簡體   English   中英

如何修復adapter.notifyDataSetChanged(); 不起作用

[英]How to fix adapter.notifyDataSetChanged(); doesn't work

public class SemuaData extends AppCompatActivity implements ListView.OnItemClickListener, SearchView.OnQueryTextListener {
private ListView list_view;
private String JSON_STRING;

List<DataModel> listData = new ArrayList<DataModel>();
Adapter adapter;

private static final String TAG = MainActivity.class.getSimpleName();

public static final String TAG_ID = "id";
public static final String TAG_NAMA = "nama";
public static final String TAG_UMUR = "umur";
public static final String TAG_ALAMAT = "alamat";

public static final String TAG_RESULTS = "results";
public static final String TAG_MESSAGE = "message";
public static final String TAG_VALUE = "value";

String tag_json_obj = "json_obj_req";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_semua_data);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    list_view = (ListView) findViewById(R.id.list_view);
    list_view.setOnItemClickListener(this);
    getJSON();
}
private void showEmployee(){
    JSONObject jsonObject = null;
    ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
    try {
        jsonObject = new JSONObject(JSON_STRING);
        JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);

        for(int i = 0; i<result.length(); i++){
            JSONObject jo = result.getJSONObject(i);
            String id = jo.getString(Config.TAG_ID);
            String name = jo.getString(Config.TAG_NAMA);

            HashMap<String,String> employees = new HashMap<>();
            employees.put(Config.TAG_ID,id);
            employees.put(Config.TAG_NAMA,name);
            list.add(employees);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    ListAdapter adapter = new SimpleAdapter(
            SemuaData.this, list, R.layout.list_item,
            new String[]{Config.TAG_ID,Config.TAG_NAMA},
            new int[]{R.id.id, R.id.nama});

    list_view.setAdapter(adapter);
}

private void getJSON(){
    class GetJSON extends AsyncTask<Void,Void,String> {

        ProgressDialog loading;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(SemuaData.this,"Mengambil Data","Tunggu...",false,false);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            JSON_STRING = s;
            showEmployee();
        }

        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            String s = rh.sendGetRequest(Config.URL_GET_ALL);
            return s;
        }
    }
    GetJSON gj = new GetJSON();
    gj.execute();
}

@Override
public boolean onQueryTextSubmit(String query) {
    cariData(query);
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    return false;
}

@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    final MenuItem item = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
    searchView.setQueryHint(getString(R.string.type_name));
    searchView.setIconified(true);
    searchView.setOnQueryTextListener(this);
    return true;
}

private void cariData(final String keyword) {

    StringRequest strReq = new StringRequest(Request.Method.POST, Config.url_cari, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.e("DATA RESPONSE SEARCH : ", response.toString());

            try {
                JSONObject jObj = new JSONObject(response);

                int value = jObj.getInt(TAG_VALUE);

                if (value == 1) {
                    listData.clear();
                    adapter.notifyDataSetChanged();//Here is the error

                    String getObject = jObj.getString(TAG_RESULTS);
                    JSONArray jsonArray = new JSONArray(getObject);

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

                        DataModel data = new DataModel();

                        data.setId(obj.getString(TAG_ID));
                        data.setNama(obj.getString(TAG_NAMA));
                        data.setUmur(obj.getString(TAG_UMUR));
                        data.setAlamat(obj.getString(TAG_ALAMAT));
                        listData.add(data);
                    }

                } else {
                    Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
            }

            adapter.notifyDataSetChanged();//Here is the error
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("keyword", keyword);
            return params;
        }
    };
    AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent(this, DetailData.class);
    HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
    String mhsid = map.get(Config.TAG_ID).toString();
    intent.putExtra(Config.MHS_ID, mhsid);
    startActivity(intent);
}

這是我的logcat

 05-31 09:33:35.897 6535-6535/com.contoh.jalikk.tumbal E/DATA RESPONSE SEARCH :: {"value":1, "results": [{ "id": "2", "nama": "ijal", "umur": "18", "alamat": "uber" }]} 05-31 09:33:35.898 6535-6535/com.contoh.jalikk.tumbal E/AndroidRuntime: FATAL EXCEPTION: main Process: com.contoh.jalikk.tumbal, PID: 6535 java.lang.NullPointerException: Attempt to invoke virtual method 'void 

com.contoh.jalikk.tumbal.SemuaData $ 1.onResponse(SemuaData.java:178)上com.contoh.jalikk.tumbal上的空對象引用上的com.contoh.jalikk.tumbal.search.Adapter.notifyDataSetChanged()'。 SecomaData $ 1.onResponse(SemuaData.java:165)位於com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)位於com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) com.android.volley.ExecutorDelivery $ ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)位於android.os.Handler.handleCallback(Handler.java:739)位於android.os.Handler.dispatchMessage(Handler.java:95) .os.Looper.loop(Looper.java:179)在android.app.ActivityThread.main(ActivityThread.java:5730)在com.android.internal.os的java.lang.reflect.Method.invoke(本機方法) .com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)上的.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:791)05-31 09:33:36.032 3019-4921 /? E / ErrorSaveTask:/data/system/dropbox/data_app_crash@1527734016024.txt.gz日志未找到! 05-31 09:33:36.032 3019-4921 /? E / ErrorSaveTask:verifyError():發生時間為空或應用名稱為空,返回false

您正在對空適配器對象調用notifyDataSetChanged()。 首先初始化適配器。 在showEmployee方法中,您正在初始化本地適配器對象。 而是初始化全局適配器對象。

這是您修改的代碼,請替換代碼並檢查:

public class SemuaData extends AppCompatActivity implements ListView.OnItemClickListener, SearchView.OnQueryTextListener {
    private ListView list_view;
    private String JSON_STRING;

    List<DataModel> listData = new ArrayList<DataModel>();

    private static final String TAG = MainActivity.class.getSimpleName();

    public static final String TAG_ID = "id";
    public static final String TAG_NAMA = "nama";
    public static final String TAG_UMUR = "umur";
    public static final String TAG_ALAMAT = "alamat";

    public static final String TAG_RESULTS = "results";
    public static final String TAG_MESSAGE = "message";
    public static final String TAG_VALUE = "value";

    String tag_json_obj = "json_obj_req";
    ListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_semua_data);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        list_view = (ListView) findViewById(R.id.list_view);
        list_view.setOnItemClickListener(this);
        getJSON();
    }

    private void showEmployee() {
        JSONObject jsonObject = null;
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        try {
            jsonObject = new JSONObject(JSON_STRING);
            JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);

            for (int i = 0; i < result.length(); i++) {
                JSONObject jo = result.getJSONObject(i);
                String id = jo.getString(Config.TAG_ID);
                String name = jo.getString(Config.TAG_NAMA);

                HashMap<String, String> employees = new HashMap<>();
                employees.put(Config.TAG_ID, id);
                employees.put(Config.TAG_NAMA, name);
                list.add(employees);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        adapter = new SimpleAdapter(
                SemuaData.this, list, R.layout.list_item,
                new String[]{Config.TAG_ID, Config.TAG_NAMA},
                new int[]{R.id.id, R.id.nama});

        list_view.setAdapter(adapter);
    }

    private void getJSON() {
        class GetJSON extends AsyncTask<Void, Void, String> {

            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(SemuaData.this, "Mengambil Data", "Tunggu...", false, false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                showEmployee();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequest(Config.URL_GET_ALL);
                return s;
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        cariData(query);
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        final MenuItem item = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setQueryHint(getString(R.string.type_name));
        searchView.setIconified(true);
        searchView.setOnQueryTextListener(this);
        return true;
    }

    private void cariData(final String keyword) {

        StringRequest strReq = new StringRequest(Request.Method.POST, Config.url_cari, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.e("DATA RESPONSE SEARCH : ", response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);

                    int value = jObj.getInt(TAG_VALUE);

                    if (value == 1) {
                        listData.clear();
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();//Here is the error
                        }

                        String getObject = jObj.getString(TAG_RESULTS);
                        JSONArray jsonArray = new JSONArray(getObject);

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

                            DataModel data = new DataModel();

                            data.setId(obj.getString(TAG_ID));
                            data.setNama(obj.getString(TAG_NAMA));
                            data.setUmur(obj.getString(TAG_UMUR));
                            data.setAlamat(obj.getString(TAG_ALAMAT));
                            listData.add(data);
                        }

                    } else {
                        Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                }

                if (adapter != null) {
                    adapter.notifyDataSetChanged();//Here is the error
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("keyword", keyword);
                return params;
            }
        };
        AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, DetailData.class);
        HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
        String mhsid = map.get(Config.TAG_ID).toString();
        intent.putExtra(Config.MHS_ID, mhsid);
        startActivity(intent);
    }
}

暫無
暫無

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

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