简体   繁体   English

android sqlite数据库检索有问题

[英]having a problem with android sqlite database retrieving

i am making a tableview in android where i have 2 columns.我正在 android 中制作一个 tableview,我有 2 列。 The first column is the itemname and second one is itemprice.第一列是商品名称,第二列是商品价格。 I have connected everything to the database.我已将所有内容连接到数据库。 I made a good alternative of maiking the itemname column as an autocomplete text view and connecting it to the listview which is further connected to the database (which is hidden).我做了一个很好的选择,将 itemname 列作为自动完成文本视图并将其连接到列表视图,该列表视图进一步连接到数据库(这是隐藏的)。 So, i get the itemnames... now i want whenever i add the itemname in the column, the prices from the database of the corresponding item is retrieved automatically to the column ...please help me i am stucked with it from last month所以,我得到了项目名称......现在我想要每当我在列中添加项目名称时,相应项目的数据库中的价格会自动检索到该列......请帮助我我从上个月开始坚持使用它

 public Cursor getAllData1() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res1 = db.rawQuery("select * from " + Tname, null);
        return res1;
    }

In my main activity在我的主要活动中

 private void preparedata() {
        list = new ArrayList<String>();
        Cursor res1 = mydb.getAllData1();

        if (res1.getCount() == 0) {
            Toast.makeText(this, "No data in the database", Toast.LENGTH_SHORT).show();
        } else {
            while (res1.moveToNext()) {
                list.add(res1.getString(2));
                adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
                adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_2,array);
                listView.setAdapter(adapter);
            }

        }
    }


 --------------------------------------------------------------------------

  autocompletetextview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                       @Override
                                       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                           try {

                                               Cursor res2 = mydb.getAllData1();
                                               if (res2.getCount() == 0) {
                                                   Toast.makeText(shopp.this, "no item added", Toast.LENGTH_SHORT).show();
                                               } else {
                                                   while (res2.moveToNext()) {
                                                       et8.setText(res2.getString(2));
                                                   }

                                                   {

                                                   }
                                               }
                                           } catch (Exception e) {
                                               Toast.makeText(shopp.this, "Oops something went wrong", Toast.LENGTH_SHORT).show();
                                           }
                                       }
                                   });

One of the areas where you are going wrong or needlessly complicating matters is in your onItemClick Listsner.您出错或不必要地使问题复杂化的领域之一是您的 onItemClick Listsner。

The following answer is a working example that uses a Cursor adapter ( SimpleCursorAdapter ) and shows both columns Itemname and Itemprice.以下答案是一个使用 Cursor 适配器 ( SimpleCursorAdapter ) 并显示 Itemname 和 Itemprice 列的工作示例。 Additionally clicking on an item Toast all the values and Long Clicking will delete an Item and refresh the ListView.此外,单击一个项目 Toast 所有值,长按将删除一个项目并刷新 ListView。

However Cursor Adapters require a column name _id and it expects this to be the value of the rowid column.但是 Cursor Adapters 需要一个列名_id并且它期望这是rowid列的值。 The rowid column is a special column that uniquely identifies a row but it is normally hidden. rowid列是一个特殊的列,它唯一地标识一行,但它通常是隐藏的。 The query in the code that returns the Cursor (method getAllData2 ) makes use of this (basically the select SQL is SELECT rowid AS _id, * FROM the_table ).返回 Cursor 的代码中的查询(方法getAllData2 )利用了这个(基本上选择 SQL 是SELECT rowid AS _id, * FROM the_table )。

As the underlying source is the Cursor, the Cursor positioned for you is available and thus all the values.由于底层源是 Cursor,为您定位的 Cursor 可用,因此所有值都可用。 So there is no need to search you just get the values from the Cursor.因此无需搜索,只需从 Cursor 获取值即可。 Additional the 4th parameter to onItemClick/onItemLongClick is the value in the _id column (the rowid ) and this can be used to find a specific row (in the example onItemLongClick uses this for the deletion of the row).附加到 onItemClick/onItemLongClick 的第四个参数是_id列( rowid )中的,这可用于查找特定行(在示例中 onItemLongClick 使用它来删除行)。

The Database Helper DBHelper.java :-数据库助手DBHelper.java :-

public class DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSION = 1;

    public static final String Tname = "mytable";
    public static final String COL_ITEMNAME = "itemname";
    public static final String COL_ITEMPRICE = "itemprice";

    String crt_tbl = "CREATE TABLE IF NOT EXISTS " + Tname + "(" +
            COL_ITEMNAME + " TEXT UNIQUE," +
            COL_ITEMPRICE + " REAL DEFAULT 0.0" +
            ")";

    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(crt_tbl);
    }

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

    }

    public long addItem(String itemname, Double itemprice) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COL_ITEMNAME,itemname);
        cv.put(COL_ITEMPRICE, itemprice);
        return db.insert(Tname,null,cv);
    }

    //<<<<<<<<<< NOT USED
    public Cursor getAllData1() {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.rawQuery("select * from " + Tname, null);
    }

    //<<<<<<<<<< ALTERNATIVE USED 
    public Cursor getAllData2() {
        SQLiteDatabase db = this.getWritableDatabase();
        String[] columns = new String[]{"rowid AS " + BaseColumns._ID,"*"}; //<<<<<<<<<< see Note below
        return db.query(Tname,columns,null,null,null,null,null);
    }

    public int deleteItemByRowid(long id) {
        String whereclause = "rowid" + "=?";
        String[] whereargs = new String[]{String.valueOf(id)};
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(Tname,whereclause,whereargs);
    }
}
  • Note BaseColumns._ID resolves to _id so String[] columns = new String[]{"rowid AS " + BaseColumns._ID,"*"};注意 BaseColumns._ID 解析为_id所以String[] columns = new String[]{"rowid AS " + BaseColumns._ID,"*"}; creates a 2 element String array the first element has rowid AS _id , the second has * (all columns).创建一个 2 元素字符串数组,第一个元素具有rowid AS _id ,第二个元素具有* (所有列)。

MainActivity.java :- MainActivity.java :-

public class MainActivity extends AppCompatActivity {

    ListView mListView;
    DBHelper mydb;
    Cursor mCsr;
    SimpleCursorAdapter mSCA;
    Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        mListView = this.findViewById(R.id.listview);
        mydb = new DBHelper(this);
        addSomeDataForTesting(); //<<<<<<<<<< Add some test data
        doListView(); //<<<<<<<<<< setup the listview
    }

    private void doListView() {
        mCsr = mydb.getAllData2();
        if (mSCA == null) {
            mSCA = new SimpleCursorAdapter(this,
                    android.R.layout.simple_list_item_2,
                    mCsr,
                    new String[]{
                            DBHelper.COL_ITEMNAME,
                            DBHelper.COL_ITEMPRICE
                    },
                    new int[]{
                            android.R.id.text1,
                            android.R.id.text2
                    },
                    0
            );
            mListView.setAdapter(mSCA);

            // Set the onItemClick Listener
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Toast.makeText(mContext,
                            "You clicked on " + mCsr.getString(mCsr.getColumnIndex(DBHelper.COL_ITEMNAME)) +
                                    ". The Price is " + String.valueOf(mCsr.getDouble(mCsr.getColumnIndex(DBHelper.COL_ITEMPRICE))) +
                                    ". The rowid is " + String.valueOf(mCsr.getLong(mCsr.getColumnIndex(BaseColumns._ID))) +
                                    ". Alternately the rowid is " + String.valueOf(l), //<<<<<<<<<< l is the value of the column _id
                            Toast.LENGTH_SHORT
                            ).show();
                }
            });
            mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    mydb.deleteItemByRowid(l); //<<<<<<<<< uses the value of the 4th parameter passed which is the value of the _id column (which should be the rowid)
                    doListView();
                    return true;
                }
            });
        } else {
            mCsr = mydb.getAllData2();
            mSCA.swapCursor(mCsr);
        }
    }

    private void addSomeDataForTesting() {
        if (DatabaseUtils.queryNumEntries(mydb.getWritableDatabase(),DBHelper.Tname) < 1) {
            mydb.addItem("Item 1",25.55);
            mydb.addItem("Item 2",50.99);
            mydb.addItem("Item 3", 125.35);
        }
    }
}

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

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