不使用AsyncTask,我的编码工作正常......
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
registerForContextMenu(mRecyclerView);
mAdapter = new CardAdapter(this);
mRecyclerView.setAdapter(mAdapter);
如果我在setAdapter(mAdapter)的mainActivity中使用AsyncTask,则在recyclelerview onBindViewHolder onClick函数中我得到NullPointeerException。
MainActivity:
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
registerForContextMenu(mRecyclerView);
/*mAdapter = new CardAdapter(this);
mRecyclerView.setAdapter(mAdapter);*/
if(isNetworkConnected()) {
new RemoteDataTask().execute();
}
// AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
mAdapter = new CardAdapter(mContext);
return null;
}
@Override
protected void onPostExecute(Void result) {
mRecyclerView.setAdapter(mAdapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Capture button clicks on ListView items
}
}
在适配器中:
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
NatureItem nature = mItems.get(i);
viewHolder.tv.setText(nature.getName());
viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
viewHolder.commentClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, Comment.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
例外:
java.lang.NullPointerException
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3655)
at com.example.demo.CardAdapter$3.onClick(CardAdapter.java:227)
at android.view.View.performClick(View.java:4191)
at android.view.View$PerformClick.run(View.java:17229)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4963)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)