ListView disappears after reloading it again - android

I have 3 arraylist that i have combined to show in listview. Wehen i click on to generate listview, it works fine the first time but when i hit back and then click the button again, the listview shows nothing. Not sure what is cause it. I checked other post but couldnt find an answer. I am not too good with Arraylist so any details would be greatly appreciated.
I have also noticed this message in Log cat. not sure what it means.
onVisibilityChanged() is called, visibility : 0
public class Edit extends Activity implements OnItemClickListener {
private int pic;
public String filename ="User Info";
//Declaring SHareddPreference as userprofile
static SharedPreferences userprofile;
ListView listView;
List<RowItem> rowItems;
// String[] titles, descriptions;
File imgpath=null;
Context context=this;
CustomListAdapter adapter;
private List<String> Titles = new ArrayList<String>();
private List<String> Actions = new ArrayList<String>();
private List<Bitmap> Images = new ArrayList<Bitmap>();
int x;
int y=1;
int z=1;
static int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aname);
listView = (ListView)findViewById(R.id.listing);
userprofile = getSharedPreferences(filename,0);
Intent pdf=getIntent();
pic= userprofile.getInt("lastpic",pic);
x=pic;
Log.d("editpic",new Integer(pic).toString());
while(y!=x){
String comment = commentresult();
Titles.add(comment);
y++;
Log.d("y",new Integer(y).toString());
}
while(z!=x){
String act = actionresult();
Actions.add(act);
z++;
Log.d("z",new Integer(z).toString());}
while(a!=x){
Bitmap photo = getbitmap();
Images.add(photo);
a++;
Log.d("a",new Integer(a).toString());}
Titles.toArray();
Actions.toArray();
Images.toArray();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < Images.size(); i++) {
RowItem item = new RowItem(Images.get(i), Titles.get(i),Actions.get(i));
rowItems.add(item);
}
Log.d("TAG", "listview null? " + (listView == null));
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.aname_list_item, rowItems);
Log.d("TAG", "adapter=null? " + (adapter == null));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(this);
}
public static Bitmap getbitmap() {
String photo1 =userprofile.getString("picpath"+a, "");
File imgpath=new File(photo1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp=DecodeImage.decodeFile(imgpath, 800, 1000, true);
bmp.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Bitmap photo2=bmp;
return photo2;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
public String commentresult()
{
// String com2 = null;
// while(y!=x){
String comment=userprofile.getString("comment"+y, "");
String com1=comment;
String com2=com1;
// }
return com2;
}
public String actionresult()
{
// String act2 = null;
// while(y!=x){
String action=userprofile.getString("action"+z, "");
String act1=action;
String act2=act1;
// }
return act2;
}
private static final long delay = 2000L;
private boolean mRecentlyBackPressed = false;
private Handler mExitHandler = new Handler();
private Runnable mExitRunnable = new Runnable() {
#Override
public void run() {
mRecentlyBackPressed=false;
}
};
#Override
public void onBackPressed() {
//You may also add condition if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) // in case of Fragment-based add
if (mRecentlyBackPressed) {
mExitHandler.removeCallbacks(mExitRunnable);
mExitHandler = null;
super.onBackPressed();
}
else
{
mRecentlyBackPressed = true;
Toast.makeText(this, "press again to exit", Toast.LENGTH_SHORT).show();
mExitHandler.postDelayed(mExitRunnable, delay);
}
}
#Override
public void onDestroy() {
// Destroy the AdView.
super.onDestroy();
}
Custom List Adapter:
public class CustomListAdapter extends ArrayAdapter<RowItem> {
Context context;
List<RowItem> items;
public CustomListAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public RowItem getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.aname_list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.rab);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// String name=items.get(position).getDesc();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageBitmap(rowItem.getImageId());
// holder.imageView.setImageResource(Images.get(position) .getPlaceholderleft());
return convertView;
}
}

It looks like this is because you've made your variables x, y, z and a all static, which means there is a single instance of the variables shared by all instances of the class. Therefore, when you call onCreate the second time, all your while loop termination conditions are already met, so the while loops never execute. It's unclear to me why you've made these static, so unless you need them to be, you should remove the static keyword for these variables.

Why are you creating another object of ListView in onCreate() and onResume()
Remove code from onResume()
Also replace this line in onCreate()
old line ListView listView = (ListView)findViewById(R.id.listing);
New line listView = (ListView)findViewById(R.id.listing);

Related

Positions of view in a custom ListView is repeating

I used CustomListAdapter class which extends baseadapter. In that i have a button on each view of the list view ..when I lick on the button it should print a text. everything is working fine except that the text is printed in someother view too. I have found many similar question but no exact solution.
public class CustomListAdapter extends BaseAdapter {
List<HashMap<String, Object>> models;
Context context;
LayoutInflater inflater;
ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2;
ArrayList<String> listItems;
public int count1 = 0;
ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email;
int i ;
ImageButton like;
ImageButton share;
JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
private static String url_all_propertiesdel = IP+"/studio/getdelete_all_agent.php";
boolean isSelected;
int a,a1,b,b1;
//private static final String TAG_SUCCESS1 = "mass";
private static final String TAG_USER = "users";
private static final String TAG_PRO = "properties";
//private static final String TAG_PRO1 = "properties1";
// products JSONArray
JSONArray users = null;
//JSONArray users1 = null;
View view;
// JSON Node names
private static final String TAG_SUCCESS = "success";
SharedPreferences sPref;
// int position;
public CustomListAdapter(Context context, List<HashMap<String, Object>> models) {
this.context = context;
this. models = models;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.counters = new int[30];
//this.session_email = sPref.getString("SESSION_UID","");
}
public class ViewHolder {
public TextView countt;
public ImageButton like,share;
}
public void clear(){
if(models!=null)
models.clear();
}
#Override
public int getCount() {
return models.size();
}
public HashMap<String, Object> getItem(int position) {
return models.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public View getView( int position, final View convertView, ViewGroup parent) {
// view = null;
view = convertView;
ViewHolder viewHolder;
pos = getItemViewType(position);
// long posn = getItemId(position);
// final int paps= (int)posn ;
if (view == null) {
viewHolder = new ViewHolder();
view = inflater.inflate(R.layout.fragment_home2, parent, false);
//your code
//add below code after (end of) your code
viewHolder.like=(ImageButton)view.findViewById(R.id.likem);
viewHolder.share=(ImageButton)view.findViewById(R.id.share);
viewHolder.like.setTag(position);
// viewHolder.share.setTag(position);
/* viewHolder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, Object> item = models.get(position);
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
// Make sure you put example png image named myImage.png in your
// directory
String imagePath = Environment.getExternalStorageDirectory()
+ "/108.png";
String imagePath = (String)item.get("IMAGE");
Toast.makeText(context, imagePath, Toast.LENGTH_LONG).show();
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(share, "Share Image!"));
}
});*/
// viewHolder.share.setOnItemClickListener(this);
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
// viewHolder.countt = (TextView) v.findViewById(R.id.count);
HashMap<String, Object> item = models.get(position);
isSelected = (Boolean) item.get("selected");
item.put("selected", !isSelected);
notifyDataSetChanged();
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
final HashMap<String, Object> item = getItem(position);
// like = (ImageView) view.findViewById(R.id.like);
//sharingButton = (ImageButton) view.findViewById(R.id.share);
// final HashMap<String, Object> item1 = getItem(position);
isSelected = (Boolean) item.get("selected");
if (isSelected) {
viewHolder.like.setBackgroundResource(R.drawable.checked);
} else {
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}
pic = (ImageView) view.findViewById(R.id.profilePic);
name = (TextView) view.findViewById(R.id.name);
idas = (TextView) view.findViewById(R.id.hpid);
idas2 = (TextView) view.findViewById(R.id.hpid2);
timestamp = (TextView) view.findViewById(R.id.timestamp);
msg = (TextView) view.findViewById(R.id.txtStatusMsg);
url = (TextView) view.findViewById(R.id.txtUrl);
image = (ImageView) view.findViewById(R.id.feedImage1);
//countt =(TextView)view.findViewById(R.id.count);
/*if any exception raises please use
locationTitle.setText(((String)item.get(“NAME�?)));
use this technique for the Image also.
*/
//holder.like.setText(item.get(item));
//like.setText((String) item.get(R.id.like));
idas.setText((CharSequence) item.get("UIDAS"));
// listItems.add(idas.getText().toString());
name.setText((CharSequence) item.get("NAME"));
timestamp.setText((CharSequence) item.get("TIME"));
msg.setText((CharSequence) item.get("MSG"));
url.setText((CharSequence) item.get("URL"));
//countt.setText((CharSequence) item.get("COUN"));
//count.setText("" + count1);
int w = image.getWidth();
int h = image.getHeight();
if (w > 1000)
{
a=w-1000;
b=w-a;
}
else
{
b=w;
}
if (h > 1000)
{
a1=h-1000;
b1=h-a1;
}
else
{
b1=h;
}
Picasso.with(context)
//.load("PIC")
.load((String)item.get("PIC"))
.placeholder(R.drawable.profile_dummy)
//.error(R.drawable.ic_whats_hot)
.resize(50, 50)
// .centerCrop()
// .fit()
.into(pic);
/*Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;*/
Picasso.with(context)
.load((String)item.get("IMAGE"))
//.load("IMAGE")
// .placeholder(R.drawable.ic_pages)
//.error(R.drawable.ic_home)
.resize(1000,b1)
.onlyScaleDown()
//.centerCrop()
// .fit().centerInside()
.into(image);
/*if ((image).length() < 0)
{
//image.setVisibility(View.VISIBLE);
// invalid = true;
idas2.setText(1);
// Toast.makeText(getApplicationContext(), "hgghghghjgh", Toast.LENGTH_LONG).show();
}*/
/* delam.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
// pacm = idas.getText().toString();
listItems.remove(index.intValue());
notifyDataSetChanged();
}
}
);
*/
/*
delam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pacm = idas.getText().toString();
removeItemFromList();
}
});
*/
/* like.setTag(position);
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// int p = (Integer)v.getTag();
//int p;
//int posit=(Integer)v.getTag();
//String s = view[position];
//Context get = null;
//Toast.makeText(context, String.valueOf(p) , Toast.LENGTH_LONG).show();
//like.setBackgroundResource(R.drawable.checked);
if( viewHolder.like.isSelected()){
viewHolder.like.setSelected(false);
//ctv.setBackgroundColor (Color.parseColor("#ffffff"));
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}else if(! viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
viewHolder.like.setBackgroundResource(R.drawable.checked);
}
}
});*/
return view;
}
// HashMap<String, Object> item = models.get(position);
}
Well try this, in your HashMap list you need to have one more item called selected to store selected row status
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
//your code
if (view == null) {
viewHolder = new ViewHolder();
//your code
//add below code after (end of) your code
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
HashMap<String, Object> item = models.get(position);
boolean isSelected = (boolean) item.get("selected");
item.put("selected", !isSelected);
notifyDataSetChanged();
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
//updated
viewHolder.like.setTag(position);
final HashMap<String, Object> item = getItem(position);
boolean isSelected = (boolean) item.get("selected");
if (isSelected) {
viewHolder.like.setBackgroundResource(R.drawable.checked);
} else {
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}
//your other code
}
This problem is due to recycling of Viewholder object in your ListView through convertView. Do not make logic based on the view state as the same state can be passed to some another item of ListView, where it supposed to be presented.
So what to do?
Hold your state on your data Item. And use notify dataSetChanged when you click some item not change its background Directly.
You can see example here. That one id for RecyclerView Adapter, but concept is same. RecyclerView causes issue when recycling

custom List view with lazy loading causes Index outof bound exception

public class LazyImageLoadAdapter extends BaseAdapter implements
OnClickListener {
private int mCount = 10;
// String mPositionString;
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
// int mTextViewResourceId;
public LazyImageLoadAdapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// mPositionString = activity.getString(d.length) + " ";
// mTextViewResourceId = textViewResourceId;
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public void addMoreItems(int count) {
mCount += count;
notifyDataSetChanged();
}
public int getCount() {
return mCount;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// #Override
// public int getViewTypeCount() {
// return 2;
// }
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
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.listview_row, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.text1 = (TextView) vi.findViewById(R.id.text1);
holder.image = (ImageView) vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.text.setText("Company " + position);
holder.text1.setText("company description " + position);
ImageView image = holder.image;
// DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(data[position], image);
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
/********* 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) {
MainActivity sct = (MainActivity) activity;
sct.onItemClick(mPosition);
}
}
}
at >>> imageLoader.DisplayImage(data[position], image);
the error is
public class MainActivity extends Activity implements OnScrollListener {
ListView list;
LazyImageLoadAdapter mAdapter;
private final int AUTOLOAD_THRESHOLD = 4;
private final int MAXIMUM_ITEMS = 1052;
private View mFooterView;
private Handler mHandler;
private boolean mIsLoading = false;
private boolean mMoreDataAvailable = true;
private boolean mWasLoading = false;
private Runnable mAddItemsRunnable = new Runnable() {
#Override
public void run() {
mAdapter.addMoreItems(10);
mIsLoading = false;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView) findViewById(R.id.list);
// Create custom adapter for listview
mAdapter = new LazyImageLoadAdapter(this, mStrings);
// Set adapter to listview
// Button b = (Button) findViewById(R.id.button1);
// b.setOnClickListener(listener);
mHandler = new Handler();
// mAdapter = new SimpleAdapter(MainActivity.this,
// android.R.layout.simple_list_item_1);
mFooterView = LayoutInflater.from(this).inflate(R.layout.loading_view,
null);
list.addFooterView(mFooterView, null, false);
// LIST(MADAPTER);
list.setAdapter(mAdapter);
list.setOnScrollListener(this);
}
#Override
public void onDestroy() {
// Remove adapter refference from list
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View arg0) {
// Refresh cache directory downloaded images
mAdapter.imageLoader.clearCache();
mAdapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition) {
String tempValues = mStrings[mPosition];
Toast.makeText(MainActivity.this, "Image URL : " + tempValues,
Toast.LENGTH_LONG).show();
}
// Image urls used in LazyImageLoadAdapter.java file
private String[] mStrings = {
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png",
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png",
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png"
};
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (!mIsLoading && mMoreDataAvailable) {
if (totalItemCount >= MAXIMUM_ITEMS) {
mMoreDataAvailable = false;
list.removeFooterView(mFooterView);
} else if (totalItemCount - AUTOLOAD_THRESHOLD <= firstVisibleItem
+ visibleItemCount) {
mIsLoading = true;
mHandler.postDelayed(mAddItemsRunnable, 1000);
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Ignore
}
#Override
public void onStart() {
super.onStart();
if (mWasLoading) {
mWasLoading = false;
mIsLoading = true;
mHandler.postDelayed(mAddItemsRunnable, 1000);
}
}
#Override
public void onStop() {
super.onStop();
mHandler.removeCallbacks(mAddItemsRunnable);
mWasLoading = mIsLoading;
mIsLoading = false;
}
}
this is my MainActivity class using OnScrollListener for data showing after scrolling .
and this is exception
please help me out..
My guess is that your data array does not contain the same amount of values as your mCount variable tells the adapter. Try to fix this issue the following way:
// change your method implementation that returns mCount to this one
public int getCount() {
return data.length;
}
This is supposed to fix the ArrayIndexOutOfBoundsException that you are getting. The next step for you, I guess, would be implementation of addMoreItems method so that it would add items to your array, and not just update the counter.
Edit
If you manually update mCount, consider the following code:
public void addMoreItems(int count) {
// update the counter
mCount += count;
// if now your counter exceeds the size of the array,
// set its value to the size
if (mCount >= data.length) {
mCount = data.length;
}
notifyDataSetChanged();
}
Also, just to make sure, you should check if you are trying to access your array at the index that is the same as its size: data[mCount] may be wrong, if mCount equals to the size of your array, in that case you should use data[mCount - 1] instead.

ListView won't refresh using notifyDataSetChanged

I'm trying to refresh the listview from the adapter class ( non activity class) I tried notifyDataSetChanged() but it wont work , I also tried to call the displayListView() in the adapter class but it crashes as well
this is my displayListView() Method in The ActivityClass
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[]{
DBAdapter.qty,
DBAdapter.price,
DBAdapter.PRODUCT_NAME
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.qtyL,
R.id.priceL,
R.id.PRODUCT_NAMEL
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.country_inf,
cursor,
columns,
to,
0);
HorizontalListView listView = (HorizontalListView) findViewById(R.id.cartCeckOutList);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
And this is the Adapter Class I use
package com.abdullahadhaim.finegrillresturant.adater;
public class CustomListAdapter extends BaseAdapter {
Context c;
// DBHelper myDataBaseHelper ;
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
DBAdapter myADapterDB;
WaiterActivity waiterAct;
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#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.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
final TextView title = (TextView) convertView.findViewById(R.id.title);
TextView price = (TextView) convertView.findViewById(R.id.rating);
// myDataBaseHelper=new DBHelper(activity, "CDB", null, 1);
myADapterDB = new DBAdapter(activity);
myADapterDB.open();
waiterAct = new WaiterActivity();
// getting movie data for the row
final Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// price
price.setText("Price: " + "SR " + String.valueOf(m.getPrice()));
Button add = (Button) convertView.findViewById(R.id.button1);
Button plus = (Button) convertView.findViewById(R.id.plus_butt);
Button minus = (Button) convertView.findViewById(R.id.minus_butt);
final EditText qty = (EditText) convertView
.findViewById(R.id.editText1);
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String the_qty = qty.getText().toString();
int my_qty = Integer.parseInt(the_qty) + 1;
qty.setText(my_qty + "");
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String the_qty = qty.getText().toString();
int my_qty = Integer.parseInt(the_qty) - 1;
qty.setText(my_qty + "");
}
});
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int myQTY = Integer.parseInt(qty.getText().toString());
String myTitle = m.getTitle().toString();
String myCategory = m.getCategory().toString();
int myCategoryN = m.getOrderNum();
double myPrice = m.getPrice() * myQTY;
if (myQTY == 0)
Toast.makeText(activity, "Orders Must be 1 Atleast",
Toast.LENGTH_SHORT).show();
else {
myADapterDB.checkIfExcist(activity, "productName", myTitle,
myQTY, myPrice, m.getPrice(), myTitle, myCategory,
myCategoryN + "", myQTY);
myADapterDB.deleteZeroOrLessValues();
}
}
});
return convertView;
}
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
}
take a look at Loaders. I think this is the prefered way to load data from datebase into views. With Loaders you get callbacks if the data has changed and the view is updated for you.
http://developer.android.com/guide/components/loaders.html
Here is a good tutorial I think:
http://code.tutsplus.com/tutorials/android-fundamentals-properly-loading-data--mobile-5673

Android custom listview layout

im new to android and java programming. Im having trouble getting my custom layout (currently with only one textview in it to work with my code. I have followed many tutorials and look and many examples but still Im getting confused as to how I would integrate it with my existing code.
Any help would be appreciated.
Here is my code:
public class checkListActivity extends MainActivity {
static String filename = "checkList";
String currentList;
SharedPreferences checkListData;
SharedPreferences.Editor checkListEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.checklist);
Button bAddItem = (Button) findViewById(R.id.bAddItem);
final EditText etItemName = (EditText) findViewById(R.id.etItemName);
final TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckLists);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String selectedItem = extras.getString("selectedItem");
// get the value based on the key
currentList = selectedItem;
}
tvTitle.setText(currentList);
checkListData = getSharedPreferences(filename, 0);
updateListView();
// Button Click Listener
bAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String checkListStringData = etItemName.getText().toString();
checkListData = getSharedPreferences(filename, 0);
SharedPreferences.Editor checkListEditor = checkListData.edit();
checkListEditor.putString(currentList + "ItemName",
checkListStringData);
checkListEditor.commit();
String checkListDataReturned = checkListData.getString(
currentList + "ItemName", currentList);
tvTitle.setText(checkListDataReturned);
updateListView();
etItemName.setText("");
};
});
}
private void updateListView() {
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
Map<String, ?> keys = checkListData.getAll();
ArrayList<String> checkListStrings = new ArrayList<String>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
if (entry.getValue() instanceof String) {
if (entry.getKey().equals(currentList + "ItemName")) {
checkListStrings.add((String) entry.getValue());
}
}
ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
this, R.layout.single_listview_item);
lvCheckList.setAdapter(checkListArrayAdapter);
}
}
}
first create this custom adapter class...
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public Context con;
public String[] sms;
public EfficientAdapter(Context context,String[] rssFeed) {
mInflater = LayoutInflater.from(context);
this.con=context;
this.sms=rssFeed;
}
public int getCount() {
return sms.length;
}
public Object getItem(int position) {
return sms[position];
}
public long getItemId(int position) {
return position;
}
#SuppressLint({ "SdCardPath", "InflateParams", "ResourceAsColor" })
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text_list_f);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text2.setText(sms[position]);
}
return convertView;
}
}
static class ViewHolder {
TextView text2;
}
then use it in your activity ...
list.setAdapter(new EfficientAdapter(this, your array));

How to Display two dimensional Array in ListView?

I Have 2D Array and this 2D Array has Strings. I would like to know How to Display the Strings in ListView?how to scroll both vertically and horizontally?
String[][] board = new String[][] {{"1","10","100"},{"hi0","1hello","test"},{"test31","test32","test43"}};
It seem to be you are asking basic things, How to use ListView. please check it you will get all about ListView.
Android ListView and ListActivity
It is to display two-d array in list view.Here's my source code in which i have implemented 2-d array in list view
My Adapter class:-
public class MyArrayAdapter extends ArrayAdapter<List>{
QuickActionDemo quickActionDemo;
public Activity context;
public List<List> list;
int CAMERA_PIC_REQUEST=10;
private int selectedPos = -1;
int clickPosition,rowPosition;
Camera camera;
private static final String TAG = "CameraDemo";
public MyArrayAdapter(Activity context,List<List> list) {
super(context,R.layout.attach_pic,list);
this.context = context;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position+1;
}
static class ViewHolder {
public TextView tv1,tv2,tv3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = null;
final ViewHolder holder = new ViewHolder();
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
rowView = inflator.inflate(R.layout.attach_pic, null);
holder.tv1 = (TextView) rowView.findViewById(R.id.defectpic);
holder.tv2 = (TextView) rowView.findViewById(R.id.no_of_uploded_pics);
holder.tv3 = (TextView) rowView.findViewById(R.id.camera);
holder.tv3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent in = new Intent(getContext(),QuickActionDemo.class);
// context.startActivityForResult(in,0);
}
});
rowView.setTag(holder);
List itemVal1 = (List)getItem(position);
String st1 = (String)itemVal1.get(0);
holder.tv1.setText(st1);
List itemVal2 = (List)getItem(position);
String st2 = (String)itemVal2.get(1);
holder.tv2.setText(st2);
} else {
rowView = convertView;
((ViewHolder) rowView.getTag()).tv1.setTag(list.get(position));
((ViewHolder) rowView.getTag()).tv2.setTag(list.get(position));
((ViewHolder) rowView.getTag()).tv3.setTag(list.get(position));
}
return rowView;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return list.size();
}
}
Here's my activity class:-
public class MyActivity extends ListActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // to hide the virtual keyboard
setContentView(R.layout.defect_pic_listview);
try{
ArrayAdapter<List> adapter = new MyArrayAdapter(this,makeList());
setListAdapter(adapter);
}
}
private List<List> makeList(){
List<List> all = new ArrayList();
String[] newArray1 = {"Defect Picture1", "2"};
List<String> newListObject1 = Arrays.asList(newArray1);
String[] newArray2 = {"Defect Picture2","1"};
List<String> newListObject2 = Arrays.asList(newArray2);
String[] newArray3 = {"Defect Picture3","4"};
List<String> newListObject3 = Arrays.asList(newArray3);
String[] newArray4 = {"Defect Picture4","1"};
List<String> newListObject4 = Arrays.asList(newArray4);
String[] newArray5 = {"Defect Picture5","3"};
List<String> newListObject5 = Arrays.asList(newArray5);
all.add(newListObject1);
all.add(newListObject2);
all.add(newListObject3);
all.add(newListObject4);
all.add(newListObject5);
return all;
}
}
Creating a model as an inner class always works well.
Good way to store any number of items.
public class ActivityClass extends Activity {
...
ArrayList<ValuesModel> listViewValues = new ArrayList<ValuesModel>();
listViewValues.add(new ValuesModel("row title", "row details"));
ListViewAdapter listAdapter = new ListViewAdapter(this, listViewValues);
((ListView) findViewById(android.R.id.list)).setAdapter(listAdapter);
...
public class ValuesModel {
private String rowTitle;
private String rowDetails;
public ValuesModel(String rowTitle, String rowDetails) {
this.rowTitle = rowTitle;
this.rowDetails = rowDetails;
}
public String getRowTitle() {
return rowTitle;
}
public String getRowDetails() {
return rowDetails();
}
}
Then inside of your list adapter,
public class ListViewAdapter extends ArrayAdapter<ActivityClass.ValuesModel> {
private ArrayList<ActivityClass.ValuesModel> mValues;
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
//here whenever you need to retrieve your values, just say:
// mValues.get(position).getRowTitle();
// mValues.get(position).getRowDetails();
//if you use a viewholder pattern, you can do this:
viewHolder.rowTitle = (TextView) convertView.findViewById(R.id.row_title_textview);
viewHolder.rowTitle.setText(mValues.get(position).getRowTitle());
...
}
}

Categories

Resources