How to retrieve all the values from a custom arraydapter - java

i have implemented a custom array adapter for my project,so far i am able to add and delete items from it and it displays them in the ListView too
dynamically..however i have a button in the MainActivity(that holds the ListView), that when clicked i want to display all the row items.
so far what i am getting instead of the data in the adapter after appending all values to a StringBuilder is:
com.baseadapter.C#4052b9b8com.baseadapter.C#4052f490com.baseadapter.C#40531378com.baseadapter.C#4053415
the arrayadapter and arraylist are set as below:
ArrayList<C> arrayvalues= new ArrayList<C>();
MyAdapter adapter;
adapter= new MyAdapter(MainActivity.this, R.layout.list_item,
arrayvalues);
the code for my collection class is this:
public class C {
String the_text;
public String getText() {
return the_text;
}
public void setText(String the_text) {
this.the_text = the_text;
}
public C(String the_text) {
super();
this.the_text = the_text;
}
}
the code i use to iterate over the adapter is this:
btn_done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
StringBuilder b = new StringBuilder();
for(int i=0 ; i<adapter.getCount() ; i++){
b.append(adapter.getItem(i));
}
Toast.makeText(getApplicationContext(), b.toString(), Toast.LENGTH_SHORT).show();
}
});
and the custom adapter code(just in case,though i don,t think the problem lies here):
public class MyAdapter extends ArrayAdapter<C> {
Context context;
int layoutResourceId;
ArrayList<C> data = new ArrayList<C>();
public MyAdapter(Context context, int layoutResourceId,
ArrayList<C> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
myholder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new myholder();
holder.tv = (TextView) row.findViewById(R.id.tv_num);
holder.btnDelete = (ImageButton) row.findViewById(R.id.btn_delete);
row.setTag(holder);
} else {
holder = (myholder) row.getTag();
}
C c=data.get(position);
holder.tv.setText(c.getText());
//String c=data.get(position);
//holder.tv.setText(c.g.getName());
holder.btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
data.remove(position);
notifyDataSetChanged();
}
});
return row;
}
static class myholder {
TextView tv;
ImageButton btnDelete;
}
}
what should i do to get the actual values in the adapter?ps:kindly attach code,thanks

Change your below loop code. it shall work now.
for(int i=0 ; i<adapter.getCount() ; i++)
{
C itemObject=adapter.getItem(i);
if(itelObject!=null)
b.append(itemObject.getText());
}

You should override the getItem() method in the Adapter:
#Override
public C getItem(int position) {
return data.get(position);
}
And update your loop code to get the text for "C" or override "C" toString() method as was suggested.

Related

How do I send the text of the ListView item that was clicked to my new activity?

I would like someone to click on an item in my ListView and then my new activity would start and the text of the item they clicked on should be set as the text of the TextView in my new activity. Currently with the following code, my TextView result is:
'com.example.draft.AnimalNames#31571cf'
Here is what I have in MainActivity.java:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedName = (list.getItemAtPosition(position).toString());
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("clickedName", clickedName);
startActivity(intent);
System.out.println(clickedName);
}
});
And in my new activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
Intent intent = getIntent();
String clickedName = intent.getStringExtra("clickedName");
animalName = findViewById(R.id.textView);
animalName.setText(clickedName);
}
And in my AnimalNames.java file:
public class AnimalNames {
private String animalName;
public AnimalNames(String animalName) {
this.animalName = animalName;
}
public String getanimalName() {
return this.animalName;
}
}
I don't think it's relevant to my question but here is my ListViewAdapter.java file:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList; // Declare a null variable
private ArrayList<AnimalNames> arraylist; // Declare a null array
public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
mContext = context;
this.animalNamesList = animalNamesList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AnimalNames>();
this.arraylist.addAll(animalNamesList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public AnimalNames getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_view_items, null); // Locate the TextViews in list_view_items.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(animalNamesList.get(position).getanimalName());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (AnimalNames wp : arraylist) {
if (wp.getanimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
String clickedName = (list.getItemAtPosition(position).toString());
By calling toString() method, it will give you the object reference, which is what you get in the TextView.
According to your code, if you wish to see the Animal name, you should do (and fix the method name to getAnimalName):
String clickedName = ((AnimalNames)list.getItemAtPosition(position)).getanimalName();
getItemAtPosition() returns an Object, so you need to cast it to the correct class.

How avoid refresh checkbox while expand list in android

I'm making NLevel expandable list using listview. I've added checkbox only last level data in list view. I have stuck in below scenario.
If I check checkbox then when I expand listview means checkbox gets automatically unchecked.I don't want it to be like that. If I checked checkbox it should stay checked until I uncheck manually.
Please anyone help me!! It's been two days I stuck here.
Here goes my code:
MainActivity.java
public class MainActivity extends Activity {
List<NLevelItem> list;
ListView listView;
Context context;
Button checkButton;
ArrayList<String>tempList;
CheckBox selected = null; //Make only one selection at a time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<NLevelItem>();
context = this;
checkButton = (Button)findViewById(R.id.buttons);
tempList = new ArrayList<String>();
//here we create 5 grandparent (top level) NLevelItems
//then foreach grandparent create a random number of parent (second level) NLevelItems
//then foreach parent create a random number of children (third level) NLevelItems
//we pass in an anonymous instance of NLevelView to the NLevelItem, this NLevelView is
//what supplies the NLevelAdapter with a View for this NLevelItem
Random rng = new Random();
final LayoutInflater inflater = LayoutInflater.from(this);
for (int i = 0; i < 5; i++) {
final NLevelItem grandParent = new NLevelItem(new SomeObject("GrandParent "+i),null, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.GREEN);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(grandParent);
int numChildren = rng.nextInt(4) + 1;
for (int j = 0; j < numChildren; j++) {
NLevelItem parent = new NLevelItem(new SomeObject("Parent "+j),grandParent, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.YELLOW);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(parent);
int children = rng.nextInt(3)+1;
for(int x=0; x<children;x++){
final NLevelItem childs = new NLevelItem(new SomeObject("Parent1 "+x),parent, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.BLUE);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(childs);
int grandChildren = rng.nextInt(5)+1;
for( int k = 0; k < grandChildren; k++) {
NLevelItem child = new NLevelItem(new SomeObject("child "+k),childs, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.check_list, null);
TextView tv = (TextView) view.findViewById(R.id.checktextView);
final String name = (String) ((SomeObject) item.getWrappedObject()).getName();
final CheckBox checkBox = (CheckBox)view.findViewById(R.id.check);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selected != null){ //Edit
selected.setChecked(false);
}
selected = checkBox; //Edit
if(checkBox.isChecked()){
tempList.add((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
else {
tempList.remove((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
}
});
//tv.setBackgroundColor(Color.GRAY);
tv.setText(name);
return view;
}
});
list.add(child);
}
}
}
}
NLevelAdapter adapter = new NLevelAdapter(list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
((NLevelAdapter)listView.getAdapter()).toggle(arg2);
((NLevelAdapter)listView.getAdapter()).getFilter().filter();
}
});
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i=0;i<tempList.size();i++){
Toast.makeText(context,tempList.get(i),Toast.LENGTH_LONG).show();
}
}
});
}
class SomeObject {
public String name;
public SomeObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
NLevelAdapter.java
public class NLevelAdapter extends BaseAdapter {
List<NLevelItem> list;
List<NLevelListItem> filtered;
public void setFiltered(ArrayList<NLevelListItem> filtered) {
this.filtered = filtered;
}
public NLevelAdapter(List<NLevelItem> list) {
this.list = list;
this.filtered = filterItems();
}
#Override
public int getCount() {
return filtered.size();
}
#Override
public NLevelListItem getItem(int arg0) {
return filtered.get(arg0);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return getItem(arg0).getView();
}
public NLevelFilter getFilter() {
return new NLevelFilter();
}
class NLevelFilter {
public void filter() {
new AsyncFilter().execute();
}
class AsyncFilter extends AsyncTask<Void, Void, ArrayList<NLevelListItem> > {
#Override
protected ArrayList<NLevelListItem> doInBackground(Void...arg0) {
return (ArrayList<NLevelListItem>)filterItems();
}
#Override
protected void onPostExecute(ArrayList<NLevelListItem> result) {
setFiltered(result);
NLevelAdapter.this.notifyDataSetChanged();
}
}
}
public List<NLevelListItem> filterItems() {
List<NLevelListItem> tempfiltered = new ArrayList<NLevelListItem>();
OUTER: for (NLevelListItem item : list) {
//add expanded items and top level items
//if parent is null then its a top level item
if(item.getParent() == null) {
tempfiltered.add(item);
} else {
//go through each ancestor to make sure they are all expanded
NLevelListItem parent = item;
while ((parent = parent.getParent())!= null) {
if (!parent.isExpanded()) {
//one parent was not expanded
//skip the rest and continue the OUTER for loop
continue OUTER;
}
}
tempfiltered.add(item);
}
}
return tempfiltered;
}
public void toggle(int arg2) {
filtered.get(arg2).toggle();
}
}
Thanks in advance!!
i think you need to store the checkbox state in a boolean (is checked), and reflect that on the view, when getView() is called.
1- Add boolean checked to NLevelItem :
private boolean checked = false;
//add setter: setChecked(boolean)
//add getter isChecked()
2- Use that boolean in getView() (last one where checkbox is added)
#Override
public View getView(final NLevelItem item) {
// .......
final CheckBox checkBox = (CheckBox)view.findViewById(R.id.check);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//store checkbox state, note that NLevelItem item might need to be defined with 'final'
item.setChecked(checkBox.isChecked());
if(checkBox.isChecked()){
tempList.add((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
else {
tempList.remove((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
}//onClick()
}//setOnClickListener()
//update checkbox state from the corresponding NLevelItem
checkBox.setChecked(item.isChecked());
//.......
}//getView()
-EDIT:
to select 1 item, you need to iterate all items, set checked = false, but 1
i am not sure if you have to do it on:
List<NLevelItem> list;
or
List<NLevelListItem> filtered;
in the adapter class
private void selectOnly(int position){
for(int a=0;a<list.size();a++){
if(a == position){
list.get(a).setChecked(true);
continue;
}
list.get(a).setChecked(false);
}//for loop
notifyDataSetChanged(); // to update views (checkbox state)
}
Usage: selectOnly(15);
Use ViewHolder class to set and get Tag like this:
public class ListAdapter extends BaseAdapter {
private Context con;
private List<String> dataLt;
private static LayoutInflater inflater = null;
public ListAdapter(Context context, List<String> dataList){
con = context;
dataLt = dataList;
inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return dataLt.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.list_item_search, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.textView = (TextView) vi.findViewById(R.id.textView);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
return vi;
}
public static class ViewHolder{
TextView textView;
}
}
Hope this may help.

No Solution for NullPointerException

I want to create a BaseAdapter for a ListView. From my database I get an ArrayList that contains the entries for the ListView. The onCreate Method works fine but if I click the button to insert data to the database and display it in the ListView my app crashes. I'm looking for the Solution but can't find it. Maybe you do.
Logcat says there is a NullPointerException at the point where the text of the TextView is set (LaunchActivity$CustomAdapter.getView).
LaunchActivity.java
public class LaunchActivity extends Activity {
ImageView buttonAdd;
EditText insertText;
SubjectAdapter helper;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
helper=new SubjectAdapter(this);
listView = (ListView) findViewById(R.id.listViewLaunch);
listView.setEmptyView(findViewById(R.id.emptyView));
insertText = (EditText) findViewById(R.id.editTextLaunch);
buttonAdd = (ImageView) findViewById(R.id.imageViewLaunch);
buttonAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String subject = insertText.getText().toString();
long id=helper.insertData(subject);
if(id<0){
Log.d("Personal", "insertData not successfull");
} else {
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(insertText.getWindowToken(), 0);
// loading ListView with newly added data
loadListViewData();
Log.d("Personal", "insertData successfull");
Toast.makeText(LaunchActivity.this, subject+" hinzugefĆ¼gt", Toast.LENGTH_LONG).show();
insertText.setText("");
}
}
});
loadListViewData();
}
public void loadListViewData() {
// database handler
SubjectAdapter helper = new SubjectAdapter(getApplicationContext());
// Get Data from Database and set ArrayList
ArrayList<String> list = (ArrayList<String>) helper.getData();
// Creating adapter for ListView
CustomAdapter adapter = new CustomAdapter(getApplicationContext(), list);
// attaching data adapter to ListView
listView.setAdapter(adapter);
}
class CustomAdapter extends BaseAdapter{
ArrayList<String> list = new ArrayList<String>();
Context context;
// Constructor
CustomAdapter(Context context, ArrayList<String> list){
this.list = list;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
// LayoutInflation and Recycling
if(row == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.item_listview, parent, false);
}
TextView myText = (TextView) findViewById(R.id.textList);
// Get String from ArrayList
String temp = list.get(position);
// Set Text for TextView inside ListView
myText.setText(temp);
return row;
}
}
}
If row is null you have to inflate and assign the result to row!
row = inflater.inflate(R.layout.item_listview, parent, false);
Also you'll want to get myText from row:
TextView myText = (TextView) row.findViewById(R.id.textList);
First create object of ArrayList<String> in getData() and check code below:
public void loadListViewData() {
// database handler
SubjectAdapter helper = new SubjectAdapter(getApplicationContext());
// Get Data from Database and set ArrayList
ArrayList<String> list = helper.getData();
// Creating adapter for ListView
CustomAdapter adapter = new CustomAdapter(getApplicationContext(), list);
// attaching data adapter to ListView
listView.setAdapter(adapter);
}
class CustomAdapter extends BaseAdapter{
ArrayList<String> list = null;
Context context;
// Constructor
CustomAdapter(Context context, ArrayList<String> list){
this.list = list;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
// LayoutInflation and Recycling
if(row == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.item_listview, parent, false);
}
TextView myText = (TextView) findViewById(R.id.textList);
// Get String from ArrayList
String temp = list.get(position);
// Set Text for TextView inside ListView
myText.setText(temp);
return row;
}
}
and make sure return type of getData() will be ArrayList<String>
hope it will help.

set onClickListener edit text listview

Hello at all the community,
i've a listview with a custom adapter that consists by one textview and one edit text. i set the text for the edit text into the adapter but in my acivity (listview) i want to set the onClickListener at this edit text. ive this code for my getView method
#Override
public View getView(int position, View view, ViewGroup parent) {
if(view == null) {
holder = new Holder();
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_adapter, null);
holder.textView = (TextView)view.findViewById(R.id.textView);
holder.editText = (EditText)view.findViewById(R.id.editText);
view.setTag(holder);
} else {
holder = (Holder)view.getTag();
}
holder.editText.setText("My text");
holder.textView.setText("text");
return view;
}
#Override
public boolean isEnabled(int position) {
return false;
}
i disablet the click on listview with the isEnabled method because I will not be able to click on the list. in my activity i've only the listview so if i want to set onclicklistener on the edit text of the adapter how can i do this?
public MyAdapterClass(Context context, int textViewResourceId, ArrayList<String> list) {
super(context, textViewResourceId, list);
// TODO Auto-generated constructor stub
this.list = list;
this.context = context;
}
Simply use this
holder.editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
#Override
public boolean isEnabled(int position) {
return true;
}
Please do something like :
private OnClickListener cl;
public MyAdapterClass(Context context, int textViewResourceId, ArrayList<String> list, OnClickListener cl) {
super(context, textViewResourceId, list);
// TODO Auto-generated constructor stub
this.list = list;
this.context = context;
this.cl = cl;
}
then in on getView()set it to EditText :
holder.editText.setOnClickListener(cl);
finally set set an put OnClickListener() like :
OnClickListener cl = new OnClickListener() {
#Override
public void onClick(View v) {
// Logic of Click goes Here.
}
};
where you are setting Adapter to
ListView, like :
adapter = MyAdapterClass(Activity.this, android.R.layout.simple_list_item_1, list, cl);
listView.setAdapter(adapter);

How to update listview in tab?

I have two tabs in my app and there are listviews in this tabs.
I set List data to each listvew.
I want to delete form list, and from listview when I click [x] image.
Item deleted from list In my code , but I dont know how to update listview,I use notifyDataSetChanged() in my customadapter, but not update.
Activity for first tab:
public static List<Product> mCartList;
mCartList = AllProducts.getCartList();
listViewCatalog = (ListView) findViewById(R.id.my_order_list);
mProductAdapter = new CustomListAdapter(MyOrders.this, mCartList, "", true);
listViewCatalog.setAdapter(mProductAdapter);
my Custom List Adapter:
public class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private Context mContext;
private List<Product> mProductList;
private String mType;
private boolean mShowQuantity;
public CustomListAdapter(Context context, List<Product> list, String type, boolean showQuantity) {
layoutInflater = LayoutInflater.from(context);
mContext = context;
mProductList = list;
mShowQuantity = showQuantity;
mType = type;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder item;
final int finalMPosition = position;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row, null);
item = new ViewHolder();
item.imageView = (ImageView) convertView.findViewById(R.id.product_image);
item.name = (TextView) convertView.findViewById(R.id.name);
item.pid = (TextView) convertView.findViewById(R.id.pid);
item.price = (TextView) convertView.findViewById(R.id.price);
item.description = (TextView) convertView.findViewById(R.id.description);
item.removeProduct = (ImageView) convertView.findViewById(R.id.removeProduct);
item.addToCart = (TextView) convertView.findViewById(R.id.addtocard);
item.productQuantity = (TextView) convertView.findViewById(R.id.textViewQuantity);
convertView.setTag(item);
} else {
item = (ViewHolder) convertView.getTag();
}
final Product curProduct = mProductList.get(position);
item.imageView.setImageDrawable(curProduct.imageView);
item.name.setText(curProduct.name);
item.pid.setText(curProduct.pid);
int length = curProduct.description.length();
int start = 0, end = length;
if (length >= 40) {
start = 0;
end = 40;
}
String s = curProduct.description.substring(start, end);
item.description.setText(s + "...");
item.price.setText(curProduct.price + mContext.getString(R.string.currency));
if (mShowQuantity) {
item.addToCart.setVisibility(View.GONE);
// item.productQuantity.setText("Quantity: " + AllProducts.getProductQuantity(curProduct));
item.productQuantity.setVisibility(View.GONE);
} else {
item.productQuantity.setVisibility(View.GONE);
item.removeProduct.setVisibility(View.GONE);
}
item.removeProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder ab = new AlertDialog.Builder(mContext);
ab.setTitle("Delete ");
ab.setMessage("This product will be deleted from list.").setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
curProduct.selected = false;
AllProducts.removeProduct(curProduct);
notifyDataSetChanged();
notifyDataSetInvalidated();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.create().show();
}
});
item.addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent productDetailsIntent = new Intent(mContext, ProductDetail.class);
productDetailsIntent.putExtra(AllProducts.PRODUCT_INDEX, finalMPosition);
productDetailsIntent.putExtra("type", mType);
mContext.startActivity(productDetailsIntent);
}
});
return convertView;
}
public class ViewHolder {
TextView pid;
TextView addToCart;
TextView name;
TextView price;
TextView description;
ImageView imageView;
ImageView removeProduct;
TextView productQuantity;
}
}
You can introduce notifyDataSetChanged() in the list view or you can reset the setAdapter() which the new list values , but later one will be costly
You have 2 different List, try doing this:
Create a constructor without passing a List i mean:
CustomListAdapter(MyOrders.this, "", true);
Then in the CustomListAdapter create an List Local variable and instatiate it in the constructor:
private List<Product> mProductList;
public CustomListAdapter(Context context, String type, boolean showQuantity) {
layoutInflater = LayoutInflater.from(context);
mContext = context;
mProductList = new ArrayList<Product>();
mShowQuantity = showQuantity;
mType = type;
}
then create an Add or Delete method in the CustomListAdapter:
public void AddItem(Product product){
if(null != product){
mProductList.add(product);
}
}
Then an updateMethod too:
public void update(){
mProductList.notifyDataSetChanged();
}
if notifyDatasetChanged is not working try to use this
yourlist.invalidateviews();
You need to remove that particular item from arraylist by calling
AllProducts.remove(position);
notifyDatasetChanged();
write this methode in your adapter and use it to remove perticular Item from adapter.
public void remove(int position){
mProductList.remove(position);
notifyDatasetChanged();
}
I resolved my problem.
public static void setTab(int i){
if(i==0){
mTabHost.setCurrentTab(i+1);
mTabHost.setCurrentTab(i);
}
else{
mTabHost.setCurrentTab(i-1);
mTabHost.setCurrentTab(i);
}
}
and
#Override
public void onClick(DialogInterface dialog, int which) {
curProduct.selected = false;
AllProducts.removeProduct(curProduct);
MyTabActivity.setTab(0);
}
and for second listview:
MyTabActivity.setTab(1);
The only reason it is not working for you now, is because you have two different lists. You are removing from wrong list.
So first of all, do not delete from your list. Write a method in your adapter where you remove it from list you have stored in that Adapter, and then call notifyDatasetChanged in that method.
Working with tabs in android 2.x, I found a bug in the emulator: The tabs are not correctly refreshed or removed. Alternatives is to use support library v7 which as support for action bar tabs.
Use following code to update ListView.
In order to update ListView you must have to call notifyDataSetChanged(); menthod on Adapter. See Below code.
What you did.
notifyDataSetChanged();
notifyDataSetInvalidated();
What you have to do is,
yourAdapter.notifyDataSetChanged();
Or you may use following code to refresh your list.
private List<Object> mCarlistitem= new ArrayList<Object>();
public void refreshlist()
{
mCarlistitem.clear();
for(int i=0; i< mCartList.size(); i++)
{
Object object = new Object();
mCarlistitem.add(object);
}
mProductAdapter = new CustomListAdapter(MyOrders.this, mCartList, "",true);
listViewCatalog.setAdapter(mProductAdapter);
}

Categories