I am a newbie in android programming and I created a image gallery app to display images on SD card in grid view . It's working fine but I want to select any image and display it on full screen in another activity. I guess its easier when using a String array but I am using an array list to hold/store images. So I don't know how to display images on full screen using that. Can anyone help me out?
ImageGallery.java
public class ImageGallery extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gv_folder = (GridView)findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
PhotosActivity.java
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gridView = (GridView)findViewById(R.id.gv_folder);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, al_images,int_position);
gridView.setAdapter(adapter);
final ImageView imageView = (ImageView) findViewById(R.id.iv_image);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
GridViewAdapter.java
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
FullImageActivity.java
public class FullImageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
// Selected image id
int position1 = i.getExtras().getInt("id");
ImageView imageView = (ImageView) findViewById(R.id.fullImage);
imageView.setImageResource();
}
}
Pass the image path to the second Activity, in your case it is "file://" + al_images.get(int_position).getAl_imagepath().get(position).
Then from the second activity, you can simply display it using the Glide
Glide.with(context).load(path)
.into(imageView);
Related
I am really new to android development and I have been trying to create an Image gallery app. Everything is working fine except when I am swiping to display next image its not displaying images in correct order but in random order. Also it is displaying images from a specific folder.
What should I do to solve this problem??
ImageGallery.java:
public class ImageGallery extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gv_folder = (GridView)findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(ImageGallery.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale( ImageGallery.this,
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions( ImageGallery.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText( ImageGallery.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
PhotosActivity.java:
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gridView = (GridView)findViewById(R.id.gv_folder);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, al_images,int_position);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String abc = "file://" + al_images.get(int_position).getAl_imagepath().get(position);
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
i.putExtra("abc",abc);
startActivity(i);
}
});
}
}
FullImageActivity.java:
public class FullImageActivity extends AppCompatActivity {
ImageSwitcher Switch;
ImageView images;
float initialX;
private Cursor cursor;
private int int_position;
ArrayList<String> al_path = new ArrayList<>();
int position1,position;
String absolutePathOfImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
Switch = (ImageSwitcher) findViewById(R.id.imageSwitcher);
Intent i = getIntent();
images = (ImageView) findViewById(R.id.fullImage);
// Selected image id
position = i.getExtras().getInt("id");
Bundle extras = getIntent().getExtras();
String value = extras.getString("abc");
Glide.with(FullImageActivity.this)
.load(value)
.skipMemoryCache(false)
.into(images);
int_position = getIntent().getIntExtra("value", 0);
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = event.getX();
break;
case MotionEvent.ACTION_UP:
float finalX = event.getX();
if (initialX > finalX)
{
Glide.with(FullImageActivity.this)
.load(al_path.get(int_position+1))
.skipMemoryCache(false)
.into(images);
Switch.showNext();
Toast.makeText(getApplicationContext(), "Next Image",
Toast.LENGTH_LONG).show();
int_position ++;
}
else
{
if(int_position> 0)
{
cursor.moveToPosition(int_position);
Glide.with(FullImageActivity.this)
.load(al_path.get(int_position))
.skipMemoryCache(false)
.into(images);
Toast.makeText(getApplicationContext(), "previous Image",
Toast.LENGTH_LONG).show();
Switch.showPrevious();
int_position= int_position-1;
}
else
{
Toast.makeText(getApplicationContext(), "No More Images To Swipe",
Toast.LENGTH_LONG).show();
}
}
break;
}
return false;
}
}
GridViewAdapter.java:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
I want to fetch 10 records in listview and other records fetch on scroll to bottom. I'm a new in this please help me. Here's my fragment of Java code and adapter:
Latest_Fragment.java
private static final String TAG = LatestFragment.class.getSimpleName();
// Movies json url
private static final String url = "http://abc.news/android/lastest.php?page=1";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private List<Movie> additems;
private ListView listView;
private CustomListAdapter adapter;
boolean flag_loading = true;
private static String Title="title";
private static String Genre="genre";
private static String Rating="rating";
private static String Sec_id="secid";
private static String Category="category";
private static String bitmap="thumbnailUrl";
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.latest_layout, container, false);
//getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent2 = new Intent();
getActivity().setResult(Activity.RESULT_OK, intent2);
list = (ListView) v.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
list.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// flag_loading = false;
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setSec_id(obj.getString("sec_id"));
movie.setCategory(obj.getString("category"));
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(obj.getString("rating"));
// movie.setYear(obj.getString("releaseYear"));
movie.setGenre(obj.getString("genre"));
// Genre is json array
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError){
Toast.makeText(getActivity().getBaseContext(), "Bummer..There's No Internet connection!", Toast.LENGTH_LONG).show();
}
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), News_Detail.class);
bitmap = ((Movie)movieList.get(position)).getThumbnailUrl();
intent.putExtra("images", bitmap);
final String names = ((TextView) view.findViewById(R.id.title)).getText().toString();
intent.putExtra(Title, names);
String genredescription = ((TextView) view.findViewById(R.id.genre)).getText().toString(); //must for send data
intent.putExtra(Genre, genredescription);
String date = ((TextView) view.findViewById(R.id.rating)).getText().toString();
intent.putExtra(Rating, date);
startActivity(intent);
}
});
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
customlistadapter.java
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
// first row layout change below code is working
#Override
public int getViewTypeCount() { return 2; }
//if remove below code then chage layout randomly
#Override
public int getItemViewType(int position) {
if (position == 0) {
return 0;
} else {
return 1;
}
}
// first row layout change above code is working
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
if(position == 0) {
convertView = inflater.inflate(R.layout.list_row2, null);
}else
{
convertView = inflater.inflate(R.layout.list_row, null);
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
final TextView sec_id = (TextView) convertView.findViewById(R.id.sec_id);
final TextView category = (TextView) convertView.findViewById(R.id.category);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView rating = (TextView) convertView.findViewById(R.id.rating);
TextView genre = (TextView) convertView.findViewById(R.id.genre);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
rating.setText(m.getRating());
// genre
genre.setText(m.getGenre());
sec_id.setText(m.getSec_id());
category.setText(m.getCategory());
// release year
// year.setText(m.getYear());
ImageView btn = (ImageView) convertView.findViewById(R.id.share);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "\n" + "\n" + "http://vasundharadeep.news/News/"+sec_id.getText().toString()+"/"+category.getText().toString());
activity.startActivity(intent);
}
});
return convertView;
}
}
Abstract class
public abstract class HidingScrollListener implements AbsListView.OnScrollListener {
private static final int HIDE_THRESHOLD = 15;
public boolean controlsVisible = true;
public int scrolledDistance = 0;
public int previousTotal = 0;
public boolean loading = true;
public int current_page = 1;
public LinearLayoutManager mLinearLayoutManager;
private int visibleThreshold = 2;
public HidingScrollListener(LinearLayoutManager layoutManager) {
this.mLinearLayoutManager = layoutManager;
}
#Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
// int firstVisibleItem =firstVisibleItem;
if (firstVisibleItem == 0) {
if (!controlsVisible) {
onShow();
controlsVisible = true;
}
} else {
if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
onHide();
controlsVisible = false;
scrolledDistance = 0;
} else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
onShow();
controlsVisible = true;
scrolledDistance = 0;
}
}
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
current_page++;
onLoadMore(current_page);
loading = true;
}
}
public abstract void onHide();
public abstract void onShow();
public abstract void onLoadMore(int current_page);
}
// Current Page getter setter
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
Check it out below code
public class MyFragment extends Fragment implements OnScrollListener {
private ListView listView;
private ArrayList<DataModel> dataList = new ArrayList<DataModel>();
private boolean mHasRequestedMore;
onCreateView(…..){
listView = view.findViewById();
listView.setonScrollLestener(this);
callWebservice();
}
#Override
public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
if (!mHasRequestedMore) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (lastInScreen >= totalItemCount) {
mHasRequestedMore = true;
callWebservice();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState{}
I have RecycleView List with an ExpandableLinearLayout ( i use a third party library). In my ExpandableLinearLayout I have a ListView, with an custom ArrayAdapter.
I set my Adapter in the RecycleViewAdapter and submit one ArrayList that contains 4 ArrayLists and the position from the onBindViewHolder() method , too fill the different sections in the RecycleView.
I pass the data in the correct section but i get only the first element of each ArrayList. I Log some stuff and the problem is the position from the getView method in my ArrayAdapter is always 0..
I search and played around a bit but i didnt found a solution.. I hope somebody can help..
Sorry for my bad grammar
This is my RecycleView :
public class EmergencyPassAdapter extends RecyclerView.Adapter<EmergencyPassAdapter.EmergencyPassViewHolder> {
private static final String LOG_TAG = EmergencyPassAdapter.class.getName();
private Context context;
private ArrayList<CellInformation> cellInformations;
private SparseBooleanArray expandState = new SparseBooleanArray();
EmergencyPassExpandAdapter emergencyPassExpandAdapter;
public EmergencyPassAdapter(Context context, ArrayList<CellInformation> cellInformations) {
this.context = context;
this.cellInformations = cellInformations;
for (int i = 0; i < cellInformations.size(); i++) {
expandState.append(i, false);
}
}
#Override
public EmergencyPassViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_emergency_pass, parent, false);
return new EmergencyPassViewHolder(view);
}
#Override
public void onBindViewHolder(final EmergencyPassViewHolder holder, final int position) {
CellInformation cellInformation = cellInformations.get(position);
holder.imageViewIcon.setImageDrawable(cellInformation.getIcon());
holder.textViewTitle.setText(cellInformation.getTitel());
emergencyPassExpandAdapter = new EmergencyPassExpandAdapter(context, EmergencyPassExpandDetailFactory.getExpandCellInformation(context), position);
holder.listView.setAdapter(emergencyPassExpandAdapter);
if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_emergency_contacts))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_legal_guardian))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
}
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!holder.expandableLinearLayout.isExpanded()) {
Log.i(LOG_TAG, "expand");
holder.expandableLinearLayout.expand();
} else {
Log.i(LOG_TAG, "collapse");
holder.expandableLinearLayout.collapse();
}
}
});
}
#Override
public int getItemCount() {
return cellInformations.size();
}
public static class EmergencyPassViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle, textViewExpandText;
ImageView imageViewIcon, imageViewArrow;
ExpandableLinearLayout expandableLinearLayout;
RelativeLayout relativeLayout;
ListView listView;
public EmergencyPassViewHolder(View itemView) {
super(itemView);
textViewTitle = (TextView) itemView.findViewById(R.id.cell_emergency_pass_title_tv);
textViewExpandText = (TextView) itemView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
imageViewIcon = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_icon_iv);
imageViewArrow = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_arrow_icon_iv);
expandableLinearLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.cell_emergency_pass_arrow_expandable_list);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.cell_emergency_pass_root_rl);
listView = (ListView) itemView.findViewById(R.id.cell_emergency_pass_expand_lv);
}
}
}
My ArrayAdapter
public class EmergencyPassExpandAdapter extends ArrayAdapter<CellExpandInformation>{
private static final String LOG_TAG = EmergencyPassExpandAdapter.class.getName();
private ArrayList<CellExpandInformation> values;
private int checkPosition;
private Context context;
public EmergencyPassExpandAdapter(Context context, ArrayList<CellExpandInformation> values, int checkPosition) {
super(context, -1, values);
this.context = context;
this.values = values;
this.checkPosition = checkPosition;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i(LOG_TAG,"View");
Log.i(LOG_TAG,"Position: " + position);
EmergencyPassExpandViewHolder viewHolder;
CellExpandInformation cellExpandInformation = values.get(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.cell_emergency_pass_expand, parent, false);
viewHolder = new EmergencyPassExpandViewHolder();
viewHolder.textViewExpandTitle = (TextView) convertView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
convertView.setTag(viewHolder);
} else {
viewHolder = (EmergencyPassExpandViewHolder) convertView.getTag();
}
Log.i(LOG_TAG,"CheckPosition: " + checkPosition);
if (values != null) {
if (checkPosition == 0) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getMedications().get(position).getMedicationName());
Log.i(LOG_TAG, "Medications: " + cellExpandInformation.getMedications().get(position).getMedicationName());
} else if (checkPosition == 1) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getAllergies().get(position).getAllgergiesName());
} else if (checkPosition == 2) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getDiseases().get(position).getDiseasesName());
} else if (checkPosition == 3) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getLegalGuradian().get(position).getGuradianName());
} else if (checkPosition == 4) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getEmergencyContact().get(position).getEmergencyContactName());
}
}
for(int i = 0; i < cellExpandInformation.getMedications().size(); i++){
Log.i(LOG_TAG,"Medis: " + cellExpandInformation.getMedications().get(i).getMedicationName());
}
return convertView;
}
static class EmergencyPassExpandViewHolder {
TextView textViewExpandTitle;
ImageView imageViewPhone, imageViewEmail, imageViewAdd;
}
}
I have a simple task that is to take string input from Dialog then add it to listview with checkbox .
What happening is that , I entered test through dialog but it is not displaying after adding and also code doesn't have any error during runtime .
MainActivity.java
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
ListView list;
MyCustomAdapter dataAdapter ;
List<SubTasksModel> subTasksModelArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.heading);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
subTasksModelArrayList = new ArrayList<SubTasksModel>();
list = (ListView) findViewById(R.id.list);
dataAdapter = new MyCustomAdapter(this , R.layout.child_row_add_subtask , subTasksModelArrayList);
list.setAdapter(dataAdapter);
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.add_subtask_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.et_task);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Add Subtask", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
/*subTasksModelArrayList = new ArrayList<SubTasksModel>();*/
fillData(editText.getText().toString() , false);
Utility.setListViewHeightBasedOnChildren(list);
}
})
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void fillData(String s, boolean b) {
final SubTasksModel model = new SubTasksModel();
model.setTask(s);
model.setSelected(b);
subTasksModelArrayList.add(model);
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends BaseAdapter {
public List<SubTasksModel> subTasksModelList;
Context context;
private LayoutInflater mInflater;
public MyCustomAdapter(Context context, int resource, List<SubTasksModel> objects) {
this.context=context;
this.subTasksModelList=objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
LinearLayout linearLayout;
TextView task;
CheckBox cb;
}
#Override
public int getCount() {
return 0;
}
#Override
public SubTasksModel getItem(int position) {
return subTasksModelList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.child_row_add_subtask, null);
holder.task = (TextView) convertView.findViewById(R.id.tv_subtask);
holder.cb = (CheckBox) convertView.findViewById(R.id.cb_subtask);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayout01);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
final int pos = position;
holder.task.setText(subTasksModelList.get(position).getTask());
holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
subTasksModelList.get(pos).setSelected(isChecked);
}
});
/*Log.d("ArrayList"," : "+ subTasksModelList);
SubTasksModel subTasksModel = subTasksModelList.get(position);
holder.task.setText(subTasksModel.getTask());
holder.cb.setChecked(subTasksModel.isSelected());
holder.cb.setTag(subTasksModel);*/
return convertView;
}
}
SubTaskModel.java
public class SubTasksModel {
String task = "";
boolean selected = false;
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
// Utility class is just to set height of listview inside scrollview.
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
Log.d("Params are : " , " : "+ params);
listView.requestLayout();
}
}
#Override
public int getCount() {
return 0;
}
replace it with
#Override
public int getCount() {
return subTasksModelList.size();
}
I have a RecyclerViewAdapter which fill my List with StoreName,image etc, I had model for listitems.ok, I'm migrating from a ListView to recylerview. i want to click on any item and get that items data(like Store name) and intent to another activity, now problem is that when i click on item it give wrong storename. but when i was using onItemclickListener that provide correct input. i will show u..
This my RecyclerViewAdapter.
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private List<StoresItem> mDataset;
private static MyClickListener myClickListener;
Context context;
Bitmap xx;
public MyRecyclerViewAdapter(Context context, List<StoresItem> myDataset)
{
mDataset = myDataset;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtStoreName,txtDeliveryTime;
ImageView storeImg;
RatingBar ratingBar;
public DataObjectHolder(View itemView)
{
super(itemView);
txtStoreName = (TextView) itemView.findViewById(R.id.txtStoreName);
txtDeliveryTime = (TextView) itemView.findViewById(R.id.txtDeliveryTime);
storeImg = (ImageView) itemView.findViewById(R.id.storeImg);
ratingBar=(RatingBar)itemView.findViewById(R.id.ratingBar);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
myClickListener.onItemClick(getLayoutPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener)
{
this.myClickListener = myClickListener;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.storelist, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position)
{
ImageView storeImg;
holder.txtStoreName.setText(mDataset.get(position).gettxtStoreName().toString());
holder.txtDeliveryTime.setText(mDataset.get(position).gettxtDeliveryTime().toString());
holder.ratingBar.setFocusable(false);
int loader = R.drawable.image;
String url = mDataset.get(position).getstoreImg().toString();
ImageLoader imgLoader = new ImageLoader(context);
imgLoader.DisplayImage(url,loader,holder.storeImg);
}
public void addItem(StoresItem dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener
{
public void onItemClick(int position, View v);
}
public Object getItem(int position)
{
return mDataset.get(position);
}
#Override
public long getItemId(int position)
{
return mDataset.indexOf(getItem(position));
}
#Override
public int getItemViewType(int position)
{
return super.getItemViewType(position);
}
}
This is my StoreModel.
public class StoresItem
{
private String txtStoreName, txtDeliveryTime, storeImg;
public StoresItem(String txtStoreName, String txtDeliveryTime,String storeImg)
{
this.txtStoreName = txtStoreName;
this.txtDeliveryTime = txtDeliveryTime;
this.storeImg = storeImg;
}
public String gettxtStoreName()
{
return txtStoreName;
}
public void settxtStoreName(String txtStoreName)
{
this.txtStoreName = txtStoreName;
}
public String gettxtDeliveryTime()
{
return txtDeliveryTime;
}
public void settxtDeliveryTime(String txtDeliveryTime)
{
this.txtDeliveryTime = txtDeliveryTime;
}
public String getstoreImg()
{
return storeImg;
}
public void setstoreImg(String storeImg)
{
this.storeImg = storeImg;
}
}
And this is my Fragment where i using onclickListner.
public class RecylerFragment extends Fragment
{
ListView storeListView;
List<StoresItem> storesItem;
StoresListAdaptor adapter;
String selectedStore;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static final String[] storeNameGrocery = new String[]
{
"Value Store", "Grocery Mart", "Wild Water-Sadar Bazar", "Store99","Coco-Buzz", "Wild Water - Sector 46"
};
public static final String[] storeNameFresh = new String[]
{
"Mother's Love", "The Flower Shop", "Flower N Emotions"
};
public static final String[] storeNameElectronics = new String[]
{
"Molife-Sheetla Mata Road", "Apple Store- Shona Road", "Vandana Communication", "Samsung Store","JMD Mobile - Sector 14", "Sterling - Gurgaon"
};
public static final String[] storeNameVegetable = new String[]
{
"Fortune Store", "Best Food - Mega Mall", "Sadar Bazar", "MTR Store","Coco-Buzz"
};
public static final String[] deliveryTime = new String[]
{
"20min", "10min", "9min", "15min","30min", "1hr","20min","20min", "10min", "9min", "15min","30min", "1hr","20min" };
private static final String KEY_POSITION="position";
public static final String[] iconsUrl = new String[]
{
"http://icons.iconarchive.com/icons/femfoyou/angry-birds/96/angry-bird-icon.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/96/grimace-icon.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
};
public RecylerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.activity_recycler_view, container, false);
Bundle bundle = this.getArguments();
String myString = bundle.getString("page_position");
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
// Code to Add an item with default animation
//((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
storesItem = new ArrayList<StoresItem>();
if(myString.equals("999")) {
for (int i = 0; i < storeNameGrocery.length; i++) {
StoresItem item = new StoresItem(storeNameGrocery[i], "Delivery Time " + deliveryTime[i],iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("888")) {
for (int i = 0; i < storeNameFresh.length; i++) {
StoresItem item = new StoresItem(storeNameFresh[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("777")) {
for (int i = 0; i < storeNameElectronics.length; i++) {
StoresItem item = new StoresItem(storeNameElectronics[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("666")) {
for (int i = 0; i < storeNameVegetable.length; i++) {
StoresItem item = new StoresItem(storeNameVegetable[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
mAdapter = new MyRecyclerViewAdapter(getActivity(), storesItem);
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
**#Override
public void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener()
{
#Override
public void onItemClick(int position, View v)
{
System.out.println(" Clicked on Item " + position);
StoresItem storesItems = (StoresItem) ((MyRecyclerViewAdapter) mAdapter).getItem(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
}**
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
okk...there is something wrong with recyclerviews-onItemclicklister because listviews - onItemCLicklistner()
provide Adapterview and i can simply get Item by using parent.getItematposition(position) like this.
storeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
StoresItem storesItems = (StoresItem) parent.getItemAtPosition(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
Can Any one tell me whats the reason why getWrong StoreName.??
You are using myClickListener.onItemClick(getLayoutPosition(), v); you have to use myClickListener.onItemClick(getAdapterPosition(), v);