Android ListView items disappear when scrolling - java

I've loaded some pictures into a ListView using an adapter. When a user clicks on any row of the list I'm showing a checkmark at the end:
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
List<String> names,facebookbid;
String sent;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, List<String> n,List<String> fid,String s) {
activity = a;
names=n;
facebookbid=fid;
sent=s;
inflater = (LayoutInflater)activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),"p");
}
#Override
public int getViewTypeCount() {
if (getCount() != 0)
return getCount();
return 1;
}
public int getCount() {
return facebookbid.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public class ViewHolder{
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
convertView=null;
final ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = inflater.inflate(R.layout.planners_friends_listrow, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView)convertView.findViewById(R.id.planner_friend_image);
holder.checkmark=(ImageView)convertView.findViewById(R.id.checkmark);
holder.friendsrow=(RelativeLayout)convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag( holder );
}
else
holder=(ViewHolder)convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if(sent.equals("planners"))
{link=facebookbid.get(position);
}
else
{
link="https://graph.facebook.com/"+facebookbid.get(position)+"/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a=isNetworkConnected();
if(a==true)
{
if(sender.equals("settings"))
{
}
else if(sender.equals("savethedate"))
{
if(sid.contains(facebookbid.get(position)))
{
if(sid.contains("_"))
{
sid=sid.replace("_"+facebookbid.get(position), "");
}
else
{
sid=sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size()-1);
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.GONE);
}
else
{
if(sid.isEmpty())
{
sid=sid+facebookbid.get(position);
}
else
{
sid=sid+"_"+facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.VISIBLE);
}
}
else
{
String friendname=names.get(position);
String friendid=facebookbid.get(position);
String friendgender=gender.get(position);
Intent resultIntent = new Intent(Friends.this,Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if(sender.equals("planner"))
{
resultIntent.putExtra("plannerid",friendid);
resultIntent.putExtra("imageurl","https://graph.facebook.com/"+friendid+"/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
else
{
resultIntent.putExtra("plannerid","");
resultIntent.putExtra("imageurl","");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
}
else
{
Toast.makeText(getApplicationContext(),"No internet connection",Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The problem is: When the ListView is scrolled, the checkmark icon simply disappears. What am I doing wrong?

Looking at your code you set the Visibility of the checkmark when the user clicks on one of the items which then shows / hides the item. Now when the user scrolls the items are recycled and you dont have any code to check if the item has been checked or not.
So in short you need something that basically says
if (checked) {
//set visibility of the checkmark to visible
} else {
//set visibility of the checkmark to gone
}

First you need to change getView method as don't reinitialize convertView as null remove below line from getView
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener {
private Activity activity;
List<String> names, facebookbid;
String sent;
public ImageLoader imageLoader;
private int size = 0;
private HashMap<String, Boolean> mapClickStatus;
public LazyImageLoadAdapter(Activity a, List<String> n, List<String> fid, String s) {
activity = a;
names = n;
facebookbid = fid;
sent = s;
mapClickStatus = new HashMap<String, Boolean>();
if (facebookbid != null)
size = facebookbid.size();
// Give total size of the list item to getCount method
imageLoader = new ImageLoader(activity, "p");
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
/*********
* Create a holder Class to contain inflated xml file elements
*********/
public class ViewHolder {
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// convertView=null;
//It should not be null every time
final ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView) convertView.findViewById(R.id.planner_friend_image);
holder.checkmark = (ImageView) convertView.findViewById(R.id.checkmark);
holder.friendsrow = (RelativeLayout) convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if (sent.equals("planners")) {
link = facebookbid.get(position);
} else {
link = "https://graph.facebook.com/" + facebookbid.get(position) + "/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
// set the visibility of CheckMark ImageView based on the click status.
if (mapClickStatus.get(facebookbid.get(position)))
holder.checkmark.setVisibility(View.VISIBLE);
else
holder.checkmark.setVisibility(View.GONE);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a = isNetworkConnected();
/// I dont know about the unique ID field in this so i took facebookbid.get(position) as a key
// To set click status of row item in hashmap.
mapClickStatus.put(facebookbid.get(position),
mapClickStatus.containsKey(facebookbid.get(position)) ? false : true);
if (a == true) {
if (sender.equals("settings")) {
} else if (sender.equals("savethedate")) {
if (sid.contains(facebookbid.get(position))) {
if (sid.contains("_")) {
sid = sid.replace("_" + facebookbid.get(position), "");
} else {
sid = sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size() - 1);
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.GONE);
} else {
if (sid.isEmpty()) {
sid = sid + facebookbid.get(position);
} else {
sid = sid + "_" + facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.VISIBLE);
}
// TO refresh view with updated checkmark status
notifyDataSetChanged();
} else {
String friendname = names.get(position);
String friendid = facebookbid.get(position);
String friendgender = gender.get(position);
Intent resultIntent = new Intent(Friends.this, Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if (sender.equals("planner")) {
resultIntent.putExtra("plannerid", friendid);
resultIntent.putExtra("imageurl", "https://graph.facebook.com/" + friendid + "/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
} else {
resultIntent.putExtra("plannerid", "");
resultIntent.putExtra("imageurl", "");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
} else {
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Suggestions
Inflate layout with parent attaching like below
.
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
Avoid mantaining status by using multiple collection(Arraylist or
like that to display data) use Model Class or JSON or Arraylist of
map etc.

Related

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.

Android Project : Check bad CheckBox in listView

I am a French student, sorry for my mistakes.
I have to do a major project of 6 months to validate my studies. This project consists of creating an Android application.
My application consists of a listView with a custom adapter (TextView and CheckBox).
My problem is that I want to check a CheckBox that is not in the current view of my listView. For example if I want to check a checkbox at the bottom of the list and I am at the top of it (it is not visible on the screen). The checkbox check is not the right one, it ticks one randomly in the current view.
Picture ListView
Here is the view code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) selectActivity.getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.station_list_item, null);
}
//Handle TextView and display string from your list
TextView textViewListNomStation = (TextView)view.findViewById(R.id.textViewListNomStation);
//Log.i(tag, "nom :" +infosStationsCapteurs.cInfosStationArrayList.get(position).getNomStation() );
textViewListNomStation.setText(infosStationsCapteurs.getcInfosStationArrayList().get(position).getNomStation() + " ID : " + infosStationsCapteurs.getcInfosStationArrayList().get(position).getIdStation());
TextView textViewListInfosStation = (TextView)view.findViewById(R.id.textViewListInfosStation);
String formatInfos = "Lat : " + infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().getLatitude() + " Lon : " + infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().getLongitude();
textViewListInfosStation.setText(formatInfos);
//Handle buttons and add onClickListeners
CheckBox checkBoxStation = (CheckBox) view.findViewById(R.id.checkBoxStation);
checkBoxTab[position] = checkBoxStation;
checkBoxTab[position].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Log.i(tag, "Bouton :" + buttonView.getId() + " Status " + isChecked);
if (isChecked == true)
{
mCheckedState[position]=true;
selectActivity.getTableauCapteurs().addHashSetstationChecked((cInfosStation)getItem(position));
selectActivity.getTableauCapteurs().createTable();
}
if (isChecked == false){
mCheckedState[position]=false;
selectActivity.getTableauCapteurs().deleteHashSetstationChecked((cInfosStation)getItem(position));
selectActivity.getTableauCapteurs().createTable();
}
}
});
checkBoxTab[position].setChecked(mCheckedState[position]);
return view;
}
Here is the code that allows me to check a checkbox in the listView
public void checkListStation(int id, boolean etat)
{
//Log.i(tag,"CheckListStation : NBR STATION : " + infosStationsCapteurs.getcInfosStationArrayList().size());
for (int i = 0;i<infosStationsCapteurs.getcInfosStationArrayList().size();i++)
{
//Log.i(tag, "CHECK " + infosStationsCapteurs.getcInfosStationArrayList().get(i).getNomStation() + " : "+name);
if (infosStationsCapteurs.getcInfosStationArrayList().get(i).getIdStation()==id)
{
mCheckedState[i]=etat;
if (checkBoxTab[i]!=null)
{
checkBoxTab[i].setChecked(etat);
Log.i(tag, "Checkbox : " + i + " : " + checkBoxTab[i].isChecked() + "taille : " + checkBoxTab.length);
}
}
}
this.notifyDataSetChanged();
}
Here is an image that shows the problem. If I want to check the one down it will check the top one instead:
Example
I hope I have been clear enough.
Thank you very much for your help.
Can you post the picture of what you want to do?It is not clear.
But what I think you want one listview which have multiple items and each item holds one checkbox.If it is then you can do it by using custom listview with adapter.
You can refer below caode
public class GeneratedOrderListAdapter extends BaseAdapter {
Context mContext;
ViewHolder holder;
Typeface tf_bold, tf_regular;
ArrayList<GenerateOrder> arrayListgeneratOrder;
public GeneratedOrderListAdapter(Context context, ArrayList<GenerateOrder> arrayListgeneratOrder) {
mContext = context;
this.arrayListgeneratOrder = new ArrayList<>();
this.arrayListgeneratOrder = arrayListgeneratOrder;
this.tf_bold = Typeface.createFromAsset(mContext.getAssets(), "opensans_semibold.ttf");
this.tf_regular = Typeface.createFromAsset(mContext.getAssets(), "opensans_regular.ttf");
}
#Override
public int getCount() {
return arrayListgeneratOrder.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
static class ViewHolder {
TextView mOrderNO;
TextView mCustomerName;
TextView mStatus;
TextView mTotalAmount;
TextView mtextOrderNO;
TextView mtextCustomerName;
TextView mtextStatus;
TextView mtextTotalAmount;
RelativeLayout relback;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = mInflater.inflate(R.layout.order_list, null);
holder = new ViewHolder();
holder.mtextStatus = (TextView) view.findViewById(R.id.txt_t_status);
holder.mtextOrderNO = (TextView) view.findViewById(R.id.txt_title_orderno);
holder.mtextCustomerName = (TextView) view.findViewById(R.id.txt_t_customer);
holder.mtextTotalAmount = (TextView) view.findViewById(R.id.txt_t_amount);
holder.mStatus = (TextView) view.findViewById(R.id.txt_status);
holder.mOrderNO = (TextView) view.findViewById(R.id.txt_orderno);
holder.mCustomerName = (TextView) view.findViewById(R.id.txt_customer);
holder.mTotalAmount = (TextView) view.findViewById(R.id.txt_amount);
holder.relback=(RelativeLayout)view.findViewById(R.id.rel_back);
// setTypeFace();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
try {
holder.mStatus.setText(arrayListgeneratOrder.get(position).getOrderStatus());
holder.mTotalAmount.setText(arrayListgeneratOrder.get(position).getAmount());
holder.mCustomerName.setText(arrayListgeneratOrder.get(position).getCustomerName());
holder.mOrderNO.setText(arrayListgeneratOrder.get(position).getOrderNo());
if(position%2==0){
holder.relback.setBackgroundColor(Color.parseColor("#f4fff5"));
}else{
holder.relback.setBackgroundColor(Color.parseColor("#ffffff"));
}
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
private void setTypeFace() {
holder.mStatus.setTypeface(tf_regular);
holder.mTotalAmount.setTypeface(tf_regular);
holder.mCustomerName.setTypeface(tf_regular);
holder.mOrderNO.setTypeface(tf_regular);
holder.mtextStatus.setTypeface(tf_regular);
holder.mtextOrderNO.setTypeface(tf_regular);
holder.mtextCustomerName.setTypeface(tf_regular);
holder.mtextTotalAmount.setTypeface(tf_regular);
}
}
In your model class add CheckFlag paramter and initialize to zero
//Handle buttons and add onClickListeners
CheckBox checkBoxStation = (CheckBox) view.findViewById(R.id.checkBoxStation);
int check_flag=infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().getCheckFlag();
if(check_flag==1)
{
checkBoxStation.setChecked(true);
}
else
{
checkBoxStation.setChecked(false);
}
checkBoxStation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Log.i(tag, "Bouton :" + buttonView.getId() + " Status " + isChecked);
if (isChecked)
{
infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().setCheckFlag(1);
}
else{
{
infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().setCheckFlag(0);
}
notifyDataSetChanged();
}
});
Use the code below.
This is adater class
public class AttendanceAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
ArrayList<Student> objects;
public AttendanceAdapter(Context context, ArrayList<Student> students) {
ctx = context;
objects = students;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.atndnc_items, parent, false);
}
Student s = getStudent(position);
((TextView) view.findViewById(R.id.txtRollno)).setText(s.rollno);
((TextView) view.findViewById(R.id.txtName)).setText(s.fname+" "+s.mname+" "+s.lname);
final CheckBox cbAtnd = (CheckBox) view.findViewById(R.id.chckTick);
cbAtnd.setOnCheckedChangeListener(myCheckChangList);
cbAtnd.setTag(position);
cbAtnd.setChecked(s.chck);
return view;
}
Student getStudent(int position) {
return ((Student) getItem(position));
}
public ArrayList<Student> getBox() {
ArrayList<Student> box = new ArrayList<Student>();
for (Student s : objects) {
box.add(s);
}
return box;
}
CompoundButton.OnCheckedChangeListener myCheckChangList = new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getStudent((Integer) buttonView.getTag()).chck = isChecked;
}
};}
Then create one object of your adater and call this method from your main activity.Here boxadater is the object of my Adapter class.
public void getValue(){
for (Student s :boxAdapter.getBox()) {
attendance.attendancelist.add(new Attendance( s.rollno,s.fname+" "+s.mname+" "+s.lname,s.chck));
}
}

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.

Android custom list view data is not updating while using shared preference

I am trying to get the value from shared preference and display it in customized list view. But the problem is list view is not getting updated with second value, means first time it's perfectly working fine but second time it overwrites the first value or may be it is opening another screen and displaying over there.
I want to add all the shared preferences data in list view one by one. please help me to solve this. Following is my code.
ListModel.java
public class ListModel {
private String Title = "";
private String Description = "";
/*********** Set Methods ******************/
public void setTitle(String Title) {
this.Title = Title;
}
public void setDescription(String Description) {
this.Description = Description;
}
/*********** Get Methods ****************/
public String getTitle() {
return this.Title;
}
public String getDescription() {
return this.Description;
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList<?> data;
private static LayoutInflater inflater = null;
public Resources res;
ListModel tempValues = null;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList<?> d, Resources resLocal) {
/********** Take passed values **********/
activity = a;
data = d;
res = resLocal;
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView textViewTitle;
public TextView textViewDescr;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
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.displaydata, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.textViewTitle = (TextView) vi.findViewById(R.id.title);
holder.textViewDescr = (TextView) vi.findViewById(R.id.description);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
if (data.size() <= 0) {
holder.textViewTitle.setText("No Data");
} else {
/***** Get each Model object from Arraylist ********/
tempValues = null;
tempValues = (ListModel) data.get(position);
/************ Set Model values in Holder elements ***********/
holder.textViewTitle.setText(tempValues.getTitle());
holder.textViewDescr.setText(tempValues.getDescription());
// holder.image.setImageResource(res.getIdentifier(
// "com.androidexample.customlistview:drawable/"
// + tempValues.getImage(), null, null));
/******** Set Item Click Listner for LayoutInflater for each row *******/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked=====");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener {
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
#Override
public void onClick(View arg0) {
Assignment sct = (Assignment) activity;
sct.onItemClick(mPosition);
}
}
}
Class Which reads shared preferencedata
public class Assignment extends Activity {
ListView list;
ImageView imageView;
CustomAdapter adapter;
public Assignment CustomListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment);
imageView = (ImageView) findViewById(R.id.createassignment);
list = (ListView) findViewById(R.id.displaydata);
CustomListView = this;
setListData();
Resources res = getResources();
adapter = new CustomAdapter(CustomListView, CustomListViewValuesArr,
res);
list.setAdapter(adapter);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Assignment.this,
Assignment_Create.class);
startActivity(intent);
}
});
}
public void setListData() {
final ListModel sched = new ListModel();
/******* Firstly take data in model object ******/
sched.setTitle("Title : "
+ PreferenceConnector.readString(this,
PreferenceConnector.TITLE, null));
sched.setDescription("Description : "
+ PreferenceConnector.readString(this,
PreferenceConnector.DESC, null));
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
}
public void onItemClick(int mPosition) {
ListModel tempValues = (ListModel) CustomListViewValuesArr
.get(mPosition);
Toast.makeText(
CustomListView,
"" + tempValues.getTitle() + "" + ""
+ tempValues.getDescription(), Toast.LENGTH_LONG)
.show();
}
}
This function shows how i am writing data in shared Preference
public void sharedPrefernces() {
if (Code.title != null)
PreferenceConnector.writeString(this, PreferenceConnector.TITLE,
Code.title);
if (Code.description != null)
PreferenceConnector.writeString(this, PreferenceConnector.DESC,
Code.description);
}
In setListData() you're only adding 1 item to the Adapter, so the listView is not going to have the 2nd item shown.

Android java.lang.IllegalStateException on ListView

I use ListActivity with SpecialAdapter that show some log information.
I do not use background thread but I get an error when scroll list:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class ru.FoxGSM.ui.DebugActivity$SpecialAdapter)]
Please, help me.
(FoxLog is static class that get log information, perhaps from another thread. But in list a want show FoxLog snapshot)
public class DebugActivity extends ListActivity {
private class SpecialAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public SpecialAdapter(Context context) {
super();
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return FoxLog.count();
}
public long getItemId(int index) {
return index;
}
public Object getItem(int index) {
return FoxLog.get(FoxLog.count()-index-1);
}
// Get the type of View
public View getView(int position, View convertView, ViewGroup parent) {
TextView text;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.debug_list, null);
text = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(text);
} else
text = (TextView) convertView.getTag();
String s = (String) getItem(position);
if (s==null)
return convertView;
text.setText(s);
boolean isError = false;
if (s!=null && s.length()>0) {
String prefix = s.substring(0, 1);
if (prefix.equals("E") || prefix.equals("W"))
isError = true;
}
if (isError)
text.setBackgroundResource(R.color.red);
else
text.setBackgroundDrawable(null);
return convertView;
}
}
private void RefreshData() {
FoxLog.ReInit(this);
SpecialAdapter adapter = (SpecialAdapter)this.getListAdapter();
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.debug);
FoxLog.ReInit(this);
SpecialAdapter adapter = new SpecialAdapter(this);
setListAdapter(adapter);
Button mExit = (Button)findViewById(R.id.exit);
mExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}

Categories