当前位置: 首页 > 知识库问答 >
问题:

如何修复Adapter.NotifyDataSetChanged();不起作用

吴哲
2023-03-14
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.search.adapter.NotifyDataSetChanged()'在com.contoh.jalikk.tumbal.semuadata$1的空对象引用上。onresponse(semuadata.java:178)在com.contoh.jalikk.tumbal.semuadata$1的onresponse(semuadata.java:165)在com.android.volle.toolbox.stringrequest.deliverresponse(stringrequest.deliverresponse(stringrequest.java:60)在E/errorsavetask:/data/system/dropbox/data_app_crash@1527734016024.txt.gz日志找不到!05-31 09:33:36.032 301 9-4921/?E/ErrorSaveTask:verifyError():发生时间为空或应用程序名称为空,返回false

共有1个答案

微生宝
2023-03-14

这里是您修改的代码,替换您的代码并检查:

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);
    }
}
 类似资料:
  • 这里是我的pom.xml 4.0.0 org.springframework.Boot spring-boot-starter-parent 2.3.2.release com.king Gestpeacesecurity 0.0.1-snapshot Gestpeacesecurity用于Spring Boot的和平安全项目 我的实体代理,我使用lomback作为getter和setter 这是

  • 问题内容: 我一直在为iPad的固定位置而苦苦挣扎。我知道iScroll,它似乎并不总是有效(即使在他们的演示中)。我也知道Sencha有一个修复程序,但是我不能+该修复程序的源代码。 我希望有人可以解决。问题在于,当用户在iOS驱动的移动Safari上上/下移动时,固定位置的元素不会更新。 问题答案: 我最终使用了新的jQuery Mobilev1.1: 现在,我们进行了可靠的重写,可以在许多流

  • 我是JSTL新手,由于某种原因,我无法让测试线工作。以下是我使用的简化代码: 当我使用 ${hasChild} 它在屏幕上打印真实,但在测试线上不会发出嗡嗡声,我不知道为什么。有人能帮忙吗?

  • 问题内容: 我正在尝试从字符串中修剪前导空格,并且我不知道我的方法有什么问题,请提出任何建议? 码: 我正在从csv文件中读取poNumber为“ IG078565和IG083060”,并且输出也使用相同的空格获得相同的值,不确定为什么吗? 更新 添加完整的方法以获得更好的上下文: 谢谢。 问题答案: 更新 看来您的空格不是空格(ascii = 32)。您的代码为160,这是一个不间断的空格。不处

  • 我试图用Spring启动制作一个“你好世界”控制器,但GET请求不起作用。我能做些什么来修复这个问题? 我在https://start.spring.io/在我选择的依赖项中 我尝试使用不同的注释,如@GetMap 我希望输出为“Hello World”,但实际输出为“Whitelabel Error Page”

  • 我试图做一个简单的rest服务,遵循几个教程和文档,但没有工作。主要是http://docs.jboss.org/seam/2.1.1.ga/reference/en-美国/html/webservices.html#D0E21523 在web.xml中有以下内容: 我的类是这样的: 根据文档,不需要做任何其他事情来使RESTeasy工作。但如果我去