Home > Back-end >  RecyclerView on a null object reference
RecyclerView on a null object reference

Time:12-12

I've been trying to get data on the RecycleView for a day now, but it doesn't work. An error comes out:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.tokenauth, PID: 8011 java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference at com.example.tokenauth.Home.PutDataIntoRecyclerView(Home.java:74) at com.example.tokenauth.Home.access$000(Home.java:25) at com.example.tokenauth.Home$1.onResponse(Home.java:56) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68) at android.os.Handler.handleCallback(Handler.java:888) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:213) at android.app.ActivityThread.main(ActivityThread.java:8178) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101) Please explain what is my mistake P.S sorry for my English

JSON type

{
   "list":[
      {
         "Id":2,
         "Name":"temp",
         "Description":"Danger"
      },
      {
         "Id":1,
         "Name":"Water",
         "Description":"Danger"
      }
   ],
   "pageInfo":{
      "totalRows":2,
      "page":1,
      "pageSize":25,
      "isFirstPage":true,
      "isLastPage":true
   }
}

Interface.class

@GET("views/Notification")
Call<NotificationArray>getCarsJson();

ModelArray.class

public class NotificationArray {
    private CarsModel[] list;
    public CarsModel[] getList() {
        return list;
    }

    public void setMoviz(CarsModel[] list) {
        this.list = list;
    }
}

Home.class

public class Home extends AppCompatActivity {
RecyclerView recyclerView;

List<CarsModel> carsModels;
private CarsAdapter carsAdapter;
private RecyclerView cars_recyclerview;
NotificationArray notificationArray;

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

    cars_recyclerview=(RecyclerView)findViewById(R.id.cars_recyclerview);
    carsModels = new ArrayList<>();

    getCarsResponse();


}

public void getCarsResponse(){
    APIService service = ApiClient.getClient().create(APIService.class);
    Call<NotificationArray> call=service.getCarsJson();
    call.enqueue(new Callback<NotificationArray>() {
        @Override
        public void onResponse(Call<NotificationArray> call, Response<NotificationArray> response) {


            NotificationArray notificationArray= response.body();
            carsModels= new ArrayList<>(Arrays.asList(notificationArray.getList()));
            PutDataIntoRecyclerView(carsModels);


            Toast.makeText(Home.this,"Success",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<NotificationArray> call, Throwable t) {
            Toast.makeText(Home.this,"Failed",Toast.LENGTH_SHORT).show();
            Log.e("failure",t.getLocalizedMessage());
        }

    });
}

private void PutDataIntoRecyclerView(List<CarsModel> carsModels) {
    CarsAdapter carsAdapter = new CarsAdapter( this, carsModels);
    cars_recyclerview.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(carsAdapter);

}

Model.class

public class CarsModel {



    @SerializedName("Id")
    @Expose
    private String Id;
    @SerializedName("Name")
    @Expose
    private String Name;
    @SerializedName("Description")
    @Expose
    private String Description;

    public String getId() {
        return Id;
    }

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

    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public String getDescription() {
        return Description;
    }

    public void getDescription(String Description) {
        this.Description = Description;
    }


}

Adapter.class

public class CarsAdapter extends RecyclerView.Adapter<CarsAdapter.ViewHolder> {

    private List<CarsModel> carsModels;
    private Context context;


    public CarsAdapter(Context context, List<CarsModel> carsModels) {
        this.carsModels=carsModels;
        this.context=context;
    }

    @NonNull
    @Override
    public CarsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cars_list_item,viewGroup,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CarsAdapter.ViewHolder viewHolder, int i) {
        viewHolder.car_name.setText(carsModels.get(i).getName());
        viewHolder.car_desc.setText(carsModels.get(i).getDescription());


    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TextView car_name,car_desc;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);


            car_name=(TextView) itemView.findViewById(R.id.car_name);
            car_desc=(TextView)itemView.findViewById(R.id.car_desc);
        }
    }
}

I've been trying to get data on the RecycleView for a day now, but it doesn't work. An error comes out:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.tokenauth, PID: 8011 java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference at com.example.tokenauth.Home.PutDataIntoRecyclerView(Home.java:74) at com.example.tokenauth.Home.access$000(Home.java:25) at com.example.tokenauth.Home$1.onResponse(Home.java:56) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68) at android.os.Handler.handleCallback(Handler.java:888) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:213) at android.app.ActivityThread.main(ActivityThread.java:8178) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101) Please explain what is my mistake P.S sorry for my English

CodePudding user response:

Inside Your Home Class:

private void PutDataIntoRecyclerView(List<CarsModel> carsModels) {
CarsAdapter carsAdapter = new CarsAdapter( this, carsModels);
cars_recyclerview.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(carsAdapter);
}

In The Last Code Line Change recyclerView.setAdapter(carsAdapter); to cars_recyclerview.setAdapter(carsAdapter);

Making it:

private void PutDataIntoRecyclerView(List<CarsModel> carsModels) {
CarsAdapter carsAdapter = new CarsAdapter( this, carsModels);
cars_recyclerview.setLayoutManager(new LinearLayoutManager(this));
cars_recyclerview.setAdapter(carsAdapter);
}

CodePudding user response:

Change your recycler view object in PutDataIntoRecyclerView(last line of the function) from recyclerView -> cars_recyclerview

and also, You have created the object of adapter twice 1st at global scope and 2nd at PutDataIntoRecyclerView method. and you also need to remove the recyclerview object(RecyclerView recyclerView;) created at global scope of you are not use it.

  • Related