我试图将editText保存到SQLite表中,但是当我点击按钮" addFavorites"一切都没有

时间:2018-02-05 06:51:58

标签: android android-sqlite

这是我的类首先将SQLite表中的项数据显示到EditText,之后我尝试通过单击EditText按钮将这些addFavorites数据保存到收藏夹表中没有什么可以保存的善意帮助

以下是代码:

public class ItemListDetail extends AppCompatActivity {

    EditText catID , itemID , itemName , itemDescription, unit , price ;
    Button addFavorites;
    DBhelper dBhelper;
    //int fav;


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

        dBhelper = new DBhelper(this);


        catID = findViewById(R.id.edCID);
        itemID = findViewById(R.id.edIID);
        itemName = findViewById(R.id.edName);
        itemDescription = findViewById(R.id.edDescription);
        unit = findViewById(R.id.edUnit);
        price = findViewById(R.id.edPrice);


        Items item = (Items) getIntent().getExtras().getSerializable("ITEMS");
       // fav = Integer.parseInt(item.getItemId());
        //fav = item.getItemId();

        catID.setText("CategoryID : " + item.getCategoryId());
        itemID.setText("ItemID : " +item.getItemId());
        itemName.setText("ItemName : " +item.getItemName());
        itemDescription.setText("Description : " +item.getItemDescription());
        unit.setText("Unit : " +item.getUnit());
        price.setText("Price : " +item.getPrice());


    }


       public void saveFavorites(View view) {
            String iID = itemID.getText().toString();
            String fID = itemID.getText().toString();

            Fav fav = new Fav(iID ,fID);
            int result =dBhelper.saveFavorites(fav);
            if(result > 0){
                Toast.makeText(this, "Favorites Added", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "Not Added", Toast.LENGTH_SHORT).show();
            }
        }

    }


<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="com.example.bhb.vu_mcs.ItemListDetail">

    <Button
        android:id="@+id/addFavorites"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:text="Add Favorites"
        android:onClick="saveFavorites"
        />

    <EditText
        android:id="@+id/edIID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <EditText
        android:id="@+id/edCID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:editable="false"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <EditText
        android:id="@+id/edPrice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <EditText
        android:id="@+id/edName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <EditText
        android:id="@+id/edDescription"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textMultiLine|textPersonName"
        android:text="Name" />

    <EditText
        android:id="@+id/edUnit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />



</LinearLayout>

package com.example.bhb.vu_mcs;

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

import java.util.ArrayList;
import java.util.List;

/**
 * Created by bhb on 1/30/2018.
 */

public class DBhelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "MyDB.db";
    private static final int DATABASE_VERSION = 2;

    private static final String KEY_CAT_TABLE = "CATEGORY";
    private static final String KEY_CAT_ID = "categoryId";
    private static final String KEY_CAT_NAME = "categoryName";
    private static final String KEY_CAT_DESCRIPTION = "categoryDescription";
    private static final String CREATE_CATEGORY_TABLE = "CREATE TABLE " + KEY_CAT_TABLE + "( "+ KEY_CAT_ID  + " INTEGER PRIMARY KEY,"
            + KEY_CAT_NAME + " TEXT NOT NULL,"
            + KEY_CAT_DESCRIPTION + " TEXT NOT NULL )";


    private static final String KEY_ITEM_TABLE = "ITEMS";
    private static final String KEY_ITEM_ID = "itemId";
    // private static final String COL3 = "categoryId";
    private static final String KEY_ITEM_NAME = "itemName";
    private static final String KEY_ITEM_DESCRIPTION = "itemDescription";
    private static final String KEY_ITEM_UNIT = "unit";
    private static final String KEY_ITEM_PRICE = "price";
    private static final String CREATE_ITEMS_TABLE = "CREATE TABLE " + KEY_ITEM_TABLE + "( "+ KEY_ITEM_ID  + " INTEGER PRIMARY KEY,"
            + KEY_CAT_ID + " INTEGER,"
            + KEY_ITEM_NAME + " TEXT NOT NULL,"
            + KEY_ITEM_DESCRIPTION + " TEXT NOT NULL,"
            + KEY_ITEM_UNIT + " TEXT NOT NULL,"
            + KEY_ITEM_PRICE + " TEXT NOT NULL )";



////////////this part is for favrities/////////////////////
    private static final String KEY_FAVORITES_TABLE = "FAVORITES";
    private static final String KEY_FAVORITES_ID = "favritesId";

    private static final String CREATE_FAVORITES_TABLE = "CREATE TABLE " + KEY_FAVORITES_TABLE + "( "+ KEY_FAVORITES_ID  + " INTEGER TEXT NOT NULL,"
            + KEY_ITEM_ID + " INTEGER PRIMARY KEY )";

///////////////////////


    public DBhelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_CATEGORY_TABLE);
        db.execSQL(CREATE_ITEMS_TABLE);
        db.execSQL(CREATE_FAVORITES_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

        db.execSQL(" DROP TABLE IF EXISTS " + KEY_CAT_TABLE);
        db.execSQL(" DROP TABLE IF EXISTS " + KEY_ITEM_TABLE);
        db.execSQL(" DROP TABLE IF EXISTS " + KEY_FAVORITES_TABLE);
        onCreate( db);
    }

    public List<Items> getItemsForCategory(int catID) {
        List<Items> myitems  = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + KEY_ITEM_TABLE + " WHERE  categoryId = " + catID , null);
        if(cursor.moveToNext())
        {
            do{
                String itemId = cursor.getString(0);
                String categoryId  = cursor.getString(1);
                String itemName = cursor.getString(2);
                String itemDescription = cursor.getString(3);
                String unit = cursor.getString(4);
                String price = cursor.getString(5);

                Items items = new Items(itemId, categoryId, itemName, itemDescription, unit, price);
                myitems.add(items);
            }while (cursor.moveToNext());
        }
        return myitems;
    }

    public List<Fav> getFavorities() {
        List<Fav> myFav = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + KEY_FAVORITES_TABLE, null );
        if(cursor.moveToNext()){
            do{
                String fid = cursor.getString(0);
                String iid = cursor.getString(1);
                Fav favrities = new Fav(fid , iid);
                myFav.add(favrities);
            }while (cursor.moveToNext());
        }
        return myFav;
    }

    public int saveFavorites(Fav fav) {
        SQLiteDatabase db = getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_ITEM_ID , fav.getItemId());
        values.put(KEY_FAVORITES_ID , fav.favId);
        //return db.update("FAVORITES" , values, "id=?", new String[]{fav.getItemId()} );
        long temp = db.insert("FAVORITES" , null, values);
        db.close();

       return (int) temp;


    }
}

2 个答案:

答案 0 :(得分:0)

我建议你这样做。使用getWritableDatabase()而不是getReadableDatabase()。

public int saveFavorites(Fav fav) {
    SQLiteDatabase db = getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_ITEM_ID , fav.getItemId());
    values.put(KEY_FAVORITES_ID , fav.favId);
   //return db.update("FAVORITES" , values, "id=?", new String[]{fav.getItemId()} );
    long temp = db.insert("FAVORITES" , null, values);
    db.close();

return (int) temp;


}

答案 1 :(得分:0)

我相信你发的是你要么

  • (a)尝试将无法转换为整数的字符串值插入到只能包含整数或
  • 的列中
  • (b)尝试将相同的值插入到必须具有唯一值的列中。

不知道无法确定的实际值。

在SQLite中,任何列都可以使用ONE EXCEPTION保存任何类型的值,并且该列是 rowid 的别名。 rowid 是默认存在的特殊隐藏列(WITHOUT ROWID可用于指定没有rowid的表)。包含特殊关键字INTEGER PRIMARY KEY(或附加AUTOINCREMENT)的列是 rowid 的别名。只能在没有指定值或整数的情况下插入这样的列,并且该值必须是唯一的。

因此,特别是可能从KEY_ITEM_ID派生的FAVORITES表的String fID = itemID.getText().toString();(itemId)列不能是等于整数的字符串(可能是它)。此外,价值必须是独一无二的。

KEY_ITEM_ID(itemId)似乎是引用ITEMS表中的Item。因此,您可能只需指定INTEGERINTEGER NOT NULL作为列类型。

虽然问题不是KEY_FAVORITES_ID(favritesId)列定义为INTEGER TEXT NOT NULL,但您应该将其更改为INTEGER NOT NULL

因此我相信你应该改变: -

private static final String CREATE_FAVORITES_TABLE = "CREATE TABLE " + KEY_FAVORITES_TABLE + "( "+ KEY_FAVORITES_ID  + " INTEGER TEXT NOT NULL,"
        + KEY_ITEM_ID + " INTEGER PRIMARY KEY )";

: -

private static final String CREATE_FAVORITES_TABLE = "CREATE TABLE " + KEY_FAVORITES_TABLE + "( "+ KEY_FAVORITES_ID  + " INTEGER NOT NULL,"
        + KEY_ITEM_ID + " INTEGER NOT NULL )";

请注意!要实现上述功能,您需要DROP并重新创建FAVORITES。如果丢失所有数据不是问题,那么您可以执行以下操作之一;

  • (a)卸载App,
  • (b)删除应用程序的数据或
  • (c)增加版本号。