数据库无法正确显示数据

时间:2017-10-06 22:52:14

标签: java android database user-interface android-recyclerview

我有一个问题,即我有一个应用程序,在RecyclerView中显示2种类型的沙拉,按下后,其中一个应显示一个视图,显示其确切的详细信息,并选择是否喜欢它。显然从数据库中检索这些数据。一切正常,直到我们进入详细的视图 - 当我们点击希腊沙拉的图片时,我们得到一个空白的视图,但是当我们点击鸡肉沙拉时,我们只能看到希腊沙拉,这有什么意义?那么鸡肉沙拉的景色在哪里?为什么意见变成了地方。我将底部的代码附在图片上,以便您可以准确理解问题所在。

DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper {

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

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

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE SALAD (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "NAME TEXT, "
            + "IMAGE_RESOURCE_ID INTEGER, "
            + "FAVORITE INTEGER);");

    insertSalatki(db, "Greek salad", R.drawable.salad_greek, 0);
    insertSalatki(db, "Chicken salad", R.drawable.salad_chicken, 0);

}

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

}

private static void insertSalatki(SQLiteDatabase db, String name, int resourceId, int favorite){

    ContentValues saladValues = new ContentValues();
    salatkiValues.put("NAME", name);
    salatkiValues.put("IMAGE_RESOURCE_ID", resourceId);
    salatkiValues.put("Favorite", favorite);
    db.insert("SALAD", null, salatkiValues);
}

}

沙拉

  public class Salad {

    private String name;
    private int imageResourceId;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getImageResourceId() {
        return imageResourceId;
    }

    public void setImageResourceId(int imageResourceId) {
        this.imageResourceId = imageResourceId;
    }
}

SaladDetailActivity

public class SaladDetailActivity extends AppCompatActivity {

public static final String EXTRA_SALAD = "salad";


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

    int salads = (Integer) getIntent().getExtras().get(EXTRA_SALAD); 

    try {

        SQLiteOpenHelper miodzioDatabaseHelper = new MiodzioDatabaseHelper(this);
        SQLiteDatabase db = miodzioDatabaseHelper.getWritableDatabase();


        Cursor cursor = db.query("SALATKI",
                new String[]{"NAME", "IMAGE_RESOURCE_ID", "FAVORITE"},
                "_id = ?",
                new String[]{Integer.toString(salads)},
                null, null, null);

        if(cursor != null) {
            if (cursor.moveToFirst()) {

                do {

                  String nameText = cursor.getString(0);
                   int photoId = cursor.getInt(1);

                    boolean isFavorite = (cursor.getInt(2) == 1);

                    TextView name = (TextView) findViewById(R.id.salad_text);
                    name.setText(nameText);

                    ImageView photo = (ImageView) findViewById(R.id.salad_image);
                    photo.setImageResource(photoId);
                    photo.setContentDescription(nameText);

                    CheckBox favorite = (CheckBox) findViewById(R.id.favorite);
                    favorite.setChecked(isFavorite);
                }while (cursor.moveToNext());
            }
        }

        cursor.close();
        db.close();

    }catch (SQLiteException e){
        Toast.makeText(this, "Database does not work!", Toast.LENGTH_SHORT).show();
    }


    Toolbar myChildToolbar = (Toolbar) findViewById(R.id.my_child_toolbar_salad_detail);
    setSupportActionBar(myChildToolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}



@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.action_create_order:
            Intent intent = new Intent(this, AddActivity.class);
            startActivity(intent);
            return true;
        default:

            return super.onOptionsItemSelected(item);
    }


}

public void onFavoriteClicked(View view) {

    int salads = (Integer) getIntent().getExtras().get(EXTRA_SALAD);

    CheckBox favorite = (CheckBox) findViewById(R.id.favorite);

    ContentValues saladValues = new ContentValues();


    saladValues.put("FAVORITE", favorite.isChecked());

    SQLiteOpenHelper databaseHelper = new DatabaseHelper(this);

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    db.update("SALAD", saladValues,
            "_id = ?", new String[]{Integer.toString(salads)});
    db.close();
}

}

SaladMaterialFragment

 public class SaladMaterialFragment extends Fragment {


    private DatabaseHelper dataBaseHelper;
    private Cursor cursor;

    private ArrayList<Salad> arrayList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        RecyclerView saladRecyler = (RecyclerView) inflater.inflate(R.layout.fragment_salad_material, container, false);

        try{
            SQLiteOpenHelper databaseHelper = new databaseHelper(inflater.getContext());
            SQLiteDatabase db = databaseHelper.getReadableDatabase();

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

            if(cursor != null){
                if(cursor.moveToFirst()){
                    do{
                        Salad salads = new Salad();
                        salad.setName(cursor.getString(0));
                        salad.setImageResourceId(cursor.getInt(1));
                        arrayList.add(salad);

                    }while (cursor.moveToNext());
                }
            }

        }catch (SQLiteException e){
            Toast.makeText(inflater.getContext(), "Database does not work!", Toast.LENGTH_SHORT).show();
        }

            CaptionedImagesAdapter adapter = new CaptionedImagesAdapter(getActivity(), arrayList);
            saladRecyler.setAdapter(adapter);

             GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
            saladRecyler.setLayoutManager(gridLayoutManager);

            adapter.setListener(new CaptionedImagesAdapter.Listener() {
                @Override
                public void onClick(int position) {
                    Intent intent = new Intent(getActivity(), SaladDetailActivity.class);
                    intent.putExtra(SaladDetailActivity.EXTRA_SALAD, position);
                    getActivity().startActivity(intent);
                }
            });
        return salatkaRecyler;
        }

    }

SaladDetailLayout

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfad.SaladDetailActivity">


<android.support.v7.widget.Toolbar
    android:id="@+id/my_child_toolbar_salad_detail"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"
    android:background="@android:color/holo_green_light"
    android:elevation="4dp"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    />

<TextView
    android:id="@+id/salatki_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"/>


<ImageView
    android:id="@+id/salad_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"/>

<CheckBox
    android:id="@+id/favorite"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/favorite"
    android:onClick="onFavoriteClicked"/>

enter image description here

因此,当我点击Salad greek时,我只能看到它是否是最喜欢的选项。当我吃鸡肉沙拉时,我会看到希腊沙拉。我不知道发生了什么?

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

您还要插入int资源的drawable值,这不是一个好主意。此值在应用程序的整个生命周期中不一定是恒定的 - 更高版本可能会向此资源发布新值。 所以请不要这样做。

insertSalatki(db, "Greek salad", R.drawable.salad_greek, 0);

而是将drawable映射到一个独立但不变的引用。有点像:

insertSalatki(db, "Greek salad", idSaladGreek, 0);

因此,由于您的数据库中可能有许多行具有相同的沙拉类型(例如希腊沙拉),可能有许多不同的资源ID,当您在数据库中查询沙拉类型时,可能会获得错误的资源ID。这可能会导致您无法显示图像的问题。

通过比较来自数据库的int值(int photoId = cursor.getInt(1))和int的{​​{1}}值来测试此内容。

R.drawable.salad_greek中,您还应检查是否获得了有效值:

SaladDetailActivity

答案 1 :(得分:0)

问题出在SaladMaterialFragment类的onClick方法中。 您正在传递项目的位置,并且在 ArrayList索引中以0开始。 但在数据库插入中,_id INTEGER PRIMARY KEY AUTOINCREMENT,数据库索引将从1开始
所以你需要用下面的方法改变onClick方法。

sum

只需使用位置+ 1 更改位置