适配器notifyDataSetChanged之后的Android更新imageview

时间:2016-06-10 06:39:07

标签: android android-recyclerview android-adapter

在我的适配器中并从服务器检索数据我可以重新加载recyclerview,在我的recyclerview项中,我有简单的imageView,在从服务器和图像状态检索数据后,我必须更改其中的图像,但重新加载数据和notifyDataSetChanged之后我的适配器无法更新图像。

我可以通过以下代码在upadte数据库之后通过syncByServer我的方法从服务器检索数据:

ContactLists exists_row = realm.where(ContactLists.class).equalTo("mobile_number", mobileNumber).findFirst();
realm.beginTransaction();
if (exists_row != null) {
    exists_row.setIsRegistered("1");
} else {
    exists_row.setIsRegistered("0");
}
realm.commitTransaction();
<{1>} setIsRegistered必须更改图片状态,如果setIsRegistered为1,则必须从setImageDrawable设置Drawable

MainActivity:

realm = Realm.getDefaultInstance();
recyclerView = (RecyclerView) findViewById(R.id.rcontactLists);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new ContactsAdapter(results, getApplication());
recyclerView.setAdapter(adapter);
long contact_count = realm.where(ContactLists.class).count();
if (contact_count > 0) {
    reloadFromDatabase();
} else {
    long count = Utils.getLocalContactsList(getContentResolver(), realm);
    if (count > 0) {
        reloadFromDatabase();
    }
    syncByServer();
}

/*----------------------------------------------------------*/

private void reloadFromDatabase() {
    results = realm.where(ContactLists.class).findAll();
    adapter.setData(results);
    adapter.notifyDataSetChanged();
}

private void syncByServer() {
    long count = Utils.getLocalContactsList(getContentResolver(), realm);
    if (count > 0) {
        showProgressDialog();
        results = realm.where(ContactLists.class).findAll();
        ArrayList wordList = new ArrayList<>();
        if (results.size() > 0) {
            for (ContactLists c : results) {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("contactName", c.getContact_name());
                map.put("mobileNumber", c.getMobile_number());
                wordList.add(map);
            }
        }

        String fetch_server_url = SampleApplication.getHostAddress() + "clientSyncContatcLists";

        HttpsTrustManager.allowAllSSL();
        JsonArrayRequest req = new JsonArrayRequest(fetch_server_url, new JSONArray(wordList),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject jsonObject   = response.getJSONObject(i);
                                String     mobileNumber = jsonObject.getString("mobileNumber");

                                ContactLists exists_row = realm.where(ContactLists.class).equalTo("mobile_number", mobileNumber).findFirst();

                                realm.beginTransaction();
                                if (exists_row != null) {
                                    exists_row.setIsRegistered("1");
                                } else {
                                    exists_row.setIsRegistered("0");
                                }
                                realm.commitTransaction();

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

                        results = realm.where(ContactLists.class).findAll();
                        adapter.setData(results);
                        adapter.notifyDataSetChanged();
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Log.e
            }
        });
        EpayApplication.getInstance().addToRequestQueue(req);
    } else {
        Utils.toast(Utils.getString(R.string.there_is_no_contacts), getBaseContext());
    }
}

我的适配器

public class ContactsAdapter extends RecyclerView.Adapter<CustomContactsViewHolder> {

    List<ContactLists> list = Collections.emptyList();
    Context context;

    public ContactsAdapter(List<ContactLists> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public CustomContactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View                     v      = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_item, parent, false);
        CustomContactsViewHolder holder = new CustomContactsViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(CustomContactsViewHolder holder, int position) {
        holder.title.setText(list.get(position).getContact_name());
        holder.description.setText(list.get(position).getMobile_number());
        if (list.get(position).getIsRegistered().equals("1"))
            holder.img_logo.setImageDrawable(context.getResources().getDrawable(R.drawable.epay_logo));
        else
            holder.img_logo.setVisibility(View.INVISIBLE);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    public void setData(List<ContactLists> list) {
        this.list = list;
    }
}

1 个答案:

答案 0 :(得分:0)

你可能遇到了NPE。发布的代码片段保证 exists_row 在else分支中 null

if (exists_row != null) {
   exists_row.setIsRegistered("1");
} else {
   exists_row.setIsRegistered("0");
}

还有一个问题,为什么IDE没有警告你呢?

OR exists_row 绝不 null 。我认为这可能是这种情况,因为你没有写过应用程序崩溃。调试该行以查看到底发生了什么。