我一直在努力recyclerView但是當我運行我的應用程序它沒有顯示在活動和應用程序崩潰的任何數據,並給出該方法空指針異常
這裏的錯誤是我的適配器類:
public class Adaptor extends RecyclerView.Adapter<Adaptor.ViewHolder> {
private ArrayList<info> Info=new ArrayList<>();
public Adaptor(ArrayList<info> info) {
this.Info = info;
}
public void updateList(ArrayList<info> data) {
Info = data;
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
info i= Info.get(position);
holder.name.setText(i.getName());
holder.city.setText(i.getCity());
holder.city.setText(i.getUniversity());
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, city, uni;
public ViewHolder(final View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
city = (TextView) v.findViewById(R.id.city);
uni = (TextView) v.findViewById(R.id.university);
}
}
public int getItemCount() {
return Info.size();
}
}
這裏是我的活動類:
public class Home extends AppCompatActivity implements HomeCallBack {
public ArrayList<info> Info;
private Adaptor myadaptor;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
recyclerView=(RecyclerView)findViewById(R.id.recycle_view);
Info=new ArrayList<>();
myadaptor=new Adaptor(Info);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(myadaptor);
BackgroundHome backgroundHome=new BackgroundHome(this,this);
backgroundHome.execute();
}
@Override
public void processData(JSONArray data)
{
JSONObject js;
if(data!=null)
{
Info=new ArrayList<>();
try
{
for(int i=0;i<data.length();i++)
{
js =data.getJSONObject(i);
info in=new
info(js.getString("Names"),js.getString("city"),
js.getString("university"));
Info.add(in);
}
myadaptor=new Adaptor(Info);
recyclerView.setAdapter(myadaptor);
} catch (JSONException e) {
e.printStackTrace();
}
myadaptor.updateList(Info);
}
每當我運行它,它崩潰和getItemcount()方法中發生錯誤,它是null,但我已初始化它爲Info.size();
不初始化您的信息的ArrayList在你的適配器類別.... 從適配器類刪除此....只是寫的ArrayList信息; 不需要初始化它。初始化將在活動中完成。 –
Sahil
我們需要找到您的問題的單條信息是堆棧跟蹤。請不要在這裏包含你的整個程序的代碼。 *只顯示我們的堆棧跟蹤*。 https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it/218510#218510 –
可能重複[什麼是NullPointerException,以及如何修復它?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) –