8

I am using AsyncTask to set my items and stuff, in the postExecute i call a synchronized Method where i do this

mAllResultsAdapter.setItems(mAllResultsItem);
mAllResultsAdapter.notifyDataSetChanged();
mListView.invalidate();
mListView.requestLayout();

Most of the time if I dowload new data and update my listview/adapter it simply works, and pretty good to. But somehow it crashes sometime, can anyone assist me with this issue.

heres my crash log.

  03-19 14:15:02.170: E/AndroidRuntime(23242): FATAL EXCEPTION: main
03-19 14:15:02.170: E/AndroidRuntime(23242): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131034153, class android.widget.ListView) with Adapter(class com....tracebuzz.allresults.AllResultsAdapter)]
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.ListView.layoutChildren(ListView.java:1556)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.AbsListView.onLayout(AbsListView.java:1993)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.View.layout(View.java:9606)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.ViewGroup.layout(ViewGroup.java:3879)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.View.layout(View.java:9606)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.ViewGroup.layout(ViewGroup.java:3879)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.View.layout(View.java:9606)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.ViewGroup.layout(ViewGroup.java:3879)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.View.layout(View.java:9606)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.ViewGroup.layout(ViewGroup.java:3879)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1542)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1403)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1314)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.View.layout(View.java:9606)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.ViewGroup.layout(ViewGroup.java:3879)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.View.layout(View.java:9606)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.ViewGroup.layout(ViewGroup.java:3879)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.ViewRoot.performTraversals(ViewRoot.java:1288)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.view.ViewRoot.handleMessage(ViewRoot.java:2066)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.os.Looper.loop(Looper.java:132)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at android.app.ActivityThread.main(ActivityThread.java:4126)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at java.lang.reflect.Method.invokeNative(Native Method)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at java.lang.reflect.Method.invoke(Method.java:491)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
03-19 14:15:02.170: E/AndroidRuntime(23242):    at dalvik.system.NativeStart.main(Native Method)

I Should update my qeustion with my code, so here it is.

public class AllResultsActivity extends TBActivity{

public String   identifier,
                feedIdentifier,
                apiKey,
                tagID,
                titleName;

private ProcesReuest procesReuest;

public ArrayList<Integer> tempIDHolder = new ArrayList<Integer>();
public ArrayList<AllResultsItem> mAllResultsItem;
public AllResultsAdapter mAllResultsAdapter;
public ListView mListView;
private Context mContext;
private ViewFlipper mViewFlipper;
private TextView mTitleText;
private int itemsForLoad = 50;
private boolean firstRun = true;

private ProgressBar mLoadItemsIndicator;
private int visibleThreshold = 5;
private int mPage = 1;
private int previousTotal = 0;
private boolean loading = true;
private SharedPreferences mSettings;
private Editor mEdit;
private View footerView;
private int itemHolder;


@Override
public void onBackPressed() {
    super.onBackPressed();
    procesReuest.cancel(true);
    AllResultsActivity.this.finish();
}
@Override
public void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.setContentView(R.layout.all_results_view);
    super.onCreate(savedInstanceState);
    getExtras();
    mContext = this;
    itemsForLoad = 50;

    loadItems(apiKey);
    initListview();
}

private void initListview() {
    mAllResultsItem = new ArrayList<AllResultsItem>();
    mAllResultsAdapter = new AllResultsAdapter(this, mAllResultsItem);
    mListView.setAdapter(mAllResultsAdapter);
    mAllResultsAdapter.notifyDataSetChanged();
}

@Override
public void bindResources() {
    mLoadItemsIndicator = (ProgressBar)findViewById(R.id.all_results_view_more_items_indicator);
    mListView = (ListView)findViewById(R.id.all_results_listview);
    mViewFlipper = (ViewFlipper)findViewById(R.id.all_results_view_viewflipper);
    mTitleText   = (TextView) findViewById(R.id.all_results_view_title_text);
    mSettings   = getSharedPreferences(WBAConstants.TRACEBUZZ, MODE_PRIVATE);
    mEdit       =   mSettings.edit();   

}

@Override
public void bindListeners() {
    mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int id, long arg3) {

        String url = (String) view.getTag(R.string.item_url);
        Intent intnt = new Intent(AllResultsActivity.this, WebviewWithControllsActivity.class); 
            if(url.contains("twitter")) {
                int     UQID    = (Integer)view.getTag(R.id.twitter_result_identifier);
                String table    = (String)view.getTag(R.string.twitter_table);

                intnt.putExtra("UQID", UQID);
                intnt.putExtra("apiKey", apiKey);
                intnt.putExtra("table", table);
            }
            View bar = (View)findViewById(R.id.all_results_title_bar);
            int barHeight = bar.getHeight();
            intnt.putExtra("barHeight", barHeight);
            intnt.putExtra("URL", url); 
            AllResultsActivity.this.startActivity(intnt);           
        }
    });

    mListView.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            Log.d("","totalItemCount = " + totalItemCount);
            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                    itemHolder = previousTotal;
                } 
            }
            if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
                    mLoadItemsIndicator.setVisibility(View.VISIBLE);
                    mListView.invalidate();

                    mPage++;
                    loadItems(apiKey);
                    loading = true;
            } else  {

            }
        }   
    });     
}   

private void loadItems(String passedApiKey) {   

    procesReuest = new ProcesReuest();
    procesReuest.execute(identifier, feedIdentifier, passedApiKey);
}

public void getExtras() {
    Bundle extras = getIntent().getExtras();

    feedIdentifier = null;
    tagID = null;
    apiKey = null;
    if(extras != null) {
        identifier      = extras.getString("identifier");
        feedIdentifier  = extras.getString("feedidentifier");
        apiKey          = extras.getString("apiKey");
        titleName       = extras.getString("tag_name");
        tagID           = extras.getString("tag_id");
        if((titleName != null) && (!titleName.equals("null"))) {
            mTitleText.setText(titleName);
        }
    }
}

public void displayDialog() {
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Error");
    dialog.setMessage("Failed to contact server, check your Internet connection or try again later");
    dialog.setNegativeButton("back", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            AllResultsActivity.this.finish();
        }
    });
    dialog.show();
}


private synchronized void addSyncedItems() throws InterruptedException {

        if(firstRun){
            mAllResultsAdapter.setItems(mAllResultsItem);
            firstRun = false;
        }   
                mAllResultsAdapter.notifyDataSetChanged();

                mListView.invalidate();
                mLoadItemsIndicator.setVisibility(View.GONE);   

}

/** Subclass for processing the ResultReqesut for the specified type **/

private class ProcesReuest extends AsyncTask<String, Void, Exception>{
    Downloader downloader = new Downloader();
    JSONObject result = null;
    List<NameValuePair> postParams;
    boolean timeOut;
    @Override
    protected Exception doInBackground(String... params) {
        Log.d("","doInBackground " + apiKey);

        try {
            postParams = new ArrayList<NameValuePair>(2);       
            postParams.add(new BasicNameValuePair("api_key",apiKey));
            postParams.add(new BasicNameValuePair("num","100"));
            postParams.add(new BasicNameValuePair("feed_id", feedIdentifier));
            postParams.add(new BasicNameValuePair("page", Integer.toString(mPage)));
            postParams.add(new BasicNameValuePair("order", "time DESC"));
            postParams.add(new BasicNameValuePair("tag_id", tagID));
            postParams.add(new BasicNameValuePair("format", "json"));
            Log.d("","postParams = " + postParams);
            downloadJSON(postParams);
            proccesJSON();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Exception exception) {
        Log.d("","onPostExecute");
            try {
                addSyncedItems();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        try {
                if(!result.getJSONObject("results").getString("result_count").equals("0")){
                    mViewFlipper.setDisplayedChild(2);
                } else {
                    Log.d("","View 3");
                    mViewFlipper.setDisplayedChild(2);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
    }

    private void proccesJSON() throws JSONException, IOException {
        String UIDHolderString = mSettings.getString(WBAConstants.UIDHOLDER, "empty");
        JSONArray arrayHolder = null;

        if(UIDHolderString.equals("empty")){
            arrayHolder = new JSONArray();
        } else {
            arrayHolder = new JSONArray(UIDHolderString);       
        }

    if(result != null){
        JSONObject feedResults = result.getJSONObject("results").getJSONObject("result");
        Log.d("","" + feedResults);
        String uniqueItemID = null;
        Iterator<String> feedResultIter = feedResults.keys();

        while (feedResultIter.hasNext()) {
            uniqueItemID = (String) feedResultIter.next();  
            Log.d("","" + uniqueItemID);

            if(!uniqueItemID.equals("metaresult")) {
            AllResultsItem item = new AllResultsItem();


            if(UIDHolderString.contains(uniqueItemID)) {
                item.setNewFeed(0);
            } else {
                item.setNewFeed(1);
                arrayHolder.put(uniqueItemID);
            }

            JSONObject resultItem = feedResults.getJSONObject(uniqueItemID);        
                String typeFeed = resultItem.getString("type");
                if(!typeFeed.contains("twitter") && typeFeed != null){      
                    if(resultItem.has("tags") && resultItem.getString("tags")!= null) {
                        JSONObject tags = resultItem.getJSONObject("tags");     

                        Iterator<String> tagIter = tags.keys();
                        ArrayList<String> tagHolder = new ArrayList<String>();
                        while (tagIter.hasNext()) {
                            String tagID = (String) tagIter.next();
                            String tagName = tags.getString(tagID);
                            tagHolder.add(tagName);         
                        }                   
                        item.setTagNames(tagHolder.toString());
                    }
                    item.setType(typeFeed);
                    if((resultItem.has("title")) && (!resultItem.isNull("title")) && (!resultItem.getString("title").equals("null") )) {
                        item.setResultTitle(resultItem.getString("title"));
                    } 
                    if(resultItem.has("unique_id")) {
                        item.setResultIdentifier(Integer.parseInt(resultItem.getString("unique_id")));
                    }
                    if(resultItem.has("src_link") && (resultItem.getString("src_link") != null)) {
                        item.setMessageURL(resultItem.getString("src_link"));
                    }
                    if(resultItem.has("date_time")) {
                        item.setDate( resultItem.getString("date_time"));
                    }
                    if(resultItem.has("description")) {
                        item.setMessage(resultItem.getString("description"));
                    }

                } else if(resultItem.getString("type").contains("twitter")){

                    Icon icon = new Icon();                                     
                    if((resultItem.has("title")) && (!resultItem.isNull("title")) && (!resultItem.getString("title").equals("null"))) {
                        item.setUserTwitter(resultItem.getString("title"));
                    } 
                    if(resultItem.has("unique_id")) {
                        item.setIdentifier(Integer.parseInt(resultItem.getString("unique_id")));
                    }
                    if(resultItem.has("src_link") && (resultItem.getString("src_link") != null)) {
                        item.setMessageURL(resultItem.getString("src_link"));

                    }
                    if(resultItem.has("date_time")) {                           

                        item.setDate(resultItem.getString("date_time"));
                    }
                    if(resultItem.has("description")) {
                        item.setMessageText(resultItem.getString("description"));

                    }
                    if(resultItem.has("image_link")) {
                        if(!resultItem.has("null")){
                            icon.setImageURL(resultItem.getString("image_link"));
                    }                   
                }       
                    if(resultItem.has("table")) {
                    item.setTable(resultItem.getString("table"));
                    }       

                        item.setType(typeFeed);
                        item.addIconsObject(icon);
                        if(resultItem.has("tags") && resultItem.getString("tags")!= null) {
                            JSONObject tags = resultItem.getJSONObject("tags");

                            Iterator<String> tagIter = tags.keys();
                            ArrayList<String> tagHolder = new ArrayList<String>();
                            while (tagIter.hasNext()) {
                                String tagID = (String) tagIter.next();
                                String tagName = tags.getString(tagID);

                                tagHolder.add(tagName);

                            }
                            item.setTagNames(tagHolder.toString());
                        }
                }
                mAllResultsItem.add(item);
            }
        }
        mEdit.putString(WBAConstants.UIDHOLDER, arrayHolder.toString());
        mEdit.commit();
        }
    }

    public boolean downloadJSON(List<NameValuePair>postParams) {
        try {
            result = downloader.getJSONFromURL("http://www.example.com/webservice/get_feed_results.php", true, postParams);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }
}
}

The reason for the Syncronized method was just for trying to get the adapter and the listview the update the same time.

Maikel Bollemeijer
  • 6,545
  • 5
  • 25
  • 48
  • where this code was written in background() or in postExecution()? – Pratik Mar 19 '12 at 13:32
  • invalidate(); and requestLayout(); are redundant if you only need refresh ListView. – yorkw Mar 19 '12 at 20:58
  • What's the reason behind calling a synchronized method from `onPostExecute`? – devmiles.com Mar 20 '12 at 08:24
  • Possible duplicate of [Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"](http://stackoverflow.com/questions/3132021/android-listview-illegalstateexception-the-content-of-the-adapter-has-changed) – rds May 11 '16 at 22:10

2 Answers2

28

According to the code snippet, there are some methods (bindResources() and bindListeners() and etc.) marked as @Override which are neither inherited from the official API nor explicitly called in AllResultsActivity. Assume these are properly implemented and involved in super class or somewhere else. The problem I see in your code is:

@Override
public void onCreate(Bundle savedInstanceState) {
  ... ...

  loadItems(apiKey); // <-- method start AsyncTask, and finially involve mAllResultsAdapter.notifyDataSetChanged();
  initListview(); // <-- method that bind Adapter to ListView. i.e. mListView.setAdapter(mAllResultsAdapter);
}

The problem is when AysncTask executed and onPostExecute() get called (where mAllResultsAdapter.notifyDataSetChanged(); get called), the Adapter has not bound to ListView yet. Simply calling initListview(); before loadItems(apiKey); should make the java.lang.IllegalStateException: goes away.

Update:
I took a deep look in your code, the problem is the ArrayList that bound to Adapter is changed in the Background thread:

// proccesJSON() is called in AsyncTask.doInBackground()
private void proccesJSON() throws JSONException, IOException {
  ... ...

  mAllResultsItem.add(item); // <-- mAllResultsItem is bound to mAllResultsAdapter

  ... ...
}

Your adapter is actually modified from a background thread, exactly as the exception suggested. The solution is moving it to UI thread or simply wrapping it with runOnUiThread():

... ...

runOnUiThread(new Runnable() {
  public void run() {
    mAllResultsItem.add(item);
    mAllResultsAdapter.notifyDataSetChanged();
  }
}); // end of runOnUiThread

... ...

Hope this helps.

yorkw
  • 40,926
  • 10
  • 117
  • 130
  • Thank you for your answer those methods where inherited from a super class indeed, I changed the name of the activity for secretcy for our client app. I will test this solution and come back to you. – Maikel Bollemeijer Mar 22 '12 at 12:49
  • Still no luck, But the strange thing is. most of the time it just works but rarely it just crashes. – Maikel Bollemeijer Mar 22 '12 at 12:58
  • 1
    What do you mean by _rarely it just crashes_? same exception? – yorkw Mar 22 '12 at 20:31
  • yes, Most of the time it works. and sometimes it crashes just random. Maby it got something todo that I am testing on a Android 4.0 devices but the target platform is 2.3.3 , I should run some extra tests on a 2.3.3 device – Maikel Bollemeijer Mar 23 '12 at 12:28
  • @MaikelBollemeijer, I think I found the bug, check out my update. – yorkw Mar 25 '12 at 21:04
  • Thanx for investegating my code, your solution was the fix. thnx – Maikel Bollemeijer Mar 26 '12 at 14:31
  • Have one more Q , why didnt it crash al the time but sometimes ? its pretty random to me – Maikel Bollemeijer Mar 27 '12 at 08:19
  • 1
    There are many possible reasons resulting this unpredictable running behaviour, one maybe lfor exampe, the problematic line of code doesn't get executed in the condition of empty list (i.e. nothing to show). without more details,I can't tell the exact cause. – yorkw Mar 28 '12 at 22:41
  • Where should be the runOnUiThread called, inside the doInBackground or some where else. – theJava Jun 12 '13 at 15:03
  • Where should be `runOnUiThread` be called at the class `SyncTask` – Alston Jul 08 '14 at 06:36
2

I know that this thread is 3 years old. I have been asked to fix a The content of the adapter has changed but ListView did not receive a notification error in existing code. I examined the usages of Timer and added a runOnUiThread(), but the problem still showed. But everything was done on the UI thread!

In fact, the ListView was showing data based on some file system directory -- that was equivalent to displaying all files in a directory in a ListView. The functions getCount() and getView() were reading data right from the directory, and when Android could detect that the number of files has changed, it threw an exception.

The solution was to cache the directory listing and let the timer refresh it. Yes, the changes on disk could not be instantly reflected in the view anymore... but le mieux est l'ennemi du bien.

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127