簡體   English   中英

java.lang.IllegalStateException:適配器的內容已更改,但ListView在android Studio中未收到通知

[英]java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification in android Studio

我曾經用過listview,但是我從來沒有遇到過這樣的問題。 我收到類似的錯誤

java.lang.IllegalStateException:適配器的內容已更改,但ListView沒有收到通知。 確保不從后台線程修改適配器的內容,而僅從UI線程修改。 確保適配器在其內容更改時調用notifyDataSetChanged()。 [在帶適配器的ListView(2131558770,類android.widget.ListView)中(類shoppingmazza.android.catalyst.com.shoppingmazza.activity.SearchAdapter)]

這是我的搜索適配器:

import java.util.ArrayList;

import shoppingmazza.android.catalyst.com.shoppingmazza.R;

/**
 * Created by ANDROID on 10/26/2015.
 *
 */
public class SearchAdapter extends ArrayAdapter<SearchItem> {

    static ArrayList<SearchItem> productsList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public SearchAdapter(Context context, int resource, ArrayList<SearchItem> object) {
        super(context, resource, object);
        vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        productsList = object;
        Resource = resource;
        //   this.context = context;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.search_name = (TextView)v.findViewById(R.id.text_name_search);
            holder.serch_id = (TextView)v.findViewById(R.id.text_id_serach);
            v.setTag(holder);
        }
        else{
            holder = (ViewHolder)v.getTag();
        }
        String content = productsList.get(position).getName();
        content = content.replace("&#039;", "");
        content = content.replace("&amp;", "");
        holder.search_name.setText(content);
        holder.serch_id.setText(productsList.get(position).getid());
        return v;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    static class ViewHolder{
        public TextView  search_name;
        public TextView  serch_id;
    }
}

這是我的活動課:

public class SearchActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private ListView listview;
    private EditText editText;
    private String searchtext;
    private SearchAdapter adapter;
    private ArrayList<SearchItem> SearchItem = new ArrayList<>();
    private ImageView imageView;

    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

    AlertDialogManager alert = new AlertDialogManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_activity);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle(null);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        cd = new ConnectionDetector(getApplicationContext());


        //Button button = (Button)findViewById(R.id.clear_text);

        imageView = (ImageView)findViewById(R.id.cross_btn);
        listview = (ListView)findViewById(R.id.search_item);
        editText = (EditText)findViewById(R.id.myEditText);
        adapter = new SearchAdapter(getApplicationContext(),R.layout.search_item_show,SearchItem);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                SearchItem.clear();
                adapter.notifyDataSetChanged();
                isInternetPresent = cd.isConnectingToInternet();
                if(isInternetPresent){

                    new SearchItemFind().execute(CollectionOfAllURL.SearchItemFind);
                }
                else {
                    alert.showAlertDialog(SearchActivity.this, "No Internet Connection",
                            "You don't have internet connection.", false);
                }
            }
        });


        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH){

                    isInternetPresent = cd.isConnectingToInternet();
                    if(isInternetPresent){
                        //  new SearchItemFind().execute("http://www.shoppingmazza.com/?route=feed/web_api/livesearch");
                        new SearchItemActionFind().execute(CollectionOfAllURL.SearchItemFind);
                        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    }
                    else {
                        alert.showAlertDialog(SearchActivity.this, "No Internet Connection",
                                "You don't have internet connection.", false);
                    }
                    return true;
                }
                return false;
            }
        });

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String svalue = SearchAdapter.productsList.get(position).getSvalue();
                String menu_id = SearchAdapter.productsList.get(position).getid();

                if(svalue.equals("0")){
                    Intent i = new Intent(SearchActivity.this, ProductsCategory.class);
                    i.putExtra("category", menu_id);
                    startActivity(i);
                }
                else {
                    Intent i = new Intent(SearchActivity.this, ProductsDetails.class);
                    i.putExtra("product_id", menu_id);
                    startActivity(i);
                }



            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText(null);
            }
        });
    }
    public class SearchItemFind extends AsyncTask<String,Void,Void>{
        Boolean result ,trycatch = true;
        JSONArray jsonArray;
        JSONArray jsonArray1;

        Boolean firstBool,secondBool;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            searchtext = editText.getText().toString();
          /*  SearchItem.clear();
            searchCateogry.clear();*/
            SearchItem.clear();
            adapter.notifyDataSetChanged();
        }

        @Override
        protected Void doInBackground(String... params) {
            try{
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(params[0]);
                List<NameValuePair> nameValuePairs = new ArrayList<>(1);

                nameValuePairs.add(new BasicNameValuePair("searchdata", searchtext));

                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = client.execute(post);

                if(response.getStatusLine().getStatusCode()==200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);

                    JSONObject jsonObject = new JSONObject(data);
                    jsonArray = jsonObject.getJSONArray("category");
                    jsonArray1 = jsonObject.getJSONArray("products");

                    if(jsonArray.length() > 1){
                        firstBool = true;

                    }
                    else {
                        firstBool = false;
                    }
                    if(jsonArray1.length() > 1){
                        secondBool = true;
                    }
                    else {
                        secondBool = false;
                    }

                    JSONArray result = new JSONArray();
                    if(firstBool){
                        for (int i = 0; i < jsonArray.length(); i++) {
                            result.put(jsonArray.get(i));
                        }
                    }
                    if(secondBool){
                        for (int i = 0; i < jsonArray1.length(); i++) {
                            result.put(jsonArray1.get(i));
                        }
                    }
                    for(int i=0;i<result.length();i++){
                        Log.d("resukt",result+"");
                        JSONObject jsonObject1 = result.getJSONObject(i);

                        SearchItem search = new SearchItem();

                        search.setName(jsonObject1.getString("name"));
                        search.setid(jsonObject1.getString("id"));
                        search.setSvalue(jsonObject1.getString("svalue"));
                        SearchItem.add(search);

                    }


                 /*   JSONArray mainJson = concatArray(jsonArray,jsonArray1);

                    for(int i=0;i<mainJson.length();i++){
                        JSONObject jsonObject1 = mainJson.getJSONObject(i);

                        SearchItem search = new SearchItem();

                        search.setName(jsonObject1.getString("name"));
                        search.setid(jsonObject1.getString("id"));
                        search.setSvalue(jsonObject1.getString("svalue"));
                        SearchItem.add(search);

                    }*/



                  /*  if (jsonArray.length() > 1) {


                    for (int i = 0; i < jsonArray.length(); i++) {

                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);

                        SearchItem search = new SearchItem();

                        search.setName(jsonObject1.getString("name"));
                        search.setid(jsonObject1.getString("id"));
                        search.setSvalue(jsonObject1.getString("svalue"));
                        SearchItem.add(search);
                    }
                }*/



                /*    if (jsonArray.length() > 1) {
                        for (int i = 0; i < jsonArray1.length(); i++) {
                            JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
                            SearchItem search = new SearchItem();

                            search.setName(jsonObject1.getString("name"));
                            search.setid(jsonObject1.getString("pid"));
                            search.setSvalue(jsonObject1.getString("svalue"));
                            SearchItem.add(search);

                        }
                    }*/
                }
                else {
                    trycatch = false;
                }

            }catch (IOException |JSONException e){
                Log.e("Error :", e.getMessage());
                trycatch = false;
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            //super.onPostExecute(aVoid);
            // dialog.dismiss();
            if(trycatch) {
                adapter.notifyDataSetChanged();
                adapter = new SearchAdapter(SearchActivity.this,R.layout.search_item_show,SearchItem);
                listview.setAdapter(adapter);
                adapter.notifyDataSetChanged();
               /* try {
                  concatArray(jsonArray,jsonArray1);
                }
                catch (Exception e){
                    e.getMessage();
                }*/

            }
            else {
                Toast.makeText(SearchActivity.this,"Something is bad happen try again later",Toast.LENGTH_LONG).show();
            }
        }
    }
    public class SearchItemActionFind extends AsyncTask<String,Void,Void>{
        Boolean result ,trycatch = true;
        JSONArray jsonArray;
        JSONArray jsonArray1;
        Boolean firstBool,secondBool;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            searchtext = editText.getText().toString();
            SearchItem.clear();
            adapter.notifyDataSetChanged();
        }

        @Override
        protected Void doInBackground(String... params) {
            try{
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(params[0]);
                List<NameValuePair> nameValuePairs = new ArrayList<>(1);

                nameValuePairs.add(new BasicNameValuePair("searchdata", searchtext));

                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = client.execute(post);

                if(response.getStatusLine().getStatusCode()==200){
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);

                    JSONObject jsonObject = new JSONObject(data);
                    jsonArray = jsonObject.getJSONArray("category");
                    jsonArray1 = jsonObject.getJSONArray("products");
                    if(jsonArray.length() > 1){
                        firstBool = true;

                    }
                    else {
                        firstBool = false;
                    }
                    if(jsonArray1.length() > 1){
                        secondBool = true;
                    }
                    else {
                        secondBool = false;
                    }

                    JSONArray result = new JSONArray();
                    if(firstBool){
                        for (int i = 0; i < jsonArray.length(); i++) {
                            result.put(jsonArray.get(i));
                        }
                    }
                    if(secondBool){
                        for (int i = 0; i < jsonArray1.length(); i++) {
                            result.put(jsonArray1.get(i));
                        }
                    }
                    for(int i=0;i<result.length();i++){
                        JSONObject jsonObject1 = result.getJSONObject(i);

                        SearchItem search = new SearchItem();

                        search.setName(jsonObject1.getString("name"));
                        search.setid(jsonObject1.getString("id"));
                        search.setSvalue(jsonObject1.getString("svalue"));
                        SearchItem.add(search);

                    }


                  /*  if (jsonArray.length() > 1) {
                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);

                            SearchItem search = new SearchItem();

                            search.setName(jsonObject1.getString("name"));
                            search.setid(jsonObject1.getString("id"));
                            search.setSvalue(jsonObject1.getString("svalue"));
                            SearchItem.add(search);
                        }
                    }*/


                 /*   if (jsonArray.length() > 1) {
                        for (int i = 0; i < jsonArray1.length(); i++) {
                            JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
                            SearchItem search = new SearchItem();

                            search.setName(jsonObject1.getString("name"));
                            search.setid(jsonObject1.getString("id"));
                            search.setSvalue(jsonObject1.getString("svalue"));
                            SearchItem.add(search);

                        }
                    }*/
                }

            }catch (IOException |JSONException e){
                // Log.e("Error :", e.getMessage());
                trycatch = false;
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            //super.onPostExecute(aVoid);
            // dialog.dismiss();
            if(trycatch) {
                adapter.notifyDataSetChanged();
                adapter = new SearchAdapter(SearchActivity.this,R.layout.search_item_show,SearchItem);
                listview.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
            else {
                Toast.makeText(SearchActivity.this,"Something is bad happen try again later",Toast.LENGTH_LONG).show();
            }
        }
    }
}

我是android開發的新手,請幫助我讓我擺脫這個錯誤。

這是因為您要在后台線程中更改適配器中使用的數組。 您正在致電:

SearchItem.add(search);

doInbackground方法中。 而是在onPostExecute方法中執行此onPostExecute

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM