Android ListView not refreshing after notifyDataSetChanged
Look at your onResume
method in ItemFragment
:
@Override
public void onResume() {
super.onResume();
items.clear();
items = dbHelper.getItems(); // reload the items from database
adapter.notifyDataSetChanged();
}
what you just have updated before calling notifyDataSetChanged()
is not the adapter's field private List<Item> items;
but the identically declared field of the fragment. The adapter still stores a reference to list of items you passed when you created the adapter (e.g. in fragment's onCreate).
The shortest (in sense of number of changes) but not elegant way to make your code behave as you expect is simply to replace the line:
items = dbHelper.getItems(); // reload the items from database
with
items.addAll(dbHelper.getItems()); // reload the items from database
A more elegant solution:
1) remove items private List<Item> items;
from ItemFragment
- we need to keep reference to them only in adapter
2) change onCreate to :
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setHasOptionsMenu(true);
getActivity().setTitle(TITLE);
dbHelper = new DatabaseHandler(getActivity());
adapter = new ItemAdapter(getActivity(), dbHelper.getItems());
setListAdapter(adapter);
}
3) add method in ItemAdapter:
public void swapItems(List<Item> items) {
this.items = items;
notifyDataSetChanged();
}
4) change your onResume to:
@Override
public void onResume() {
super.onResume();
adapter.swapItems(dbHelper.getItems());
}
Android ListView not refreshing after notifyDataSetChanged with data as Map
You must add a method to your CategoryAdapter
to change the instance's list, like so
public class CategoryAdapter extends BaseAdapter {
ArrayList<Category> list = new ArrayList<Category>();
Context context;
public CategoryAdapter(Context context, Map<String, Category> categories) {
this.context = context;
list.clear();
list.addAll(categories.values());
}
@Override
public int getCount() {
return list.size();
}
//ADD THIS METHOD TO CHANGE YOUR LIST
public void addItems(Map<String, Category> categories){
list.clear();
list.addAll(categories.values());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHandler handler;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.category_list_item, null);
handler = new ViewHandler();
handler.name = (TextView) convertView.findViewById(R.id.name);
handler.count = (TextView) convertView.findViewById(R.id.count);
convertView.setTag(handler);
} else {
handler = (ViewHandler) convertView.getTag();
}
Category category = list.get(position);
handler.name.setText(category.getMenuName());
handler.count.setText(category.getCount() + "");
if (category.getCount() <= 0) {
handler.count.setVisibility(View.INVISIBLE);
} else {
handler.count.setVisibility(View.VISIBLE);
}
return convertView;
}
}
and change your loadCategories like so (note that I call the addItems() before notifyDataSetChanged()
private void loadCategories() {
sampleDB = openOrCreateDatabase(AppConstants.DB_NAME, MODE_PRIVATE,
null);
Cursor menuCursor = sampleDB.rawQuery("select * from menu", null);
categories.clear();
while (menuCursor.moveToNext()) {
String menu = menuCursor.getString(menuCursor
.getColumnIndex("name"));
String id = menuCursor.getString(menuCursor.getColumnIndex("id"));
Category category = new Category(menu, id);
categories.put(id, category);
}
menuCursor.close();
//ADD CALL TO addItems TO UPDATE THE LIST OF THE categoryAdapter instance
categoryAdapter.addItems(categories);
categoryAdapter.notifyDataSetChanged();
}
Android ListView notifyDataSetChanged() dont refresh the list
replace :
credentials.clear();
with :
adapter.clear()
and whenever you want adding data to the list use:
adapter.addAll(credentials)
or
adapter.insert("new data")
its must fix your problem.
last point : adapter.notifyDataSetChanged(); it not necessary because it is inside the body of adapter methods. good luck.
listview not updating with notifydatasetchanged() call
It looks like you're changing the collection that you initialized adapter with. I would change your code in this way:
// initial setup
listview =(ListView) findViewById(R.id.lv1);
ArrayList<SClass> Monday = new ArrayList<SClass>();
adapter = new CustomAdap(this, Monday);
listview.setAdapter(adapter);
// change your model Monday here, since it is what the adapter is observing
SClass s1=new SubjectClass();
s1.sName="samp";
s1.salary=1000;
Monday.add(s1);
// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();
Note that if your CustomAdap was a subclass of ArrayAdapter, you could also have done
// change your array adapter here
SClass s1=new SubjectClass();
s1.sName="samp";
s1.salary=1000;
adapter.add(s1);
// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();
EDIT: I understand more what you want to do now thanks to your comment. You'll probably want to have the adapter replace its contents with that your different ArrayLists then. I would make your CustomAdap be a subclass of ArrayAdapter.
Then you can utilize it this way:
// replace the array adapters contents with the ArrayList corresponding to the day
adapter.clear();
adapter.addAll(MONDAY);
// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();
Android notifyDataSetChanged not refreshing the items after removing
Try this one
itemsPending.remove(sp.keyAt(i));
adapterPending.remove(adapterPending.getItem(sp.keyAt(i)));
adapterPending.notifyDataSetChanged();
EDIT:
So basically the switching of list data is working fine. What's messing the code is his file writing. I resolve it this way.
First is a create a function that would update my Pending Files to submitted.
public void submitPendingProfile(String filename){
try {
BufferedReader file = new BufferedReader(new FileReader(path + "/" + filename+".txt"));
String line;
StringBuffer inputBuffer = new StringBuffer();
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
String inputStr = inputBuffer.toString();
file.close();
inputStr = inputStr.replace("--PENDING SUBMIT--", "--SUBMITTED--");
FileOutputStream fileOut = new FileOutputStream(path + "/" + filename+".txt");
fileOut.write(inputStr.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Then i refactor the loop for simplier process. Like removing the line SubmittedProfile();
that keeps reading all text files if conditions is true. That is a lot of process. Here's how instead.
for(int i = lstPendingPro.getAdapter().getCount() - 1 ; i >= 0; i--) {
if (sp.get(i)) {
//So when file is submitted, i update the files status using the above function.
submitPendingProfile(itemsPending.get(i));
//To avoid rereading of files, just add the item before removing it to the pending list
itemsSubmit.add(itemsPending.get(i));
adapterSubmit.notifyDataSetChanged();
itemsPending.remove(sp.keyAt(i));
adapterPending.notifyDataSetChanged();
Toast.makeText(ProList.this, "Your profiles have been submitted successfully.", Toast.LENGTH_LONG).show();
}
}
ListView doesn't refresh with notifydatasetchanged
I've founded a solution. I've added getActivity.recreate();
in the method insert_data.
public void success(Response result, Response response) {
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(result.getBody().in()));
String resp;
resp = reader.readLine();
Log.d("success", "" + resp);
JSONObject jObj = new JSONObject(resp);
int success = jObj.getInt("success");
if(success == 1){
Toast.makeText(getActivity(), "Successfully inserted",
Toast.LENGTH_SHORT).show();
getActivity().recreate();
} else{
Toast.makeText(getActivity(), "Insertion Failed",
Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Log.d("Exception", e.toString());
} catch (JSONException e) {
Log.d("JsonException", e.toString());
}
}
I'm not sure that is the best solution but it works.
notifyDataSetChanged() not refreshing adapter
Call the data loading task inside the onReceive()
of BroadcastReceiver
mMyBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Here you can refresh your listview or other UI
new loadListTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
SlidingTab.slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
SlidingTab.slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");;
SlidingTab.slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");
}
};
And also do following changes in your Adapter class.
public void addApplications(ArrayList<Info> candidates) {
if (this.filterList == null) {
filterList = new ArrayList<>();
}
this.mDataset.clear();
this.mDataset.addAll(candidates);
this.filterList.addAll(mDataset);
this.notifyItemRangeInserted(0, candidates.size());
}
public void clearApplications() {
int size = this.mDataset.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
mDataset.remove(i);
filterList.remove(i);
}
this.notifyItemRangeRemoved(0, size);
}
}
Hope that works!
Related Topics
Android Sample Bluetooth Code to Send a Simple String via Bluetooth
Best Practice: Asynctask During Orientation Change
Android: Getting a File Uri from a Content Uri
Valid Values for Android:Fontfamily and What They Map To
Android: Remove Notification from Notification Bar
Android - Java.Lang.Securityexception: Permission Denial: Starting Intent
How to Set a Reminder in Android
How to Monitor the Network Connection Status in Android
How to Set Tint for an Image View Programmatically in Android
Open Link of Google Play Store in Mobile Version Android
Custom Filtering in Android Using Arrayadapter
How to Hide Action Bar Before Activity Is Created, and Then Show It Again
How to Open a Second Activity on Click of Button in Android App
How to Put a Border Around an Android Textview
Error Opening Trace File: No Such File or Directory (2)