Clear all items in a ListFragment - android

I am using a ListFragment and display a dynamic list from a database, I want to update the view and change the order of the list by running the ASYNCTASK again. At them moment when this is done the new data just gets put on the bottom of the current list.
asynctask in fragment:
creates the list adapter and displays it
protected void onPostExecute(String file_url) {
// // dismiss the dialog once done
pDialog.dismiss();
fragment_module.this.getListView().invalidateViews(); //does nothing
adapter = new SimpleAdapter(getActivity(),
questionsList, R.layout.questionlistitem, new String[] {
TAG_QUESTIONVOTE, TAG_QUESTIONTEXT,
TAG_QUESTIONANSWER, CONCATINATED_SUBMISSION,
TAG_QUESTIONID }, new int[] { R.id.upvoteText,
R.id.questionText, R.id.questionAnswer,
R.id.submission, R.id.qid });
// updating listview
setListAdapter(adapter);
}
The view is to change after an onclick event is just want the list to be cleared so it can update.
update
Code called to update view and re-run asynctask
fragment_module.this.getListView().invalidateViews();
getQuestionList obj2 = new getQuestionList();
obj2.execute();

you can use something like
collection.clear();
listview.getAdapter().notifyDataSetChanged();

Related

How to Refresh a RecyclerView with new data in onResume()?

In my main activity I have a RecyclerView which is loaded with data from an array list:
protected void onReady(Bundle savedInstanceState) {
...
// create summary item array & populate it based on task item array
_alData = new ArrayList();
PopulateDataList();
_rv = (RecyclerView) findViewById(R.id.rvDataList);
_li = getLayoutInflater();
_rv.setLayoutManager(new LinearLayoutManager(this));
_adapter = new TaskItemAdapter();
_rv.setAdapter(_adapter);
...
}
When the back button is tapped in a second activity, it returns to my main activity, but the RecyclerView is not updated with the new data. So I want to add the following:
public void onResume() {
super.onResume(); // Always call the superclass method first
// clear out & re-populate summary list, in case something has changed
_alData.clear();
PopulateDataList();
// *** WHAT GOES HERE...???
}
I don't know how to tell the RecyclerView to re-bind the data from the repopulated list... Any help would be appreciated!
Add this after populateDataList() :
_adapter.notifyDataSetChanged();

Android - Update GridView on button click

I am trying to set up a gridview that will refresh when a new search is executed.
this is my call to set up the gridview
final GridElement_Results adapter = new GridElement_Results(this, savedInstanceState, track_name, album_name, track_num, album_id, album_link);
grid = (GridView)findViewById(R.id.grid_results);
grid.setAdapter(adapter);
As you can see, I am passing it a bunch of arrays.
On a button click, the function getTracks() is called which gets new data from the server. The arrays are updated with the new data, which I have verified is working.
icon_activesearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getTracks("newsearchterm");
adapter.notifyDataSetChanged();
grid.invalidateViews();
}
}
);
And then I call adapter.notifyDataSetChanged() and grid.invalidateViews() to update and redraw the grid. But obviously I'm doing something wrong here.
Is it because I'm setting the adapter as final? To access it within the onClick method I need to set it to final.
What should I change to get it to work.
you should wait until new data fetch then notify adapter but you call notify just after getTracks() without any delay

ListView does not show changes until focus changes after notifyDataSetChanged

I have an AlertDialog with a ListView set to multiple selection on it. It also has a Button on it.
The Button open another AlertDialog that if ok'ed will remove the selected items from the data set of the ListView, and then tell the adapter of the list view that the dataset has changed with the notifyDataSetChanged() method.
This all works fine except for one thing. The ListView does not update it's content until I interact with something. Then it updates to the correct data.
This is not a big problem, but I really would like the ListView to appear correct at once, and not just after the focus has changed.
Code:
Button remove = (Button) view.findViewById(R.id.btn_remove_questions_edit_rack);
final Context con = this;
remove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Builder warnBuild = new Builder(con);
warnBuild.setMessage(R.string.question_deletion_warning);
warnBuild.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
SparseBooleanArray checked = list.getCheckedItemPositions();
for (String s : keys)
{
int i = keys.indexOf(s);
if (checked.get(i))
{
toRemove.add(map.get(s));
map.remove(s);
}
}
keys.clear();
keys.addAll(map.keySet());
((ArrayAdapter) list.getAdapter()).notifyDataSetChanged();
list.clearChoices(); //This makes sure the selection is cleared, if it isn't, some of the other items (those that now has the index of the selected items) will be selected when the View refreshes.
dialog.dismiss();
}
});
//Negative button here, not relevant.
}
});
Where map and keys are:
final HashMap<String, QualityQuestion> map = new HashMap<>();
//I add items to the map
final ArrayList<String> keys = new ArrayList<>(map.keySet());
And toRemove is where I store the items to be removed from the actual object they are on when the ok button on the original AlertDialog is pressed.
This is how I populate my ListView in the first place:
final ListView list = (ListView) view.findViewById(R.id.list_questions_edit_rack);
list.setAdapter(
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1,
keys));
I have tried things like list.invalidateViews(), list.invalidate and other things I found in questions similar to mine here on SO. But none of that made any difference. I suspect my problem to be different from theirs since my items clearly are updated, it just takes a change of focus on the original AlertDialog for the change to be visible.
How can I make the ListView show the changes in it's data source imidiatly insted of after a focus change?
By calling
((ArrayAdapter) list.getAdapter()).notifyDataSetChanged();
you get a fresh adapter which is almost certainly not identical to the anonymous adapter you used to populate your list in the first instance.
See also the documentation for ListView.getAdapter()
Returns the adapter currently in use in this ListView.
The returned adapter might not be the same adapter passed to setAdapter(ListAdapter) but might be a WrapperListAdapter.
From the point of view of this fresh adapter, the data set hasn't changed because the changes happened way before it was instantiated.
To solve your problem, make your list and your list adapter members of your activity class (or the scope where you want to keep them alive):
private ArrayList<String> keys;
private ArrayAdapter myAdapter;
private ListView list;
Then in your "onCreate()"
keys = ...; // initialization of ArrayList with the needed data
myAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1,
keys);
list = (ListView) view.findViewById(R.id.list_questions_edit_rack);
list.setAdapter(myAdapter);
This way, in your "OnClickListener" you can notify "myAdapter":
keys.addAll(map.keySet());
myAdapter.notifyDataSetChanged();
Hope this helps :)
You can tweak it, by granting focus to another view, and then requesting it back:
view.requestFocus();
You can also use:
view.requestFocusFromTouch();

after refreshing listview it shows first position data

I have a long ListView that the user can scroll around. I am refreshing this listview after every 30 seconds, listview refresh succesfully. But there is one issue that I want the list to be scrolled to the same point that it was previously before refreshing. Because now if list refresh then it shows the first position.
I am updating list through AsynchronousTask as:
private class HttpTask extends AsyncTask<String, Boolean, String> {
#Override
protected String doInBackground(String... params) {
System.out.println("inside doInBackground>>!!>>> ");
getResponse();
return "Executed";
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
// publishProgress(false);
System.out.println("post excute funt***********");
setListAdapter(new ListAdapter(getApplicationContext(),
R.layout.mylist, dataArr));
}
}
Any help will be appreciated.Thanks in advance
try to use setSelectionFromTop() to set the position to the previously visible state.
You would just have to do this :
listView.setSelection(position) // position is the item on the listView
I think when your listview is going to be refreshed the get the position of item which is first visible at that time then refresh your listview and set the position which you got before refreshing
int firstPosition = mEventListView.getFirstVisiblePosition();
EventLogAdapter eventLogAdapter = new EventLogAdapter(mContext, events);
mEventListView.setAdapter(eventLogAdapter);
mEventListView.setSelection(firstPosition);
Instead of set a new ListAdapter, do listAdapter.notifyDataSetChanged() this will refresh the contents of view instead of create new ones and the listview will not scroll up
What you are doing is you are assigning adapter to your list view when you call refresh
setListAdapter(new ListAdapter(getApplicationContext(),
R.layout.mylist, dataArr));
Which is wrong
You have to refresh your adapter
dataArr.notifyDataSetChanged();
Hope this will work

Why do I get duplicate Items in my ListView?

I'm using the following code to populate listview
Oncreate method:
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.more_custom_row_view, new String[] {"title","desc"}, new int[] {R.id.text1,R.id.text2});
populateList();
setListAdapter(adapter);
static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
private void populateList() {
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("title","Previous Searches");
temp.put("desc", "View your search history");
list.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("title","Settings");
temp1.put("desc", "Update your account settings");
list.add(temp1);
}
when i go to another activity and come back to this acitivity it duplicate list items
each time any one guide me what mistake am i doing?
The problem is that you are using a static list for your items and not clearing or reinstantiating it in your onCreate method.
The list will stay in memory as long as your program is running because it is defined static. If you are returning to the activity the items are again added to the list. You could use clear() to remove all items from the list in your populate list call before filling it again.
Simple, check adapter.isEmpty() before populating
This is a snippet from my own codebase.
private void populateWithAppPackages() {
//DON'T continue if the adapter is not empty; prevents duplicates
if(!mAdapter.isEmpty()){
return;
}
/* ... populate the list ... */
}
DON'T clear() the list adapter!!
clear() and repopulating list every time the activity or the fragment are visited is a very expensive set of operations. You would be better of intelligently populating the list as above.
removing final from the list resolved my problem.

Categories

Resources