我知道有数十亿个相同的问题,但实际上我无法处理这个问题。这是导致问题的代码:
public class CategoryActivity extends AppCompatActivity implements CategoryAdapter.CategoryAdapterClickHandler {
@Override
public void onClick(String name) {
}
RecyclerView recyclerView;
CategoryAdapter mAdapter;
ArrayList<String> items;
static String catName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
//get intent and extra text
Intent intent = getIntent();
catName = intent.getStringExtra("categoryName");
Log.e("fwdf", catName);
//execute categoryTask;
new CategoryAsyncTask(){
@Override
protected void onPostExecute(ArrayList<String> categoryItems) {
super.onPostExecute(categoryItems);
items = categoryItems;
}
}.execute(catName);
//initialize recyclerview and set it to its adapter
recyclerView = (RecyclerView) findViewById(R.id.list);
LinearLayoutManager layoutManager =
new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
Log.e("fgjhkkl;",items.get(1));
mAdapter = new CategoryAdapter(this, this, items, false);
recyclerView.setAdapter(mAdapter);
}
}
发生错误是因为items变量为null,尽管categoryItems不为null,我将项目分配给了CategryItems。
答案 0 :(得分:1)
您正在尝试在AsyncTask完成之前使用这些项目。
要解决(例如),请移动
recyclerView = (RecyclerView) findViewById(R.id.list);
LinearLayoutManager layoutManager =
new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
mAdapter = new CategoryAdapter(this, this, items, false);
recyclerView.setAdapter(mAdapter);
到onPostExecute
函数