空指针异常无法在asynctask中赋值

时间:2018-04-12 16:45:49

标签: android android-asynctask nullpointerexception

我知道有数十亿个相同的问题,但实际上我无法处理这个问题。这是导致问题的代码:

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。

1 个答案:

答案 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函数

的末尾