kotlin 空对象引用上的RecyclerView

hs1ihplo  于 2022-12-13  发布在  Kotlin
关注(0)|答案(1)|浏览(99)

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);

}

}
MainActivity.class

public class MainActivity extends AppCompatActivity {
    EditText username_et,password_et;
    SharedPreferences _objpref;
    private APIService service;
    Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnLogin=(Button)findViewById(R.id.btn_Login);
        username_et=(EditText) findViewById(R.id.username);
        password_et=(EditText)findViewById(R.id.password);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CallLoginService();
            }
        });
    }
    private void CallLoginService() {

        try {
            final String username = username_et.getText().toString();
            final String password = password_et.getText().toString();

            APIService service = ApiClient.getClient().create(APIService.class);
            Call<ResponseBody> srvLogin = service.getToken( username, password);
            srvLogin.enqueue(new Callback<ResponseBody>() {

                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        try {
                            String ResponseJson = response.body().string();
                            Gson objGson = new Gson();
                            tokenResponse objResp = objGson.fromJson(ResponseJson, tokenResponse.class);
                            Toast.makeText(MainActivity.this, objResp.getAccess_token(), Toast.LENGTH_LONG).show();
                            Log.i(TAG,"MyClass.getView() — get item number " + objResp);

                            Intent intent = new Intent(MainActivity.this, Home.class);
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                        }
                    } else {

                        Toast.makeText(MainActivity.this, "ошибка", Toast.LENGTH_LONG).show();

                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Toast.makeText(MainActivity.this, "Ошибка" + t.getMessage(), Toast.LENGTH_LONG).show();

                }
            });

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

    }
}

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);
        }
    }
}

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;
    }

}

ModelArray.class

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

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

Interface.class

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

JSON type

{
   "list":[
      {
         "Id":2,
         "Name":"Система отопления",
         "Description":"Температура котла достигла максимального порога"
      },
      {
         "Id":1,
         "Name":"Система отопления",
         "Description":"Температура котла достигла максимального порога"
      }
   ],
   "pageInfo":{
      "totalRows":2,
      "page":1,
      "pageSize":25,
      "isFirstPage":true,
      "isLastPage":true
   }
}

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

t9aqgxwy

t9aqgxwy1#

我想你还没有分享真正触发错误的类。堆栈跟踪显示你试图将一个Adapter赋值给一个RecyclerView,但是RecyclerView引用是null
这应该是一个非常简单的修复方法,只需转到PutDataIntoRecyclerView中的Home.java:74,并确保具有对RecyclerView的有效引用
如果Home.java您需要进一步的帮助,请随时共享您的www.example.com文件。

相关问题