Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm getting the following error :

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

This occurs at this line
holder.myTextView.setText(itemRecipe.get(position).toString());

I have gone through several troubleshooting steps for this and not sure what else to try or if the database is even working, the reason I want this to work.

What I have tried:

RecyclerAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    private List<RecipeList> itemRecipe;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    RecyclerViewAdapter(Context context, List<RecipeList> data) {
        this.mInflater = LayoutInflater.from(context);
        this.itemRecipe = data;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.fragment_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.myTextView.setText(itemRecipe.get(position).toString());

    }

    // total number of rows
    @Override
    public int getItemCount() {
        return itemRecipe.size();
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.listIngredient);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }


    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}


Main class

public class Recipe extends MainActivity {

    TabLayout tabLayout;
    ImageView recipeImage;
    TextView descriptionText, courseText, servingsText, costText, caloriesText, methodText;
    RecyclerView listIngredient;
    SQLiteDatabase db;
    String search_name;
    Cursor c;
    RecyclerViewAdapter adapterRecipe;
    List<RecipeList> itemRecipe = new ArrayList<>();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recipe);
        //search_name = getIntent().getStringExtra("NAME");
        search_name = "Speedy chicken couscous";

        loadRecipe();
        //recyclerview Recipe
        adapterRecipe = new RecyclerViewAdapter(this, itemRecipe);
        listIngredient = findViewById(R.id.listIngredient);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        listIngredient.setLayoutManager(mLayoutManager);
        listIngredient.setItemAnimator(new DefaultItemAnimator());
        listIngredient.setAdapter(adapterRecipe);

    }
    public void loadRecipe() {
        itemRecipe.clear();
        db = (new DatabaseManager(this).getWritableDatabase());
        String RECIPE_SEARCH = " SELECT A.recipe, A.ingredient_quantity, B.measurement_name, B.ingredient_name, B.description " +
                "FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS +
                " AS B ON A.ingredient = B.ingredient_name";
        String selectQuery = "";
        selectQuery = RECIPE_SEARCH + " WHERE A.recipe LIKE ?";
        c = db.rawQuery(selectQuery, new String[]{"%" + search_name + "%"});
        if (c.moveToFirst()) {
            do {
                RecipeList recipeList = new RecipeList();
                recipeList.setRecipe(c.getString(c.getColumnIndex("recipe")));
                recipeList.setIngredient_amount(c.getString(c.getColumnIndex("ingredient_quantity")));
                recipeList.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
                recipeList.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
                recipeList.setDescription(c.getString(c.getColumnIndex("description")));
                itemRecipe.add(recipeList);
            } while (c.moveToNext());
            c.close();
        }

    }
}


RecipeList Class

public class RecipeList {

    private Integer id;
    private Double ingredient_quantity;
    private String recipe;
    private String measurement_name;
    private String ingredient_name;
    private String description;
    private String ingredient_amount = String.valueOf(ingredient_quantity);
    public RecipeList(){

    }

    public RecipeList(String recipe, String ingredient_amount, String measurement_name, String ingredient_name, String description) {

        this.recipe = recipe;
        this.ingredient_amount = ingredient_amount;
        this.measurement_name = measurement_name;
        this.ingredient_name = ingredient_name;
        this.description = description;
    }

    public String getRecipe() {
        return recipe;
    }

    public void setRecipe(String recipe) {
        this.recipe = recipe;
    }

    public String getIngredient_amount() {
        return ingredient_amount;
    }

    public void setIngredient_amount(String ingredient_amount) {
        this.ingredient_amount = ingredient_amount;
    }

    public String getMeasurement_name() {
        return measurement_name;
    }

    public void setMeasurement_name(String measurement_name) {
        this.measurement_name = measurement_name;
    }

    public String getIngredient_name() {
        return ingredient_name;
    }

    public void setIngredient_name(String ingredient_name) {
        this.ingredient_name = ingredient_name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
    @Override
    public String toString() {
        return "RecipeList{" +
                "id=" + id +
                ", ingredient_quantity=" + ingredient_quantity +
                ", recipe='" + recipe + '\'' +
                ", measurement_name='" + measurement_name + '\'' +
                ", ingredient_name='" + ingredient_name + '\'' +
                ", description='" + description + '\'' +
                ", ingredient_amount='" + ingredient_amount + '\'' +
                '}';
    }
}
Posted
Updated 17-Sep-20 18:55pm
Comments
David Crow 17-Sep-20 16:33pm    
It has nothing to do with the database. It has everything to do with myTextView being null. Have you stepped into the ViewHolder constructor to see what is returned from findViewById()?

I don't see any try/catch blocks in your code. Is that intentional?
Rhys Owain Evans 17-Sep-20 16:54pm    
I am very new to this and uncertain as to what you refer, where would the try/catch blocks be?
David Crow 17-Sep-20 23:09pm    
Around code for which an exception might be thrown.
Rhys Owain Evans 18-Sep-20 0:43am    
Where would I place them in this code? Also how do I look to see what is being returned by findViewById()?
David Crow 18-Sep-20 8:08am    
"Where would I place them in this code?"

See here.

"Also how do I look to see what is being returned by findViewById()?"

By using the debugger.

1 solution

Reference: How to resolve the java.lang.NullPointerException[^]
Quote:
In Java, the java.lang.NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Your case, I would suggest to check for null before converting it into string for usage.
Java
// binds the data to the TextView in each row
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    if(itemRecipe.get(position) != null)
    {
      holder.myTextView.setText(itemRecipe.get(position).toString());
    }
}

Using debugger, you will be able to know what exactly is null. Above code is assuing itemRecipe is not null but the value at a position asked in it is. If it turns itemReceipe is null, use that as the condition.
 
Share this answer
 
Comments
Rhys Owain Evans 18-Sep-20 2:51am    
Thanks, I'll give this a go later. I'm very new to this and haven't used debugger yet, not sure how yet.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900