无法将notifyDataSetChanged()与RecyclerView一起使用,会导致NullPointerException

时间:2015-10-27 00:13:43

标签: java android android-recyclerview

我正在尝试使用RecyclerView实施CardView。但是,当我从云加载数据时,我需要使用notifyDataSetChanged()方法来更新视图,但这样做会导致我的自定义适配器类中出现NullPointerException

以下是我在主要活动中的表现:

public class BigBoard extends ActionBarActivity {

private List<Person> persons;
private RecyclerView rv;
RVAdapter adapter;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Parse.initialize(this, "app-id", "client-key");
    setContentView(R.layout.activity_big_board);
    adapter = new RVAdapter(persons);


    rv=(RecyclerView)findViewById(R.id.rv);

    LinearLayoutManager llm = new LinearLayoutManager(this);
    rv.setLayoutManager(llm);
    rv.setHasFixedSize(true);

    initializeData();
    initializeAdapter();

}

private void initializeData(){
    persons = new ArrayList<>();

    ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Credentials");
    query.findInBackground(new FindCallback<ParseObject>() {
        public void done(List<ParseObject> credentialList, ParseException e) {
            if (e == null) {
                for(int i=0;i<credentialList.size();i++)
                {
                    persons.add(new Person(credentialList.get(i).getString("Name"), credentialList.get(i).getString("SurName")));



                    Log.d("OUT", "So the Val::------> " + persons);
                    adapter.notifyDataSetChanged();// <---- Problem line

                }
            } else {
                Log.d("score", "Error: " + e.getMessage());
            }
        }
    });


}




private void initializeAdapter(){

    rv.setAdapter(adapter);
}

以下是Adapter类的代码:

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {

public static class PersonViewHolder extends RecyclerView.ViewHolder {

    CardView cv;
    TextView personName;
    TextView personAge;
    //ImageView personPhoto;

    PersonViewHolder(View itemView) {
        super(itemView);
        cv = (CardView)itemView.findViewById(R.id.cv);
        personName = (TextView)itemView.findViewById(R.id.person_name);
        personAge = (TextView)itemView.findViewById(R.id.person_age);
        //personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
    }
}

List<Person> persons;

RVAdapter(List<Person> persons){
    this.persons = persons;
}

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

@Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
    PersonViewHolder pvh = new PersonViewHolder(v);
    return pvh;
}

@Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
    personViewHolder.personName.setText(persons.get(i).name);
    personViewHolder.personAge.setText(persons.get(i).surname);
   // personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
}

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

我相信return persons.size();这是每次调用notifyDataSetChanged()时导致NullPointerException的行,因为我猜这是空的或者是这样! 问题是如何解决这个问题?

这里也是logcat:

>  java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
            at obx.com.futurister.RVAdapter.getItemCount(RVAdapter.java:58)
            at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2357)
            at android.view.View.measure(View.java:18788)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
            at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1112)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:632)
            at android.view.View.measure(View.java:18788)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
            at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
            at android.view.View.measure(View.java:18788)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
            at android.view.View.measure(View.java:18788)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
            at android.view.View.measure(View.java:18788)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
            at android.view.View.measure(View.java:18788)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
            at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
            at android.view.View.measure(View.java:18788)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
            at android.view.Choreographer.doCallbacks(Choreographer.java:670)
            at android.view.Choreographer.doFrame(Choreographer.java:606)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:2)

在调用任何方法之前,您需要初始化列表persons

您只需更改以下

即可
List<Person> persons;

 List<Person> persons = new ArrayList<Person>();
  

OR

您可以将现有的getItemCount方法更新为以下

@Override
public int getItemCount() {
    if(persons!=null){
        return persons.size();  
    } else{
        return 0;
    }        
}