简体   繁体   中英

Passing data to recycler adapter with getter and setter problem

I'm trying to pass a string from my Main.java class to my RecyclerAdapter with getter and setters but I can't get it to work. I have read through all kinds of suggestions here at StackOverflow but still, I can't it to work. I hope someone can help.

Main.java

private List<ProjectId> projectIdList;

protected void onStart() { 
    ProjectId projectId = new ProjectId();
    projectId.setProjectId(dataSnapshot.getKey());
    projectIdList.add(projectId);
}

ProjectId.java

public class ProjectId {

public String projectId;

public String getProjectId() {
    return projectId;
}

public void setProjectId(String projectID) {
    this.projectId = projectId;
}
}

RecyclerAdapter.java

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    private ProjectId projectId;
    private String projectID;

    public ViewHolder(View view, Context ctx) {
        projectID = projectId.getProjectId();
    }


}

It is returning this error:

Attempt to invoke virtual method 'java.lang.String Services.ProjectId.getProjectId()' on a null object reference

I know that I have a value from dataSnapshot.getKey() . Is this the right way to try to do this or is there any other way? I appreciate all help.

tl;dr: You are getting NullPointerException because you are using projectId in ViewHolder constructor without initializing it first.

It's very clear that you are creating an object of ProjectId in onStart() and then you are setting its project_id as setProjectId() but you have not passed this object to the Adapter/ViewHolder class whatsoever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM