繁体   English   中英

如何解决 android.content.res.Resources$NotFoundException: Resource ID #0x0 & 正确显示数据库中的数据到卡片视图?

[英]How to solve android.content.res.Resources$NotFoundException: Resource ID #0x0 & properly display data from a database to a cardview?

我正在尝试构建一个卡片视图,该视图显示来自我的 SQLite 数据库的数据列表。 我使用grocery_item class 创建回收站视图并从MyDataBaseHelper获取数据并将数据放入ArrayList。 在同一个 class 中,然后我创建一个 CaptionedImagesAdapter 的captionedImagesAdapter来为卡片视图创建视图持有者,并将 ArrayLists 中的数据绑定到卡片视图。

但是,每当我尝试运行该程序时,我都会收到异常android.content.res.Resources$NotFoundException: Resource ID #0x0并且卡片视图未显示在item_grocery.xml布局上。 导致问题的代码at com.myapps.myapplication.captionedImagesAdapter.onBindViewHolder(captionedImagesAdapter.java:44)这是Drawable drawable = ContextCompat.getDrawable (holder.cardView.getContext(), images [position]); & at com.myapps.myapplication.captionedImagesAdapter.onBindViewHolder(captionedImagesAdapter.java:14) which is public class captionedImagesAdapter extends RecyclerView.Adapter <captionedImagesAdapter.ViewHolder> .

我尝试通过检查 ArrayList 是否有 null 引用来解决问题,但一切都很好,从研究来看,我已经完成了异常,因为无法从holder.cardView.getContext()找到资源。 但是,我被困在这个问题上,我不知道我是否以正确的方式将数据库中的数据显示到 Recycler 视图。

这是我的grocery_item.java活动的代码:

package com.myapps.myapplication;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class grocery_item extends AppCompatActivity {

ArrayList <String> groceryName;
ArrayList <Integer> groceryImages;
SQLiteDatabase db;
Cursor cursor;

protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.item_grocery);

    RecyclerView groceryRecycler = (RecyclerView) findViewById(R.id.grocery_recycler_view);

    groceryName = new ArrayList<String>();
    groceryImages = new ArrayList <Integer>();

    accessDataBase();

    cursor = db.query("ITEMS", new String[] {"NAME", "DESCRIPTION", "IMAGE_RESOURCE_ID"}, null, null, null, null, null);

    for (int i = 0; i <= 11; i++) {

        if (i == 0) {
            if (cursor.moveToFirst()) {
                groceryName.add (cursor.getString (0));
                groceryImages.add (cursor.getInt (1));
            }

        } 

        if (i != 0) {
            if (cursor.moveToNext()) {
                groceryName.add (cursor.getString (0));
                groceryImages.add (cursor.getInt (1));
            } else {
                Log.d ("blue", "the next record in the cursor was not found for the images");
            }
        }

    }

    captionedImagesAdapter adapter = new captionedImagesAdapter (groceryName, groceryImages);

    groceryRecycler.setHasFixedSize(true);
    GridLayoutManager layoutManager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
    groceryRecycler.setLayoutManager(layoutManager);
    groceryRecycler.setAdapter (adapter);
}

public void accessDataBase () {
    MyDatabaseHelper databaseHelper = new MyDatabaseHelper(this);
    try {
        db = databaseHelper.getReadableDatabase();

        if (db != null) {
            Log.d ("db", "db is is accessed");
        }
    } catch (SQLiteException e) {
        e.printStackTrace();
    }
}
}

这是我的item_grocery.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grocery_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical" />

这是我的card_view.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_margin="5dp"
    card_view:cardElevation="2dp"
    card_view:cardCornerRadius="4dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/info_image"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1.0"
        android:scaleType="centerCrop" >

    </ImageView>

    <TextView
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="4dp"
        android:layout_marginBottom="4dp" >

    </TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>

这是我的captionedImagesAdapter.java的代码:

package com.myapps.myapplication;

import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.cardview.widget.CardView;

public class captionedImagesAdapter extends RecyclerView.Adapter <captionedImagesAdapter.ViewHolder> {

private int [] images;
private String [] names;

public captionedImagesAdapter (ArrayList <String> captions, ArrayList <Integer> imageIds) {

    images = new int [11];
    names = new String [11];

    for (int i = 0; i <11; i++) {
        images [i] = imageIds.get (i);
    }

    for (int i = 0; i < 11; i++) {
        names [i] = captions.get (i);
    }
}

public captionedImagesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    CardView cv = (CardView) LayoutInflater.from (parent.getContext()).
            inflate(R.layout.card_view, parent, false);

    return new ViewHolder (cv);
}

public void onBindViewHolder(ViewHolder holder, int position) {
    Drawable drawable = ContextCompat.getDrawable (holder.cardView.getContext(), images [position]);
    holder.imageView.setImageDrawable (drawable);
    holder.textView.setText (names [position]);
}

public int getItemCount() {
    Log.d ("captionSize", String.valueOf(names.length));
    return names.length;
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    private ImageView imageView;
    private TextView textView;
    private CardView cardView;

    public ViewHolder(CardView view) {
        super(view);
        imageView = view.findViewById(R.id.info_image);
        textView = view.findViewById(R.id.info_text);
        cardView = view;
    }
}
}

这是我的 SQLiteHelper 的代码:

package com.myapps.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabaseHelper extends SQLiteOpenHelper {

private static final String DB_NAME = "starbuzz";
private static final int DB_VERSION = 1;

public MyDatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE ITEMS (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "NAME TEXT, " + "DESCRIPTION TEXT, " + "IMAGE_RESOURCE_ID INTEGER) ;");
    insertItems (db, "Faan", "Bangla Faan", R.drawable.faan);
    insertItems (db, "Milk", "Whole Milk", R.drawable.milk);
    insertItems (db, "Egg", "A tray of Eggs", R.drawable.egg);
    insertItems (db, "Toilet Tissue", "A bag of toilet tissue", R.drawable.toilet_tissue);
    insertItems (db, "Kitchen Tissue", "A bag of kitchen tissue", R.drawable.kitchen_tissue);
    insertItems (db, "Bread", "a bag of bread", R.drawable.bread);
    insertItems (db, "Potatoe", "a sack of potatoe", R.drawable.potatoe);
    insertItems (db, "Onion", "a sack of onions", R.drawable.onion);
    insertItems (db, "Flour", "a packet of flour", R.drawable.flour);
    insertItems (db, "Tomatoe", "a packet of tomatoe", R.drawable.tomatoe);
    insertItems (db, "Corriandor", "a bag of corriandor", R.drawable.corriandor);
}

public void insertItems (SQLiteDatabase db, String name, String description, int image) {
    ContentValues contentValues = new ContentValues();
    contentValues.put ("NAME", name);
    contentValues.put ("DESCRIPTION", description);
    contentValues.put ("IMAGE_RESOURCE_ID", image);
    db.insert ("ITEMS", null, contentValues);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}

这是我在运行代码时收到的异常:

2020-07-30 11:00:09.754 28815-28815/com.myapps.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapps.myapplication, PID: 28815
android.content.res.Resources$NotFoundException: Resource ID #0x0
    at android.content.res.ResourcesImpl.getValueForDensity(ResourcesImpl.java:246)
    at android.content.res.Resources.getDrawableForDensity(Resources.java:905)
    at android.content.res.Resources.getDrawable(Resources.java:845)
    at android.content.Context.getDrawable(Context.java:687)
    at androidx.core.content.ContextCompat.getDrawable(ContextCompat.java:455)
    at com.myapps.myapplication.captionedImagesAdapter.onBindViewHolder(captionedImagesAdapter.java:44)
    at com.myapps.myapplication.captionedImagesAdapter.onBindViewHolder(captionedImagesAdapter.java:14)
    at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7178)
    at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7258)
    at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6125)
    at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6391)
    at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6231)
    at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6227)
    at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2330)
    at androidx.recyclerview.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:572)
    at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1591)
    at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:668)
    at androidx.recyclerview.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:170)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4230)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3941)
    at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4499)
    at android.view.View.layout(View.java:22085)
    at android.view.ViewGroup.layout(ViewGroup.java:6290)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
    at android.view.View.layout(View.java:22085)
    at android.view.ViewGroup.layout(ViewGroup.java:6290)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
    at android.view.View.layout(View.java:22085)
    at android.view.ViewGroup.layout(ViewGroup.java:6290)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
    at android.view.View.layout(View.java:22085)
    at android.view.ViewGroup.layout(ViewGroup.java:6290)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
    at android.view.View.layout(View.java:22085)
    at android.view.ViewGroup.layout(ViewGroup.java:6290)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:786)
    at android.view.View.layout(View.java:22085)
    at android.view.ViewGroup.layout(ViewGroup.java:6290)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3333)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2810)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1930)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7988)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1154)
    at android.view.Choreographer.doCallbacks(Choreographer.java:977)
    at android.view.Choreographer.doFrame(Choreographer.java:893)
    2020-07-30 11:00:09.754 28815-28815/? E/AndroidRuntime:     at 
    android.view.Choreographer$FrameHandler.handleMessage(Choreographer.java:1082)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7682)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

升级以下依赖项后,我遇到了类似的错误。 将它们还原后,它得到了解决。

 implementation 'androidx.appcompat:appcompat:1.2.0'
 implementation 'androidx.recyclerview:recyclerview:1.2.0'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM