I created a ListView with a custom layout for each view. I have several onClickListeners within the list view adapter for TextView items within the custom layout. The onClickListeners work within the list view adapter and I can obtain the position of the view, but when I try to make calls within the onClickListeners to methods in my activity, I get the "Cannot make a static reference to a non-static method" errors. So I started converting things to static, which made things work as intended, but I'm sure you all know it's a big mistake, which has finally caught up with me.
How the heck do I access methods in my main activity without making the methods static?? I'm new at this, so please forgive my noobish question. Thanks
partial code listing...
public class main extends Activity {
private ArrayList<DataItem> dataItems;
private DataItemAdapter aa;
private ListView dataListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dataListView = (ListView)findViewById(R.id.dataListView);
dataItems = new ArrayList<DataItem>();
int resID = R.layout.dataitem;
aa = new DataItemAdapter(this, resID, dataItems);
dataListView.setAdapter(aa);
dataListView.setItemsCanFocus(true);
populateArray();
}
public void populateArray() {
DataItem newItem = new DataItem(
"2008","Ferrari","F430","Red","ASX772"
);
dataItems.add(0, newItem);
newItem = new DataItem(
"2008","Ferrari","F430","Black","TZB123"
);
dataItems.add(0, newItem);
newItem = new DataItem(
"2009","Ferrari","F430","Red","MIDAS"
);
dataItems.add(0, newItem);
aa.notifyDataSetChanged();
}
public static void modelInfo(int pos) {
Log.i("modelInfo", "=" + pos);
}
public static void makeInfo(int pos) {
Log.i("makeInfo", "=" + pos);
}
public static void assetInfo(int pos) {
Log.i("assetInfo", "=" + pos);
}
}
public class DataItemAdapter extends ArrayAdapter<DataItem> {
private Activity activity;
private int resource;
private static LayoutInflater inflater=null;
public DataItemAdapter(Activity _activity,int _resource,List<DataItem> _items) {
super(_activity, _resource, _items);
inflater = (LayoutInflater)_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
resource = _resource;
activity = _activity;
}
public static class ViewHolder {
TextView carYear;
TextView carMake;
TextView carModel;
TextView carColor;
TextView assetTag;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(resource, null);
holder=new ViewHolder();
holder.carYear = (TextView)vi.findViewById(R.id.carYear);
holder.carMake = (TextView)vi.findViewById(R.id.carMake);
holder.carModel = (TextView)vi.findViewById(R.id.carModel);
holder.carColor = (TextView)vi.findViewById(R.id.carColor);
holder.assetTag = (TextView)vi.findViewById(R.id.assetTag);
vi.setTag(holder);
} else {
holder=(ViewHolder)vi.getTag();
}
DataItem item = getItem(position);
holder.carYear.setText(item.getCarYear());
holder.carMake.setText(item.getCarMake());
holder.carModel.setText(item.getCarModel());
holder.carColor.setText(item.getCarColor());
holder.assetTag.setText(item.getAssetTag());
holder.carYear.setTag(position);
holder.assetTag.setTag(position);
final OnClickListener makeListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
main.makeInfo(pos);
}
};
holder.carMake.setOnClickListener(makeListener);
final OnClickListener modelListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
main.modelInfo(pos);
}
};
holder.carModel.setOnClickListener(modelListener);
final OnClickListener assetListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
main.assetInfo(pos);
}
};
holder.assetTag.setOnClickListener(assetListener);
return vi;
}
why you dont attach an onItemClickListener to your ListView in your activity, instead of perform ItemClick from each inner view in the ListView
dataListView = (ListView)findViewById(R.id.dataListView);
dataItems = new ArrayList<DataItem>();
int resID = R.layout.dataitem;
aa = new DataItemAdapter(this, resID, dataItems);
dataListView.setAdapter(aa);
//attach a listener to the list view
dataListView.setOnItemClickListener (listener);
dataListView.setItemsCanFocus(true);
and inside your listener on onItemClick method you can access the activity methods.
EDIT 1:
the OnItemClickListener gives to you the following parameters, AdapterView parent, View view, int position, long
your individual TextView is a child of the view parameter and you can access to it getting the childAt... something like this:
OnItemClickListener listener = new OnItemClickListener (){
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id){
((TextView)view.findViewById(R.id.yourTextViewId)).getText();
//or do your stuff
}
}
EDIT 2:
your main activity, remember, by convention all Class name are capitalized, so main class must be Main class
public class Main extends Activity {
private ArrayList<DataItem> dataItems;
private DataItemAdapter aa;
private ListView dataListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dataListView = (ListView)findViewById(R.id.dataListView);
dataItems = new ArrayList<DataItem>();
int resID = R.layout.dataitem;
aa = new DataItemAdapter(this, resID, dataItems);
dataListView.setAdapter(aa);
dataListView.setItemsCanFocus(true);
populateArray();
}
public void populateArray() {
DataItem newItem = new DataItem(
"2008","Ferrari","F430","Red","ASX772"
);
dataItems.add(0, newItem);
newItem = new DataItem(
"2008","Ferrari","F430","Black","TZB123"
);
dataItems.add(0, newItem);
newItem = new DataItem(
"2009","Ferrari","F430","Red","MIDAS"
);
dataItems.add(0, newItem);
aa.notifyDataSetChanged();
}
public void modelInfo(int pos) {
Log.i("modelInfo", "=" + pos);
}
public void makeInfo(int pos) {
Log.i("makeInfo", "=" + pos);
}
public void assetInfo(int pos) {
Log.i("assetInfo", "=" + pos);
}
}
Now, your adapter
public class DataItemAdapter extends ArrayAdapter<DataItem> {
private Activity activity;
private int resource;
private LayoutInflater inflater=null;
public DataItemAdapter(Activity _activity,int _resource,List<DataItem> _items) {
super(_activity, _resource, _items);
inflater = (LayoutInflater)_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//i always do this way, but i dont think this is the error
//inflater = LayoutInflater.from(_activity.getBaseContext());
resource = _resource;
activity = _activity;
}
public static class ViewHolder {
TextView carYear;
TextView carMake;
TextView carModel;
TextView carColor;
TextView assetTag;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(resource, null);
holder=new ViewHolder();
holder.carYear = (TextView)vi.findViewById(R.id.carYear);
holder.carMake = (TextView)vi.findViewById(R.id.carMake);
holder.carModel = (TextView)vi.findViewById(R.id.carModel);
holder.carColor = (TextView)vi.findViewById(R.id.carColor);
holder.assetTag = (TextView)vi.findViewById(R.id.assetTag);
vi.setTag(holder);
} else {
holder=(ViewHolder)vi.getTag();
}
DataItem item = getItem(position);
holder.carYear.setText(item.getCarYear());
holder.carMake.setText(item.getCarMake());
holder.carModel.setText(item.getCarModel());
holder.carColor.setText(item.getCarColor());
holder.assetTag.setText(item.getAssetTag());
holder.carYear.setTag(position);
holder.assetTag.setTag(position);
final OnClickListener makeListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
//main.makeInfo(pos);
((Main)activity).makeInfo(pos);
}
};
holder.carMake.setOnClickListener(makeListener);
final OnClickListener modelListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
//main.modelInfo(pos);
((Main)activity).modelInfo(pos);
}
};
holder.carModel.setOnClickListener(modelListener);
final OnClickListener assetListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
//main.assetInfo(pos);
((Main)activity).assetInfo(pos);
}
};
holder.assetTag.setOnClickListener(assetListener);
return vi;
}
hope it works :)
Related
I have a class which extends ArrayAdapter<String>. I want to have a delete image button deletes the particular row.. This is my code:
public class ViewCartList extends ArrayAdapter<String> {
private String[] cart_item_name;
private String[] cart_item_quan;
private String[] cart_item_price;
private Activity context;
public ViewCartList(Activity context, String[] cartitemquan, String[] cartitemname,String[] cartitemprice){
super(context,R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan[position]);
textViewItemName.setText(cart_item_name[position]);
textViewItemPrice.setText(cart_item_price[position]);
imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
}
});
return listViewItem;
}
}
And This is my Basket class where I am using this above adapter class.
What to do if i want to remove a particular row from the ListView from that delete button given above..
public class Basket extends AppCompatActivity implements View.OnClickListener {
TextView cartview;
MyCartDatabse myDatabase;
SQLiteDatabase sql;
ContentValues cv;
String wr;
ListView list;
public static String[] quan =null;
public static String[] itemname=null;
public static String[] baseprice=null;
TextView edit_order;
public boolean imrow;
ViewCartList vc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basket);
myDatabase = new MyCartDatabse(this,"mydb",null,1);
sql = myDatabase.getWritableDatabase();
cv = new ContentValues();
list = (ListView)findViewById(R.id.listcart);
getRecords();
edit_order = (TextView)findViewById(R.id.edit_order);
edit_order.setOnClickListener(this);
}
public void getRecords(){
sql = myDatabase.getReadableDatabase();
Cursor cursor = sql.rawQuery("select * from cart ",null);
quan = new String[cursor.getCount()];
itemname = new String[cursor.getCount()];
baseprice = new String[cursor.getCount()];
int i = 0;
if(cursor.getCount()>0){
while(cursor.moveToNext()){
String uquan = cursor.getString(5);
String uname = cursor.getString(1);
String uprice = cursor.getString(4);
quan[i] = uquan;
itemname[i] = uname;
baseprice[i] = uprice;
i++;
}
vc = new ViewCartList(this,quan,itemname,baseprice);
list.setAdapter(vc);
}
else{
// Do something
}
cursor.close();
}
#Override
public void onClick(View view) {
edit_order.setText("Apply Changes");
}
}
The elegant approach for your problem is to pass an ArrayList of object to your Adapter and then handle the delete action.
So you might consider creating an object like this.
public class Cart {
public String cart_item_name;
public String cart_item_quan;
public String cart_item_price;
}
Now take an ArrayList of that class and populate the ArrayList to pass to your Adapter.
public class ViewCartList extends BaseAdapter {
private Context context;
private ArrayList<Cart> mCartList;
public ViewCartList(Context context, ArrayList<Cart> mCartList) {
this.context = context;
this.mCartList = mCartList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(mCartList.get(position).cart_item_quan);
textViewItemName.setText(mCartList.get(position).cart_item_name);
textViewItemPrice.setText(mCartList.get(position).cart_item_price);
// Remove the following and set the visibility true from the layout.
// imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Delete the row
mCartList.remove(position);
notifyDatasetChanged();
}
});
return listViewItem;
}
}
If you want to completely delete the item you should consider using List<String> instead of Array
Here is updated code for List
public class ViewCartList extends ArrayAdapter<String> {
private List<String> cart_item_name; // Use List here
private List<String> cart_item_quan; // Use List here
private List<String> cart_item_price; // Use List here
private Activity context;
public ViewCartList(Activity context, List<String> cartitemquan, List<String> cartitemname,List<String> cartitemprice){
super(context, R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan.get(position));
textViewItemName.setText(cart_item_name.get(position));
textViewItemPrice.setText(cart_item_price.get(position));
imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
cart_item_quan.remove(position);
cart_item_name.remove(position);
cart_item_price.remove(position);
notifyDataSetChanged();
}
});
return listViewItem;
}
}
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
cart_item_name[position] = null;
cart_item_quan[position]= null;
cart_item_price[position] = null;
notifydatasetchanged();
}
});
public class ViewCartList extends ArrayAdapter<String> {
private String[] cart_item_name;
private String[] cart_item_quan;
private String[] cart_item_price;
private Activity context;
public ViewCartList(Activity context, String[] cartitemquan, String[] cartitemname,String[] cartitemprice){
super(context,R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan[position]);
textViewItemName.setText(cart_item_name[position]);
textViewItemPrice.setText(cart_item_price[position]);
imcut.setVisibility(View.VISIBLE);
imcut.setTag(position);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
int pos = Integer.parseInt(view.getTag().toString());
mCartList.remove(position);
notifyDatasetChanged();
}
});
return listViewItem;
}
}
I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(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.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(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.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");
Please tell me how to add items in listview arrayadapter?
I found only how to make for standard adapter
Activity:
public class Activity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.m);
ListView lv=(ListView) findViewById(R.id.lv);
String[] Id1={"1","2","3"}, Text1={"one","two","three"};
CustomAdapter ad = new CustomAdapter(this, Id1 , Text1);
ad.setCustomListener(new LVListener() {
public void onClick(String text) {
Log.d("APP", text);
}
});
lv.setAdapter(ad);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setVisibility(View.GONE);
String[] Id2={"4","5","6"},Text2={"four","five","six"};
// add Id2 and Text2 in listview
}
});
}
}
CustomAdapter:
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] id, text;
private ListViewListener micl;
public CustomAdapter(Context context, String[] id, String[] text) {
super(context, R.layout.list, id);
this.context = context;
this.id = id;
this.text = text;
}
public void setCustomListener(ListViewListener micl) { this.micl = micl; }
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View View = inflater.inflate(R.layout.list, parent, false);
final int pos = position;
final TextView tView = (TextView) View.findViewById(R.id.textView);
tView.setText(text[pos]);
rowView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (micl != null)
micl.onClick(text[pos]);
}
});
return View;
}
}
I tried to do with notifyDatasetChanged() but nothing happened.
Please tell me how to do that.
ArrayAdapter has the add method, but in order to use it the dataset you provide to the super can not be an array, that's because the using Arrays.asList(objects), that returns an immutable list. From the documentation
Returns a List of the objects in the specified array. The size of the
List cannot be modified, i.e. adding and removing are unsupported, but
the elements can be set. Setting an element modifies the underlying
array.
I am adding one button per row to show off map in that row in array adapter . I want to get hold of value in that row when that button is clicked . How can I get those values on click of button .
my class:
public class MyListAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<HashMap<String, ArrayList<String>>> pjclist;
private final ArrayList<PermJorneyCycleBean> pjcarraylist ;
String villagename;
int black = Color.WHITE;
float village = 20f;
float depot = 16f;
int red = Color.RED;
int count;
ArrayList<String> Deoptname;
public MyListAdapter(Context context,ArrayList<HashMap<String, ArrayList<String>>>pjcretrivelist, String [] villagename,ArrayList<PermJorneyCycleBean>itempjcarraylist) {
// public MyListAdapter(Context context,ArrayList<PermJorneyCycleBean> pjcretrivelist, String [] villagename) {
super(context, R.layout.scheduleplan,villagename);
this.context = context;
this.pjcarraylist=itempjcarraylist;
this.pjclist=pjcretrivelist;
count =pjcretrivelist.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowView1=null;
LinearLayout rowView=null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position<count){
rowView1= (LinearLayout) inflater.inflate(R.layout.scheduleplan, null, true);
rowView= (LinearLayout) rowView1.findViewById(R.id.plan);
HashMap<String, ArrayList<String>> depotlistnew = new HashMap<String, ArrayList<String>>();
depotlistnew = pjclist.get(position);
Iterator<Entry<String, ArrayList<String>>> itr = depotlistnew.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pairs = (Map.Entry) itr.next();
villagename = pairs.getKey().toString();
createNewRow(rowView, villagename, black, village);
Deoptname = (ArrayList) pairs.getValue();
for (int i = 0; i < Deoptname.size(); i++) {
String depotname = new String();
depotname = Deoptname.get(i);
createNewRow(rowView, depotname, red, depot);
}
}
Button mapbutton = createbutton(rowView, "Locate on Map");
mapbutton.setTag(position);
mapbutton.setClickable(true);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to depot map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count){
rowView1 = (LinearLayout) inflater.inflate(R.layout.schedulemap, null, true);
Button villagebutton = (Button)rowView1.findViewById(R.id.getBack);
villagebutton.setClickable(true);
villagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "This is for Map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count+1)
{
rowView1 = (LinearLayout) inflater.inflate(R.layout.scheduleplanlast, null, true);
Button backbutton = (Button)rowView1.findViewById(R.id.getBackHome);
backbutton.setClickable(true);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to test it",Toast.LENGTH_LONG).show();
}
});
}
return rowView1;
}
public void createNewRow(LinearLayout ll1, String value, Integer color,float size) {
TextView tv = new TextView(ll1.getContext());
tv.setTextColor(color);
tv.setTextSize(size);
tv.setText(value);
ll1.addView(tv);
}
public Button createbutton(LinearLayout ll1, String value) {
Button backbutton = new Button(ll1.getContext());
backbutton.setText(value);
backbutton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(backbutton);
return backbutton;
}
public TextView createTextView(LinearLayout ll1, String value){
TextView lattextview = new TextView(ll1.getContext());
lattextview.setVisibility(0);
lattextview.setText(value);
lattextview.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(lattextview);
return lattextview;
}
}
I am not able to get hold of position on click of those buttons .
For your reference i have the following code snippet for button click on Array Adapter
class MySimpleArrayAdapter extends ArrayAdapter<String> {
private Context context;
public MySimpleArrayAdapter(Context context) {
super(context, R.layout.buddy_list);
this.context = context;
}
public int getCount() {
return speedList.size();
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.speeddial_list, null);
}
TextView name = (TextView) rowView.findViewById(R.id.Name);
TextView buddyId = (TextView) rowView.findViewById(R.id.sipid);
Button btn = (Button)rowView.findViewById(R.id.speeddialbtn);
name.setText(speedList.get(position).getName());
buddyId.setText(speedList.get(position).getNumber());
btn.setText(Integer.toString(speedList.get(position).getSPDIndex()));
/*name.setText(names.get(position).toString());
buddyId.setText(buddyIds.get(position).toString());
btn.setText(numberButton.get(position).toString());*/
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (!speedList.get(0).getName().equals(" No SpeedDial Found")) {
registerForContextMenu(getListView());
getListView().showContextMenu();
} else {
unregisterForContextMenu(getListView());
}
selected_name_fromlist = speedList.get(position).getName();
selected_number_fromlist = speedList.get(position).getNumber();
System.out.println(" selected :" + selected_name_fromlist);
}
});
return rowView;
}
}
Here is a good Handling Button clicks in a ListView Row tutorial.
i created custom listview with text and two buttons, i set up arraylist and adapter but my listview is showing every element as last, for ex. if i add 3 elements: "text1","text2","text3" my listview shows "text3", "text3" "text3" and i dont have any idea why.
private ListView lista;
private List<Piosenka> listaPiosenek;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
lista = (ListView) findViewById(R.id.listView1);
lista.setClickable(true);
}
public void update_listy() throws MalformedURLException, IOException
{
final List<Piosenka> listaPiosenek = new ArrayList<Piosenka>();
listaPiosenek.add(new Piosenka("text1"));
listaPiosenek.add(new Piosenka("text2"));
listaPiosenek.add(new Piosenka("text3"));
PiosenkaAdapter adapter = new PiosenkaAdapter(this, listaPiosenek);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long index)
{
System.out.println("sadsfsf");
}
});
lista.setAdapter(adapter);
}
Edit: PiosenkaAdapter code
public class PiosenkaAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<Piosenka> listapiosenek;
public PiosenkaAdapter(Context context, List<Piosenka> listapiosenek) {
this.context = context;
this.listapiosenek = listapiosenek;
}
public int getCount() {
return listapiosenek.size();
}
public Object getItem(int position) {
return listapiosenek.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Piosenka element = listapiosenek.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_element, null);
}
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Button btnPobierz = (Button) convertView.findViewById(R.id.btnPobierz);
btnPobierz.setFocusableInTouchMode(false);
btnPobierz.setFocusable(false);
btnPobierz.setTag(element);
Button btnPlay = (Button) convertView.findViewById(R.id.btnPlay);
btnPlay.setFocusableInTouchMode(false);
btnPlay.setFocusable(false);
btnPlay.setOnClickListener(this);
btnPlay.setTag(element);
// btnRemove.setId(position);
return convertView;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPobierz:
Piosenka entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
case R.id.btnPlay:
entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
}
}
}
Try this...
lista.setAdapter(adapter);
adapter.notifyDataSetChanged();
Can you paste you PiosenkaAdapter's code?
I don't know your language, but the Piosenka variable is fetched correctly in getView()
Piosenka element = listapiosenek.get(position);
But this looks strange to me
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Piosenka.getTytul() looks to me as a static method call, where you should do a regular method call to element.getTytul() instead.