what I have is an AsyncTask, that started as soon as ListView reached bottom item on a screen, and in AsyncTask it adds new items to the ListView.
Here is the code:
#Override
protected void onPostExecute(final List<ItemDailyRecord> records) {
super.onPostExecute(records);
((ActivityHome)context).runOnUiThread(new Runnable() {
public void run() {
for (ItemDailyRecord p : records) {
adapter.add(p);
}
adapter.notifyDataSetChanged();
}
});
}
#Override
protected List<ItemDailyRecord> doInBackground(Void... voids) {
DbAdapterDailyRecord db = new DbAdapterDailyRecord(context);
List<ItemDailyRecord> list = db.getRecordsFromTo(offset, count);
return list;
}
here is a method from ListView Adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position == getCount() - 1 && hasMoreItems){
HistoryLoaderTask t = new HistoryLoaderTask(position + 1, pageSize, getContext(),this);
t.execute();
footer.setText("Loading . . .");
}
And the error message is(if I scroll the listview too fast :)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its
views.
any ideas how to solve this issue?
The onPostExecute() method is executed on the UI thread, so you should be updating the UI directly in this method; no need to spawn a new Runnable object.
You shouldn't execute your async task from getView of your adapter. Instead you should try to do it from your activity/fragment where your list resides by using getLastVisiblePosition() of ListView
Like this --->
if(list.getLastVisiblePosition() == (dataSet.size() - 1)) {
// last item displayed
.... change the text off footer and execute async task
}
and in the async task append the extra data to dataset and then call notifyDataSetChanged() on the adapter.
Related
I'm using a recycler view in which there are some items containing complex custom component to load. It takes times to load and the problem is the recycler view call whenever necessary the method "onBindViewHolder" (during scroll etc) to recreate the views and so it needs time again to regenerate all the item (I'm not talking about the item's XML layout). And so... not very cool for performance.
How to avoid recreating a item ?
I tried to call :
setIsRecyclable
But it doesn't work.
Example :
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// CODE 1 : treatments applied to the item view
// the problem is here, I don't want to repeat this code when it's already done
}
Why not have a hashmap where you store a boolean value to indicate if you have performed operation at the position?
HashMap<Integer,boolean> operations = new HashMap<>();
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(operations.contains(position){
//Do nothing..
}
else
{
//Do operations...
operations.put(position,true);
}
}
final Handler timerHandler;
timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() { // Here you can update your adapter data
mRecyclerView.invalidate();
My_function();
// mRecyclerView.scrollToPosition(mRecyclerView.getAdapter().getItemCount() - 1);
//mAdapter.notifyDataSetChanged();
timerHandler.postDelayed(this, 3000);
//Toast.makeText(Chat_Activity.this, "Refreace", Toast.LENGTH_SHORT).show();
}
};
timerHandler.postDelayed(timerRunnable, 3000);
in your onBindViewHolder
generate Asynctask and in doInBackground do your content setting process.
I wana create mobile application that uses RecyclerView with pagination that loads each time from dataBase 10 items, then when the list reaches the bottom I load 10 other items, so I used this metho to be notified if I reached the end of the list :
public boolean reachedEndOfList(int position) {
// can check if close or exactly at the end
return position == getItemCount() - 1;
}
and I used this function to load items :
#Override
public void onBindViewHolder(Info holder, int position, List<Object> payloads) {
if (reachedEndOfList(position)) {
Log.d("reachedEnd", "true");
this.autoCompletesTmp = getTmp();
notifyDataSetChanged();
}
}
getTmp() update the list of items with another 10 items, but i get this exception when I reached the bottom of the list:
java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
I had the same problem a while ago:
This helped:
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
//Do something like notifyDataSetChanged()
}
};
handler.post(r);
I am retrieving some data in an Async class called from a Custom ArrayAdapter. When i add a new comment, i update the comment text view and that works ok, but after i reload the entire list the updates don't appear anymore. I can see in the logcat that there is a new comment nr, but not on the UI.
Shouldn't this : answersListView.invalidateViews be enough? I am trying to update that single row from the listview, to escape the issue with not updating the comment nr after a while.
private void updateView(int index) {
System.out.println("index: " + index);
View v = answersListView.getChildAt(index - answersListView.getFirstVisiblePosition());
if (v == null)
return;
final TextView nrComments = (TextView) v.findViewById(com.dub.mobile.R.id.showCommentsTxt);
if (nrComments != null) {
if (nrComments.getText().toString().trim().length() == 0) {
// first comment
nrComments.setText("1 comments");
} else {
// comments exist already
int newNr = Integer.parseInt(nrComments.getText().toString().trim()
.substring(0, nrComments.getText().toString().trim().indexOf("comments")).trim()) + 1;
nrComments.setText(newNr + " comments");
}
System.out.println("final nr of comments: " + nrComments.getText());
nrComments.setVisibility(View.VISIBLE);
}
answersListView.getAdapter().getView(position, v, answersListView);
v.setBackgroundColor(Color.GREEN);
answersListView.invalidateViews();
}
And :
updateView(position);
adapter.notifyDataSetChanged();
The answer is pretty much what #Rami said in a comment to your question. You don't update directly the views, you just need to update the data. In your adapter, you override the getView method, in there is where you make all this changes, you don't need the updateViews method.
Let me try to explain how it works.
The listView uses an Adapter.
The List view ask the Adapter "give me the view in X position" with the getView method.
The adapter creates that view, is returned to the ListView, and that what is shown.
The Adapter itself, should contain a List with the data you want to show.
Those views (rows) are created and destroyed everytime one of those views become visible or invisible in the screen, or if you call the notifyDataSetChanged method.
So now, the thing is, if you change, let's say, the object in the position 5, of the adapter List for a different object with new data, then next time the ListView ask the Adapter to give me the view in the position 5, the adapter is going to create the View (row) with the new data. That's it.
you need to update the data in the UI thread.
if you have context in your Async class use
runOnUiThread(new Runnable() {
#Override
public void run() {
//update here
}
});
or
android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
#Override
public void run() {
//update here
}
});
That's not how you change data for an item in a list view. You must have used some array of strings to fill data in textview in the getView function of the adapter. You only need to change that array and then call notifydatasetchanged on adapter. Views are recycled by adapter so above does not make sense
getView (...)
{
TextView tv = new TextView(context);
tv.setText(myData[index]); // You need to change myData array contents
}
I have a ListView in an Android Activity and a custom adapter for that listview.
I want to be able to edit a row item and update that row instantly. This works, the modifications of the row is seen But, on scroll i loose all data.
This is my Asynk task from where i get the data and update the list row item:
/**
*
*/
public class EditNewsFeedPostAsyncTask extends AsyncTask<Void, Void, Boolean> {
public Activity context;
public String content;
public int rowPosition;
public ListView listView;
public TextView decriptionTxt;
#Override
protected Boolean doInBackground(Void... params) {
try {
token = Utils.getToken(context);
if (token != null) {
....
// {"status":"true"}
if (result != null) {
....
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
if (success) {
updateListView(rowPosition, content);
}
}
public boolean updateListView(int position, String content) {
int first = listView.getFirstVisiblePosition();
int last = listView.getLastVisiblePosition();
if (position < first || position > last) {
return false;
} else {
View convertView = listView.getChildAt(position - first);
decriptionTxt.setText(content);
listView.invalidateViews();
return true;
}
}
private void updateView(int index, TextView decriptionTxt) {
View v = listView.getChildAt(index - listView.getFirstVisiblePosition());
if (v == null)
return;
decriptionTxt.setText(content);
listView.invalidateViews();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onCancelled() {
}
}
What am i missing? shouldn't the data be persistent?
Thx
You must update the object in your listView adapter, not only the views!
after scrolling, the getView method inside your list's adapter will call and you will return the default view for that.
if you want to change that item permanent, you should update your data set and call notifyDataSetChanged on your adapter.
Make sure you're updating the data, not just the view.
When you modify the row, are you changing the underlying data or just the view? If just the view...
You're probably running into ListView recycling issues. This answer has a great explanation. Basically, ListViews are about efficiency in displaying views based on data, but are not good for holding new data on screen. Every time a ListView item is scrolled out of view, its View is recycled to be used for the item that just scrolled into view. Therefore, if you put "hi" in an EditText and then scroll it off screen, you can say goodbye to that string.
I solved this in my app by ditching ListView altogether and using an array of LinearLayouts (probably a clunky approach, but I had a known list size and it works great now). If you want to continue using a ListView, you'll have to approach it from a "data first" perspective. Like I said, ListViews are great at showing info from underlying data. If you put "hi" in an EditText and simultaneously put that string in the underlying data, it would be there regardless of any scrolling you do. Updating onTextChanged might be cumbersome, so you could also let each row open a dialog in which the user enters their data which then updates the underlying dataset when the dialog closes.
These are just some ideas, based on some assumptions, but editing views in a ListView is, in general, not very in line with how ListViews work.
Sometimes, when I call goToLast() it throws me a null exception in vista=lista.getChildAt(), it happens when the list is full, I dont know why I have this code:
private void goToLast() {
lista.post(new Runnable() {
#Override
public void run() {
lista.setSelection(mensajes.getCount() - 1);
View vista = lista.getChildAt(mensajes.getCount() - 1);
TextView txtMensaje = (TextView)vista.findViewById(R.id.txtMensajeLista);
txtMensaje.setBackgroundColor(Color.RED);
}
});
}
You should log lista.getChildCount(), see how many children the ListView has. ListView recycles views, which means it only hold limit number of views.
So if you want to get the last view, you should do something like this
private void goToLast() {
lista.post(new Runnable() {
#Override
public void run() {
lista.setSelection(mensajes.getCount() - 1);
// Figure out the last position of the view on the list.
int lastViewIndex = lista.getChildCount() - 1;
View vista = lista.getChildAt(lastViewIndex);
TextView txtMensaje = (TextView)vista.findViewById(R.id.txtMensajeLista);
txtMensaje.setBackgroundColor(Color.RED);
}
});
}
ListView.getChildAt() position is different to the position in your adapter. ListView recycles its views, so if you have more items in your adapter, than can fit on the screen it will not create views for all of those, but only the ones that are visible. If you want to update an item in the ListView you need to update it in the adapter and call notifyDataSetChanged()