-1

please dont mark my question as duplicate as none of the solutions wotked for me

i was trying to pass value from adapter to another activity through interface.......

the error shows at this evrytime :--- data clickedItem = mdata.get(position);

giving as

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference

following is my code :------------------- Adapter :---

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
Context mContext;
 List<data> mExampleList;
 OnItemClickListener mListener;
public interface OnItemClickListener {
    void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
}
public ExampleAdapter(Context context,List<data> exampleList) {
    mContext = context;
    mExampleList = exampleList;
}
@Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.employeelist, parent, false);
    ExampleViewHolder evh = new ExampleViewHolder(v);
    return evh;
}
@Override
public void onBindViewHolder(ExampleViewHolder holder, final int position) {
    data currentItem = mExampleList.get(position);

    Picasso.get().load(currentItem.getAvatar()).into(holder.mimageView);

    holder.mtextview1.setText(String.format("%s %s", currentItem.getFirst_name(), currentItem.getLast_name()));
    holder.mtextveiew2.setText(currentItem.getEmail());
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mListener.onItemClick(position);

        }
    });

}
@Override
public int getItemCount() {
    return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder {
    public ImageView mimageView;
    public TextView mtextview1;
    public TextView mtextveiew2;
    public ExampleViewHolder(View itemView) {
        super(itemView);
        mimageView = itemView.findViewById(R.id.imageView);
        mtextview1 = itemView.findViewById(R.id.textView1);
        mtextveiew2 = itemView.findViewById(R.id.textView2);

    }
}

}

Another activity:--

public class Details extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_details);
    textView=findViewById(R.id.tvEmail);
    Intent intent = getIntent();

    String emailadd = intent.getStringExtra("email");
    textView.setText(emailadd);

}

}

Sample pojo :--

public class SampleResponse {
@SerializedName("page")
@Expose
private String page;
@SerializedName("per_page")
@Expose
private String per_page;
@SerializedName("total")
@Expose
private String total;
@SerializedName("total_pages")
@Expose
private String total_pages;
@SerializedName("data")
@Expose
private List<data> dataArray = null;

public String getPage() {
    return page;
}

public void setPage(String page) {
    this.page = page;
}

public String getPer_page() {
    return per_page;
}

public void setPer_page(String per_page) {
    this.per_page = per_page;
}

public String getTotal() {
    return total;
}

public void setTotal(String total) {
    this.total = total;
}

public String getTotal_pages() {
    return total_pages;
}

public void setTotal_pages(String total_pages) {
    this.total_pages = total_pages;
}

public List<data> getDataArray() {
    return dataArray;
}

public void setDataArray(List<data> dataArray) {
    this.dataArray = dataArray;
}

}

data pojo:--

public class data {
@SerializedName("id")
@Expose
private String id;
@SerializedName("first_name")
@Expose
private String first_name;
@SerializedName("last_name")
@Expose
private String last_name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("avatar")
@Expose
private String avatar;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getFirst_name() {
    return first_name;
}

public void setFirst_name(String first_name) {
    this.first_name = first_name;
}

public String getLast_name() {
    return last_name;
}

public void setLast_name(String last_name) {
    this.last_name = last_name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getAvatar() {
    return avatar;
}

public void setAvatar(String avatar) {
    this.avatar = avatar;
}

}

main activity:--

public class MainActivity extends AppCompatActivity implements ExampleAdapter.OnItemClickListener {
 RecyclerView mRecyclerView;
 ExampleAdapter mAdapter;
 RecyclerView.LayoutManager mLayoutManager;
 List<data> mdata;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    mRecyclerView = findViewById(R.id.recyclerView);
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    
    jsonparse();
}

private void jsonparse() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://reqres.in/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    EmployeeAPI request = retrofit.create(EmployeeAPI.class);
    Call<SampleResponse> call1 = request.getJson(10);
    call1.enqueue(new Callback<SampleResponse>() {
        @Override
        public void onResponse(Call<SampleResponse> call, retrofit2.Response<SampleResponse> response) {

            List<data> exampleList = response.body().getDataArray();
            mAdapter = new ExampleAdapter(MainActivity.this,exampleList);
            mRecyclerView.setAdapter(mAdapter);
            mAdapter.setOnItemClickListener(MainActivity.this);

        }

        @Override
        public void onFailure(Call<SampleResponse> call, Throwable t) {
        }
    });
}

@Override
public void onItemClick(int position) {
    Intent detailIntent = new Intent(this, Details.class);
    data clickedItem = mdata.get(position);
    detailIntent.putExtra("email", clickedItem.getEmail());
    startActivity(detailIntent);
}
IRON MAN
  • 191
  • 3
  • 18

1 Answers1

1

Your issue with the NullPointerException is due to your variable List<data> mdata; on the activity.

The reason it is crashing is because you've declared variable List<data> mdata; but never assigned value to it, thus it eventually crash due to 'null pointer' because there's no value to read from that variable.

I would suggest following modification on your activity to fix your issue temporarily but still permanent fix would be refactor on OnItemClickListener.

Temporary fix:

On your jsonparse() method, you'll need to assign value to mdata and then use it afterwards like below code snippet:

mdata = response.body().getDataArray(); // remove local variable from here and assign value directly to mdata
mAdapter = new ExampleAdapter(MainActivity.this, mdata); // instead of local variable exampleList, you now pass mdata

This will fix your issue temporarily

Permanent fix:

To fix this properly, I would suggest following refactor (I recommend this approach because it would be less error prone and doesn't require you to have local variable on activity).

Instead of passing position from adapter to activity, you should instead pass variable directly via method, so that you don't end up storing list locally.

Modified interface:

public interface OnItemClickListener {
    void onItemClick(data selectedData);
}

& During onClick on adapter item, use it like this: mListener.onItemClick(mExampleList.get(position));

This also changes your code on activity where you override method:

@Override
public void onItemClick(data selectedData) {
    Intent detailIntent = new Intent(this, Details.class);
    detailIntent.putExtra("email", selectedData.getEmail());
    startActivity(detailIntent);
}
Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58