Android Listview Caching work unexpectedly on initialization - java

I have a bit troublesome with view caching in listview (a.k.a convertView)
so here is my code,
private class CurrencyAdapter extends ArrayAdapter<CurrencyModel> {
Context ctx;
int layoutResourceId;
List<CurrencyModel> adapter_models = null;
public CurrencyAdapter(Context ctx, int layoutResourceId,
List<CurrencyModel> model) {
super(ctx, layoutResourceId, model);
this.ctx = ctx;
this.layoutResourceId = layoutResourceId;
adapter_models = model;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.d(Constants.APP_TAG, "position: " + position);
View row = convertView;
CurrencyAdapterContainer holder = null;
if (row == null) {
Log.d(Constants.APP_TAG, "APP NULL");
row = ((Activity) ctx).getLayoutInflater().inflate(
layoutResourceId, parent, false);
holder = new CurrencyAdapterContainer();
holder.textView = (TextView) row
.findViewById(R.id.currencies_txt);
holder.imgView = (ImageView) row
.findViewById(R.id.currencies_flag_icon);
row.setTag(holder);
} else {
Log.d(Constants.APP_TAG, "APP NOT NULL");
holder = (CurrencyAdapterContainer) row.getTag();
}
CurrencyModel curr = getItem(position);
if (curr.currency_value == null) {
if (counter < MAX_COUNTER) {
++counter;
CurrencyJsonDownloader cDownloader = new CurrencyJsonDownloader(
curr, holder.textView); //download currency value in background, and set textview text if currency_value has been loaded in onpostExcecute (i'm using AsyncTask)
String url = CURRENCY_URL.replace("<symbol>", curr.symbol);
Log.d(Constants.APP_TAG, "Url currency: " + url);
cDownloader.execute(url);
}
holder.textView.setText("");
} else {
holder.textView.setText(curr.currency_value);
}
holder.imgView.setImageResource(curr.drawableId);
return row;
}
#Override
public CurrencyModel getItem(int position) {
// TODO Auto-generated method stub
return adapter_models.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return adapter_models.size();
}
}
static class CurrencyAdapterContainer {
ImageView imgView;
TextView textView;
}
and here is the output in my logcat
position : 0
APP NULL
position : 1
APP NOT NULL
position : 2
APP NOT NULL
position : 3
APP NOT NULL
.
.
.
position : 10
APP NOT NULL
which make a disaster because it means that the textview being passed in the background job is the same textview and the the changed view is the same textview and the other textview will have blank view unless i scroll it of course which call again the getView() and everything is fine. But it's a problem when starting the app, because just one textview that always changing its value.
so why is this happen? and is there any hack that i can do??
thanks before...

ListView item Views are recycled, so never hold a reference to a particular item view and expect it to represent same data after ListView has been scrolled.
Pass the data item to your worker task instead and let it update the data to it.
Updating:
If your current item is off screen, It'll be requested from adapter (
when ListView scroll to it), and will show updated data.
If that item is currently being displayed , call notifyDataSetChanged() on adapter, this will make ListView refresh its displayed items.

I think problem is with your List adapter. Here i had posted a adapter class i think it will help you.
public class UploadListAdaptor extends BaseAdapter {
private Context context;
private List<UploadDetailsObj> uploadList;
public UploadListAdaptor(Context context, List<UploadDetailsObj> list) {
this.context = context;
uploadList = list;
}
public int getCount() {
return uploadList.size();
}
public Object getItem(int position) {
return uploadList.get(position);
}
public long getItemId(int position) {
return position;
}
/** LIST CATEGORY */
public View getView(int position, View convertView, ViewGroup viewGroup) {
final UploadDetailsObj chlListObj = uploadList.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater
.inflate(R.layout.inflator_progress_bar, null);
TextView photoName = (TextView) convertView
.findViewById(R.id.tv_photoname);
Button btnProgress=(Button)convertView.findViewById(R.id.btn_progress);
photoName.setText(chlListObj.getPhotoName());
}
return convertView;
}
}
You can call this adapter by using this code.
List<UploadDetailsObj> listofUploads= new ArrayList<UploadDetailsObj>();
UploadListAdaptor uploadListAdptr = new UploadListAdaptor(yourclass.this,
listofUploads);
uploadListView.setAdapter(uploadListAdptr);

Related

No Action while SmoothScrollToPosition in Custom List View

Hi I m using below code where when user touches the textview , list will be updated and touched list row will be in front of user.
public class AppAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<AppList> listStorage;
private Context context;
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
int pos = 0;
public AppAdapter(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
this.context = context;
}
#Override
public int getCount() {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
pos = sharedPreferences.getInt("pos", 0);
Log.e("POS",pos+"At Get cpiunt");
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
listViewHolder.textInListView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("pos", position).apply();
Log.e("Pressed", position + "");
MainActivity.installedAppAdapter.notifyDataSetChanged();
Log.e("Saved", sharedPreferences.getInt("pos", 0) + "value");
}
});
if (pos != 0) {
MainActivity.userInstalledApps.setSelection(pos);
editor.putInt("pos",0).apply();
}
return convertView;
}
static class ViewHolder {
TextView textInListView;
ImageView imageInListView;
}
}
I read many questions but did not get clear picture about how to use SmoothScrolltopostion. Though I as per info got, I captured click position and retrieved during list load to set saved position of list to user.
If I use smoothscrolltoposition, there is no action, but if I use setselection as shown in above code, I could able to see the clicked item in top of view after reloading.
Why smoothscroll is not working and m I doing correct coding for required action. pls guide.

Android different Row layout only for first row in BaseAdapter

I am making an Custom listview with Custom Adapter extending BaseAdapter. Now I want to set a different layout only for first row and another layout for all other rows. I am using this code but it sets the special layout for 1st row and also repeats it after every 5/6 rows. How can I fix it and can set it only for 1st row and another layout for all other rows.
public class NewsAdapter extends BaseAdapter {
private Context context;
List<News> newsList;
private Typeface customBanglaFont;
private LayoutInflater inflater;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public NewsAdapter(Context context, List<News> newsList){
this.context = context;
this.newsList = newsList;
}
#Override
public int getCount() {
return newsList.size();
}
#Override
public Object getItem(int arg0) {
return newsList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View row;
row = convertView;
ViewHolder holder=null;
if(row == null){
if(position == 0){
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row =inflater.inflate(R.layout.row_single_big_view,viewGroup,false);
}
else{
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row =inflater.inflate(R.layout.row_single_default,viewGroup,false);
}
holder = new ViewHolder(row);
row.setTag(holder);
}
else{
holder = (ViewHolder) row.getTag();
}
if (imageLoader == null){
imageLoader = AppController.getInstance().getImageLoader();
}
final News news = newsList.get(position);
customBanglaFont = Typeface.createFromAsset(viewGroup.getContext().getAssets(), "fonts/SolaimanLipi.ttf");
holder.newsTitleView.setTypeface(customBanglaFont);
holder.newsTitleView.setText(news.getTitle());
holder.thumbNail.setImageUrl(news.getFeaturedImgSrc(), imageLoader);
return row;
}
}
/**
* Custom View Holder Class
* #author Tonmoy
*
*/
class ViewHolder{
TextView newsTitleView;
NetworkImageView thumbNail;
public ViewHolder(View v) {
// TODO Auto-generated constructor stub
newsTitleView = (TextView) v.findViewById(R.id.news_title);
thumbNail = (NetworkImageView) v.findViewById(R.id.news_image);
}
}
Why don't you use the Header functionality already built into ListView for this specific thing.
The docs:
http://developer.android.com/reference/android/widget/ListView.html#addHeaderView%28android.view.View,%20java.lang.Object,%20boolean%29
or a SO question:
Using ListView : How to add a header view?
your attempting is wrong. Your way you will be able to inflate just one layout. In fact, after the method returns the first time, convertView is not null. To fix quickly you could override getViewTypeCount and getItemViewType. This way you will get convertViews eqaul to the return value of getViewTypeCount, or you could just add the first item as header view for the ListView

multiselection listView contains checkBoxes

I have ListView with check boxes the app delete the checked items ;; and should delet teh items that have the same id with the checked items :
here's my code
private class CAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<Entity> list;
private Context context;
String Status;
CAdapter(Context context,
ArrayList<Entity> getC) {
this.context = context;
this.list = getC;
Status="";
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
class ViewHolder {
TextView Name;
TextView Desc;
Button deleteBtn;
CheckBox CBox;
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
#SuppressLint("NewApi")
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final CEntity CObj = list.get(position);
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.custom_list_view_confirmed, parent,
false);
holder = new ViewHolder();
holder.Name = (TextView) convertView
.findViewById(R.id.Name);
holder.Desc = (TextView) convertView
.findViewById(R.id.activity1);
holder.deleteBtn = (Button) convertView
.findViewById(R.id.deleteBtn);
holder.CBox=(CheckBox) convertView.findViewById(R.id.isCheck);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (CObj.getMystatus().equals(
context.getResources().getString(R.string.course_status_delete))) {
holder.status.setTextColor(Color.RED);
} else if (attemptedCourseObj.getMystatus().equals(
context.getResources().getString(R.string.course_status_pending))) {
holder.status.setTextColor(Color.GREEN);
} else if (attemptedCourseObj.getMystatus().equals(
context.getResources().getString(R.string.course_status_update))) {
holder.status.setTextColor(Color.BLUE);
}
holder.Name.setText(attemptedCourseObj.getCourseName());
holder.CBox.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(holder.CBox.isChecked()){
if(list.contains(getItem(position))){
list.remove(getItem(position));
}
}
}
});
//
return convertView;
}
}
the problem is when delete the checked it dosent delete the item that have the same id .
int pos=Data.CList.size();
SparseBooleanArray checked=CListView.getCheckedItemPositions();
for (int n = pos; n > 0; n--){
if (checked.get(n)){
code=Data.inList.get(n).getCCode();
Data.inList.remove(n);
}else if(CList.get(n).equal(code){
Data.inList.remove(n);
}
try to refresh the list with notifydatasetchanged and be sure that you delete the entire object from the list
You need to inform your adapter with the new modifications by giving the adapter the new dataset after removing the deleted elements from it and notify with the changes. You can do this as the following:
1)Add method into your adapter to set the new data as following:
public void setNewData(ArrayList<Entity> newEntities){
this.list = newEntities;
}
2)From the activity or the fragment call the previous method with the new data and call this line to notify the adapter with the changes
myAdapter.setNewData(myNewEntities);
myAdapter.notifyDataSetChanges();
Read this answer for more info about NotifyDataSetChanges() method

Android Listview clickable textview

I have made an Listview populated with list_row_layout.xml(which is populated with json serializable class), i have clickable textview and onclick changing text from "Accept" to "Accepted". But when i click it on first listview item, another textview listview items below are changing.
Here's some photos to descibe you better
this is the adapter class
public class CustomListAdapter extends BaseAdapter {
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView)convertView.findViewById(R.id.sex);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.confid);
holder.approve = (TextView) convertView.findViewById(R.id.approveTV);
holder.approve.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View argView)
{
holder.approve.setText("Accepted");
}
}
);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = (FeedItem) listData.get(position);
holder.headlineView.setText(Html.fromHtml(newsItem.getTitle()));
holder.reportedDateView.setText(Html.fromHtml(newsItem.getContent()));
return convertView;
}
static class ViewHolder {
TextView approve;
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
Remember that views can be recycled via convertView.
In your onClick method you set the approve text to "Accepted" but when the view is recycled, you never set it back to "Accept"
Actually you need to update (something in) the list in response to an click and have the Accept/Accepted value toggle based on that value rather than simply updating what is currently visible on the screen.
-- to answer the "how" question (asked below)--
Add a new field to ViewHolder
static class ViewHolder {
TextView approve;
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
FeedItem newsItem;
}
Change the onClick method:
public void onClick(View argView)
{
// note that holder no longer needs to be final in the parent class
// because it is not used here.
View parent = (View)argView.getParent();
ViewHolder clickedHolder = (ViewHolder)parent.getTag();
clickedHolder .newsItem.setAccepted(true); /// a new method
clickedHolder .approve.setText ("Accepted");
Log.d(TAG, "Accepted item #" + position);
}
After you have convertView created (if necessary)
FeedItem newsItem = (FeedItem) listData.get(position);
holder.newsItem = newsItem; // populate the new field.
holder.headlineView.setText(Html.fromHtml(newsItem.getTitle()));
holder.reportedDateView.setText(Html.fromHtml(newsItem.getContent()));
if(newsItem.isAccepted ()){ // another new method!
holder.approve.setText ("Accepted");
Log.d(TAG, "Set text to Accepted for item #" + position);
}else{
holder.approve.setText("Accept");
Log.d(TAG, "Set text to Accept for item #" + position);
}
Once it is working you should consider removing the Log.d() lines to cut down on the noise in LogCat.

Delete item from listview

I have listview which contains textview and buttons. When i delete listview item and i try to scroll down, i get exception on this:
BuildQueue eile = countryList.get(position);
Exception:
02-08 19:11:04.279: E/AndroidRuntime(10509): java.lang.IndexOutOfBoundsException: Invalid index 15, size is 15
Seems i do not updating something when i delete item from listview. I think i have problem with ViewHolder, but i do not know what kind of...
My ArrayAdapter code:
public class MyCustomAdapter extends ArrayAdapter<BuildQueue> {
private ArrayList<BuildQueue> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<BuildQueue> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<BuildQueue>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView field;
Button del;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.queue_buildings, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.field = (TextView) convertView.findViewById(R.id.field_text);
holder.del = (Button) convertView.findViewById(R.id.del_button);
convertView.setTag(holder);
holder.del.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Button del_button = (Button) v;
BuildQueue building = (BuildQueue) del_button.getTag();
countryList.remove(building);
dataAdapter.notifyDataSetChanged();
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
BuildQueue eile = countryList.get(position);
holder.code.setText(" ( Level: " + eile.getOld_level() + " to "+eile.getNew_level()+")");
holder.field.setText(eile.getNameSort());
holder.field.setTag(eile);
holder.del.setText("Delete");
holder.del.setTag(eile);
return convertView;
}
}
You are using a two arrays in your Adapter, but only changing one of them.
Every Adapter uses getCount() to determine how many row should be drawn. ArrayAdapter's getCount() simply asks for the size of the array that you pass to the super constructor here: super(context, textViewResourceId, countryList);. But you are also using a second, local array and when you delete a value from this countryList getCount() has no idea this happened which results in getView() throwing an IndexOutOfBoundsException...
Either extend BaseAdapter, or use ArrrayAdapter's methods like getItem(), add(), and remove() and remove your local data set.

Categories