空对象引用上的RecyclerView



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

类适配器


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

型号.类别

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

接口.类

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

JSON类型

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

我已经试着在RecycleView上获取数据一天了,但它不起作用。出现错误:

E/AndroidRuntime:致命异常:main进程:com.example.tokenauth,PID:8011java.lang.NullPointerException:尝试在null对象引用上调用虚拟方法"void androidx.recyclerview.widget.CyclerView.setAdapter(androidx.cyclerview.widget.RyclerView$Adapter)"网址:com.example.tokenauth.Home.PutDataIntoRecyclerView(Home.java:74)访问com.example.tokenauth.Home.access$000(Home.java:25)网址:com.example.tokenauth.Home$1.onResponse(Home.java:56)在retrofit2.ExecutorCallAdapterFactory$Executor回调调用$1$1.run(ExecutorCallAdapterFactory.java:68)在android.os.Handler.handleCallback(Handler.java:888)在android.os.Handler.dispatchMessage(Handler.java:100)在android.os.Looper.loop(Looper.java:213)在android.app.ActivityThread.main(ActivityThreads.java:8178)位于java.lang.reflect.Method.ioke(本机方法)网址:com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)网址:com.android.internal.os.ZygoteInit.main(ZygoteNit.java:1101)请解释一下我的错误是什么P.S对不起我的英语

我认为您还没有共享触发实际错误的类。堆栈跟踪表明您正试图将Adapter分配给RecyclerView,但RecyclerView引用是null

这应该是一个非常简单的修复方法,只需转到PutDataIntoRecyclerView中的Home.java:74,并确保您有一个对RecyclerView的有效引用

如果您需要进一步的帮助,请随时分享您的Home.java文件。

相关内容

  • 没有找到相关文章

最新更新