开发者社区> 问答> 正文

单击recyclerview中的项目之一以读取详细信息时,出现NullPointerExceptio

我正在尝试创建一个简单的食谱应用程序。一个recyclerview,单击该项目时将显示每个配方的详细信息。单击该项目时,应用程序崩溃并显示nullPointerException。我不确定如何纠正它?

主要活动

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecipeAdapter adapter;
    List<Recipe> recipeList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recipeRecyclerView);
        recipeList = new ArrayList<>();
        recipeList.add(new Recipe(
                "Good-Fat Fish",
                "1 spoon sauce\n" + "fish\n" + "lemon",
                "Put the fish in pot and steam it with sauce and lemon",
                "One serving",
                "Healthy and improve memory"));

        recipeList.add(new Recipe(
                "Good-Fat pork",
                "1 spoon sauce\n" + "fish\n" + "lemon",
                "Put the fish in pot and steam it with sauce and lemon",
                "One serving",
                "Healthy and improve memory"));

        adapter = new RecipeAdapter(this, recipeList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this)); //or new GridLayoutManager(this, 1)
        recyclerView.setAdapter(adapter);

    }
}

适配器

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.RecipeHolder> {

    private Context context;
    private List<Recipe> recipeList;

    public RecipeAdapter(Context context, List<Recipe> recipeList) {
        this.context = context;
        this.recipeList = recipeList;
    }

    @NonNull
    @Override
    public RecipeHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view;
        LayoutInflater inflater = LayoutInflater.from(context);
        view = inflater.inflate(R.layout.recipe_single_cardview, parent, false);
        return new RecipeHolder(view);

        // or return new RecipeHolder(LayoutInflater.from(context).inflate(R.layout.recipe_single_cardview, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecipeHolder holder, int position) {
        Recipe recipe = recipeList.get(position);
        holder.showRecipeName.setText(recipe.getRecipeName());
        holder.showInfo.setText(recipe.getInfo());
    }

    @Override
    public int getItemCount() {
        return recipeList.size();
    }

    public class RecipeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView showRecipeName, showInfo;

        public RecipeHolder(@NonNull View itemView) {
            super(itemView);

            showRecipeName = (TextView) itemView.findViewById(R.id.cardView_recipeName);
            showInfo = (TextView) itemView.findViewById(R.id.cardView_info);

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Recipe recipe = recipeList.get(getAdapterPosition());
            Intent intent = new Intent(context, ReadActivity.class);
            intent.putExtra("recipe", recipe); //need to implements Serializable at Recipe class
            context.startActivity(intent);
        }
    }
}

食谱课

public class Recipe implements Serializable {

    private String recipeName, ingredients, preparation, yield, info;

    public Recipe() {
    }

    public Recipe(String recipeName, String ingredients, String preparation, String yield, String info) {
        this.recipeName = recipeName;
        this.ingredients = ingredients;
        this.preparation = preparation;
        this.yield = yield;
        this.info = info;
    }

    public String getRecipeName() {
        return recipeName;
    }

    public void setRecipeName(String recipeName) {
        this.recipeName = recipeName;
    }

    public String getIngredients() {
        return ingredients;
    }

    public void setIngredients(String ingredients) {
        this.ingredients = ingredients;
    }

    public String getPreparation() {
        return preparation;
    }

    public void setPreparation(String preparation) {
        this.preparation = preparation;
    }

    public String getYield() {
        return yield;
    }

    public void setYield(String yield) {
        this.yield = yield;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}
ReadActivity

public class ReadActivity extends AppCompatActivity {

    private TextView recipeNameTV, ingredientsTV, preparationTV, yieldTV, infoTV;
    private String name, ingredients, preparation, yield, info;
    private Recipe recipe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read);

        recipeNameTV = (TextView) findViewById(R.id.cardView_recipeName);
        ingredientsTV = (TextView) findViewById(R.id.read_ingredients);
        preparationTV = (TextView) findViewById(R.id.read_preparation);
        yieldTV = (TextView) findViewById(R.id.read_yield);
        infoTV = (TextView) findViewById(R.id.read_info);

        recipe = (Recipe) getIntent().getSerializableExtra("recipe");

        Intent intent = getIntent();
        name = intent.getExtras().getString("recipeName");
        ingredients = intent.getExtras().getString("ingredients");
        preparation = intent.getExtras().getString("preparation");
        yield = intent.getExtras().getString("yield");
        info = intent.getExtras().getString("info");

        recipeNameTV.setText(name);
        ingredientsTV.setText(ingredients);
        preparationTV.setText(preparation);
        yieldTV.setText(yield);
        infoTV.setText(info);

    }
}

错误:

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.amethyst.mindrecipe, PID: 26121
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amethyst.mindrecipe/com.amethyst.mindrecipe.ReadActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3146)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3296)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:114)
Process 26121 terminated.
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:74)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994)
        at android.os.Handler.dispatchMessage(Handler.java:106)

展开
收起
几许相思几点泪 2019-12-29 19:51:22 1000 0
1 条回答
写回答
取消 提交回答
  • 这是一个粗心的错误,(设置项目的ID错误)

    我变了

    recipeNameTV = (TextView) findViewById(R.id.cardView_recipeName);
    
    

    recipeNameTV = (TextView) findViewById(R.id.read_recipeName);
    
    

    谢谢!

    2019-12-29 19:51:54
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载