Buttons in ListView each item layout - java

I have a listview and I am populating that list view from a ArrayList of custom objects.
This is the custom adapter code.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final int a=position;
FileHolder holder=null;
View row = convertView;
if(row==null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(textViewResourceId, parent, false);
holder=new FileHolder();
holder.file=files.get(position);
holder.deleteButton=(ImageButton) row.findViewById(R.id.deleteButton);
holder.downloadButton=(ImageButton) row.findViewById(R.id.downloadButton);
holder.deleteButton.setTag(holder.file);
holder.downloadButton.setTag(holder.file);
holder.fileName= (TextView) row.findViewById(R.id.fileName);
holder.fileName.setText(holder.file.getFileName());
}
else
{
holder=(FileHolder) row.getTag();
}
fPOJO=holder.file;
final AsyncCall call=new AsyncCall();
holder.downloadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MODE=0;
//call.execute(MODE);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "Delete File "+(String.valueOf(a))+" "+fPOJO.getFileName(), Toast.LENGTH_LONG).show();
MODE=1;
//call.execute(MODE);
}
});
return row;
}
public static class FileHolder{
FilesPOJO file;
TextView fileName;
ImageButton downloadButton;
ImageButton deleteButton;
}
There are two buttons one for file delete and other for file download. I have implemented on click listeners for these two buttons. The problem is when I click any button the fileName in the Toast message is different from the file name that I see on the screen display. For ex: I have 5 files with names
delete.png
upload.png
share.png
referesh.png
copy.png
and now when I click delete button corresponding to referesh.png file the toast pop ups and in that the file name is different than referesh.png.
how to resolve this issue.
EDITS:
This is how I set up this adapter
FilesAdapter adapter=new FilesAdapter(rootView.getContext(), R.layout.file_list_view_item_row, Application.files);
View header = (View) View.inflate(rootView.getContext(), R.layout.files_list_view_header_row, null);
fileListHeading.inflate(rootView.getContext(), R.layout.files_list_view_header_row, null);
filesListView.addHeaderView(header);
filesListView.setAdapter(adapter);

I think the problem is with your fPOJO variable when onClick is called it may have different value because after every getView you're changing it's value.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final int a=position;
final FileHolder holder;
View row = convertView;
if(row==null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(textViewResourceId, parent, false);
holder=new FileHolder();
holder.file=files.get(position);
holder.deleteButton=(ImageButton) row.findViewById(R.id.deleteButton);
holder.downloadButton=(ImageButton) row.findViewById(R.id.downloadButton);
holder.deleteButton.setTag(holder.file);
holder.downloadButton.setTag(holder.file);
holder.fileName= (TextView) row.findViewById(R.id.fileName);
holder.fileName.setText(holder.file.getFileName());
}
else
{
holder=(FileHolder) row.getTag();
}
final AsyncCall call=new AsyncCall();
holder.downloadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MODE=0;
//call.execute(MODE);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "Delete File "+(String.valueOf(a))+" "+holder.fileName, Toast.LENGTH_LONG).show();
MODE=1;
//call.execute(MODE);
}
});
return row;
}
Just make holder final and get you're file name from it.

You store your list item in holder, this is your problem, ListView adapter creates as much convertViews as needed to fill the screen so if you have list of 10+ elements, only few will be added to row.
First of all don't store your list element in holder, you gave adapter method called getItem(positoin) to get it.
In your holder view store only references to layout views (TextView, Buttons etc) and (if(row == null) call findViewById on them and setTag.
Then set text, listeners outside the if statement, like so:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final int a=position;
FileHolder holder=null;
View row = convertView;
if(row==null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(textViewResourceId, parent, false);
holder=new FileHolder();
holder.deleteButton=(ImageButton) row.findViewById(R.id.deleteButton);
holder.downloadButton=(ImageButton) row.findViewById(R.id.downloadButton);
holder.fileName= (TextView) row.findViewById(R.id.fileName);
row.setTag(holder);
}
else
{
holder=(FileHolder) row.getTag();
}
fPOJO= getItem(position);
final AsyncCall call=new AsyncCall();
holder.downloadButton.setOnClickListener(null);
holder.downloadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MODE=0;
//call.execute(MODE);
}
});
holder.deleteButton.setOnClickListener(null);
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "Delete File "+(String.valueOf(a))+" "+fPOJO.getFileName(), Toast.LENGTH_LONG).show();
MODE=1;
//call.execute(MODE);
}
});
return row;
}
public static class FileHolder{
TextView fileName;
ImageButton downloadButton;
ImageButton deleteButton;
}
Also you can do some code optimalization, for example don't initialize LayoutInflater in getView() method, you can do it in adapter Constructor

Related

Set button and imageview in gridview and how to set each of them listener

Hi guys I need your help. I want to set listner imageview and button in gridview and when I click to imageview app should show dialog with image and when I click to button app should do something.
like this:
enter image description here
You need to create Custom Adapter for your GridView with Custom UI with ImageView and Button, and then inside the getVieew(){} you need to make click listener for Image and button, and there you can do your action with the help of position with your array list.
here I am posting demo adapter for your reference:
here you can change TextView to Button.
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
ref:-https://caveofprogramming.com/guest-posts/custom-gridview-with-imageview-and-textview-in-android.html

button click on listview displays the same output

public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.joinlistviewitem, parent, false);
resultp = data.get(position);
name = (TextView) itemView.findViewById(R.id.personname);
name.setText(resultp.get(Joinlistview.RANK));
Button deletejoin=(Button)itemView.findViewById(R.id.delete);
deletejoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//resultp.get("userId");
// TODO Auto-generated method stub
Log.e("delete clicked", "delete clicked");
Toast.makeText(context,"clicked"+resultp.get(Joinlistview.RANK), Toast.LENGTH_SHORT).show();
}
});
return itemView;
}
I used the above code for button click on listview.If i click a button it sows the user name with its position. But it displays the same name in all position.??How to solve this??
Use getTag/setTag methods for getting current row value inside onClick as:
Button deletejoin=(Button)itemView.findViewById(R.id.delete);
deletejoin.setTag(resultp.get(Joinlistview.RANK));
And on Button Click:
Toast.makeText(context,"clicked "+ v.getTag().toString(),
Toast.LENGTH_SHORT).show();

when i scroll button position is changing in ListView

I have implemented a ListView. From ListView I am adding a products to cart. My problem is if i add a first product i am changing a button name Addtocart to Added if i scroll ListView 4th position product button name is changing to Added.
How can I resolve this ?
Here my code:
holderForGrid.AddtoCart.setTag(position);
holderForGrid.AddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
holderForGrid.AddtoCart.setText("Added");
}
});
Adapter Class:
class ListAdapter extends BaseAdapter {
public Context context;
public ListAdapter(Context a,List<BusinessCatalogVariables> listDataHeader) {
this.listDataHeader = listDataHeader;
context = a;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return catalogList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolderGrid holderForGrid;
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.catalog_list_item, null);
holderForGrid = new ViewHolderGrid(convertView);
convertView.setTag(holderForGrid);
} else {
holderForGrid = (ViewHolderGrid) convertView.getTag();
}
finalCatalogVariables Catalog = catalogList.get(position);
holderForGrid.AddtoCart.setClickable(false);
holderForGrid.AddtoCart.setTag(position);
holderForGrid.AddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int position1=(Integer)arg0.getTag();
AddedProduct = (String) holderForGrid.CatalogHeader.getText();
holderForGrid.AddtoCart.setText("Added");
}
});
return convertView;
}
private class ViewHolderGrid {
Button AddtoCart = null;
ViewHolderGrid(View convertView) {
AddtoCart = (Button) convertView.findViewById(R.id.btn_AddtoCart);
}
}
}
create boolean variable added in finalCatalogVariables class.
and create getter,setter method for this variable.
like,
class finalCatalogVariables{
// other variable and methods
boolean added;
public boolean isAdded()
{
return this.added;
}
public void setAdded(boolean added){
this.added = added;
}
}
then in getView method on click of holderForGrid.AddtoCart
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolderGrid holderForGrid;
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.catalog_list_item, null);
holderForGrid = new ViewHolderGrid(convertView);
convertView.setTag(holderForGrid);
} else {
holderForGrid = (ViewHolderGrid) convertView.getTag();
}
finalCatalogVariables catalog = catalogList.get(position);
if(catalog.isAdded()){
holderForGrid.AddtoCart.setText("Added");
}else{
holderForGrid.AddtoCart.setText("Add to cart");
}
holderForGrid.AddtoCart.setClickable(false);
holderForGrid.AddtoCart.setTag(position);
holderForGrid.AddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
catalog.setAdded(true);
int position1=(Integer)arg0.getTag();
AddedProduct = (String) holderForGrid.CatalogHeader.getText();
// holderForGrid.AddtoCart.setText("Added");
}
});
return convertView;
}
Override below mentioned two methods in your adapter class.
Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.rowlayout, null);
if (imageLoader == null)
imageLoader = Session.getInstance().getImageLoader();
//write your declaration code
List m = Yourarray.get(position);
// thumbnail image
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your code
int position1=(Integer)arg0.getTag();
AddedProduct = (String) holderForGrid.CatalogHeader.getText();
holderForGrid.AddtoCart.setText("Added");
}
});
return convertView;
}
I think the problem is that if you change the button on a view and then scroll far enough for the view to disappear, Android will assign the view position to another item in the listView.
You need to maintain somehow the status "added" or not of each product and let your adapter decide what label to display based on that.

How to start activity based on listview item click?

I have the following code but I have tried for days now and I cannot seem to figure out how to start an activity based on the listview item clicked, the result[position] does not work for start intent.
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
EDIT : If the first list item is clicked I want it to start an activity (images class) , if second clicked to start images2 class and so on..
Starting an activity based on a ListView's item click is not done in the adapter. It is done in the Activity where you show the ListView:
In your Activity:
mListView.setAdapter(mAdapter); //mAdapter is your CustomAdapter
mListView.setClickable(true);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Start the activity here.
//based on the value of position or id.
}
});
Please try this in onclick
if(position ==1){
--fire your first intent here.--
} else if(position ==2) {
-------your other intent------
}
----etc
Try something like this
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(v.getContext(),ActivityYouWantToGo.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
EDIT
Just create this method on your BaseAdapter
public void StartActivityForImages(Context context, int i){
switch (i){
case 0:
Intent Intent = new Intent(context, Image0.class);
context.startActivity(Intent);
break;
case 1:
Intent Intent2 = new Intent(context, Image1.class);
context.startActivity(Intent2);
break;
case 2:
Intent Intent3 = new Intent(context, Image3.class);
context.startActivity(Intent3);
break;
......
}
}
And on your setOnClickListener()
You call this method as follows :
StartActivityForImages(v.getContext(),position);
Toast.makeText(context, "You Clicked " + result[position], Toast.LENGTH_LONG).show();
Efficient way to do it
If you don't want to create a method and do this stuff, you could do something like this :
Create a String with the name of your next class like :
String NextActivity = getPackageName()+".Image"+position;
And then you can do something like this :
try {
String className =getPackageName()+".Image"+2;
Intent openNewIntent = new Intent(v.getContext(), Class.forName( className ) );
startActivity( openNewIntent );
} catch (ClassNotFoundException e) {
Log.d("ERRORPEW", e.getMessage());
e.printStackTrace();
}
Don't make position as a final static parameter in getView(), its a wronge way. Use below getView method to startActivity from list Item,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setTag(position);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pos = (Integer) v.getTag;
Intent i = new Intent(context, YourActivity.class);
context.startActivity(i);
}
});
return rowView;
}

Tabs are Slow/Laggy

so i have 3 tabs and i have noticed that my tabs are slow. how can i improve the performance of the tabs. The tabs have list views.
what are the ways to improve performance for the tabs
i think the problem is because i have a list view with a database and it is constantly calling the onActivityCreated and the list is updating(i m not sure)
here is my code this fragment is causing the problem
public class Jornal extends Fragment {
DataBasaJurnal dbJ;
ListView listView;
public static myAdapter myA;
ImageButton AddButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater
.inflate(R.layout.fragment_jornal, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
AddButton = (ImageButton) getActivity().findViewById(R.id.buttonAddJornal);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddToJornal.class));
}
});
listView = (ListView) getView().findViewById(R.id.listViewJurnal);
dbJ = new DataBasaJurnal(getActivity());
dbJ.open();
new Handler().post(new Runnable() {
#Override
public void run() {
myA = new myAdapter(getActivity(), dbJ.getAllRowre());
listView.setAdapter(myA);
}
});
listView.setAdapter(myA);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
int mySuperInt = dbJ.countCases() - position;
Intent myIntent = new Intent(getActivity(),
JornalListViewClick.class);
myIntent.putExtra("intVariableName", mySuperInt);
listView.setEnabled(false);
startActivity(myIntent);
}
});
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
onActivityCreated(null);
System.out.println("ok");
listView.setEnabled(true);
}
class myAdapter extends CursorAdapter {
public myAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_jornal, parent,
false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textViewMonth = (TextView) view
.findViewById(R.id.textViewDateWeek);
textViewMonth.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1))));
TextView textViewMonthDay = (TextView) view
.findViewById(R.id.textViewDateNum);
textViewMonthDay.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2))));
TextView textViewUserInput = (TextView) view
.findViewById(R.id.textViewUserInput);
textViewUserInput.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(5))));
TextView textViewUserTitle = (TextView) view
.findViewById(R.id.textViewTitelFromDB);
textViewUserTitle.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(6))));
TextView textViewLucid = (TextView) view
.findViewById(R.id.textViewhasLucid);
}
}}

Categories