cursor.getstring()是变在数据库中的错误的字段 [英] cursor.getstring() is getting the wrong field in the database

查看:521
本文介绍了cursor.getstring()是变在数据库中的错误的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的code:

 公共无效onItemClick(适配器视图<>的ListView,视图中查看,
      INT位置,长的id){

      光标光标=(光标)listView.getItemAtPosition(位置);


      INT _id = cursor.getInt(0);
      串_recipe = cursor.getString(1);
      意向意图=新的意图(Luzon1Activity.this,RecipeInstruction.class);
      intent.putExtra(ID,_id);
      intent.putExtra(秘方,_recipe);
      startActivity(意向);
      }
      });
 

这是我的code为下一个活动:

 保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.recipeinstruction);


    dbHelper =新Dbadapter(本);
    dbHelper.open();
    BG =(RelativeLayout的)findViewById(R.id.relativeLayout1);

    捆绑额外= getIntent()getExtras()。
    如果(临时演员!= NULL){
        ID = extras.getInt(ID);
        配方= extras.getString(配方);
    }
    Toast.makeText(这一点,ID +\ N+配方,Toast.LENGTH_SHORT).show();
    bg.setBackgroundResource(getImageId(这一点,配方));



}
 

我的问题是关于这一部分:字符串_recipe = cursor.getString(1); 它总是给我错误的数据。我试图改变的数目,但它仍然给了我错误的数据。

这是我的数据库:

 包com.pinoycookbook;

    进口android.content.ContentValues​​;
    进口android.content.Context;
    进口android.database.Cursor;
    进口android.database.SQLException;
    进口android.database.sqlite.SQLiteDatabase;
    进口android.database.sqlite.SQLiteOpenHelper;
    进口android.util.Log;

    公共类Dbadapter {

公共静态最后弦乐ROWID =_id;
公共静态最终字符串名称=foodname;
公共静态最后弦乐ORIGIN =原产地;

公共静态最后弦乐食谱=秘方;

公共静态最后弦乐类别=类别;

私有静态最后字符串变量=Dbadapter;
私人DatabaseHelper mDbHelper;
私人SQLiteDatabase MDB;

私有静态最后弦乐DATABASE_NAME =PinoyCookbook.sqlite;
公共静态最后弦乐SQLITE_TABLE =粮食;
私有静态最终诠释DATABASE_VERSION = 1;

私人最终语境mCtx;

私有静态最后弦乐DATABASE_CREATE =
        CREATE TABLE如果不存在+ SQLITE_TABLE +(+
                ROWID +INTEGER PRIMARY KEY AUTOINCREMENT,+
                名称+TEXT+
                食谱+TEXT+
                ORIGIN +TEXT+
                类别+TEXT+
                UNIQUE(+ ROWID +));;

私有静态类DatabaseHelper扩展SQLiteOpenHelper {

    DatabaseHelper(上下文的背景下){
        超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
    }


    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        Log.w(TAG,DATABASE_CREATE);
        db.execSQL(DATABASE_CREATE);
    }

    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        Log.w(TAG,从版本升级数据库+ oldVersion +到
                +动态网页+,这将销毁所有旧数据);
        db.execSQL(DROP TABLE IF EXISTS+ SQLITE_TABLE);
        的onCreate(DB);
    }
}

公共Dbadapter(上下文CTX){
    this.mCtx = CTX;
}

公共Dbadapter的open()抛出的SQLException {
    mDbHelper =新DatabaseHelper(mCtx);
    MDB = mDbHelper.getWritableDatabase();
    回到这一点;
}

公共无效的close(){
    如果(mDbHelper!= NULL){
        mDbHelper.close();
    }
}

众长createData(字符串foodname,字符串配方,
        字符串的起源,int i)以{

    ContentValues​​ initialValues​​ =新ContentValues​​();
    initialValues​​.put(姓名,foodname);
    initialValues​​.put(配方,配方);
    initialValues​​.put(原产地,原产地);

    initialValues​​.put(类别,I);

    返回mDb.insert(SQLITE_TABLE,空,initialValues​​);
}

公共布尔deleteAllData(){

    INT doneDelete = 0;
    doneDelete = mDb.delete(SQLITE_TABLE,NULL,NULL);
    Log.w(TAG,Integer.toString(doneDelete));
    返回doneDelete> 0;

}


公共无效insertData(){

    createData(Adobong Manok(马诺科),adobongmanok,马尼拉,1);
    createData(菲律宾烧乳猪,菲律宾烧乳猪,宿,2);
    createData(脆​​皮啪嗒,crispypata,宿,2);
    createData(Bulalo,bulalo,打雁,1);
    createData(塔巴纳克Talangka稻,talangkarice,罗哈斯,2);
    createData(Arroz CALDO,arrozcaldo,罗哈斯,2);
    createData(Sinigang,sinigang,马尼拉,1);


}

    }
 

解决方案

所以,我推荐你使用<一个href="http://developer.android.com/reference/android/database/Cursor.html#getColumnIndex%28java.lang.String%29"相对=nofollow> getColumnIndex() 的方法,而不是硬code吧。

 字符串_recipe = cursor.getString(cursor.getColumnIndex(Dbadapter.RECIPE));
 

这将保证你会得到永远正确的领域。如果它仍然得到错误的数据问题在查询未在光标

注意:的静态字段持有列名的使用始终是最好的做法

更新:

  

我以前尝试过了,它给了我这个错误:   java.lang.IllegalArgumentException:如果列'配方'不存在

您需要了解您的实际表结构。尝试执行该语句:

  PRAGMA table_info(Dbadapter.SQLITE_TABLE);
 

什么说的文档():

  

本附注返回一行在命名表中的每一列。   列在结果集中包括列名,数据类型,无论是   或不在列可以为NULL,和该​​列的默认值。   在结果集的PK栏目是为那些不列为零   主键的一部分,并且是列在主索引   关键是主键的一部分列。

例:

在这里,我给你的方法创建通过 PRAGMA 获得tableinfo:

 公共字符串getTableInfo(){
    StringBuilder的B =新的StringBuilder();
    光标C = NULL;
    尝试 {
        DB = helper.getReadableDatabase();
        查询字符串=杂table_info(+ Dbadapter.SQLITE_TABLE +);
        C = db.rawQuery(查询,NULL);
        如果(c.moveToFirst()){
            做 {
                在b.append(歌罗西书:+ c.getString(c.getColumnIndex(名字))+);
                在b.append(c.getString(c.getColumnIndex(类型)));
                在b.append(\ N);
            }而(c.moveToNext());
        }
        返回b.toString();
    }
    最后 {
        如果(C!= NULL){
            c.close();
        }
        如果(DB!= NULL){
            db.close();
        }
    }
}
 

输出将是这样的:

 列:键入文本
专栏:日期文本
 

仅限于想象,我会给你的屏幕:

So this is my code:

      public void onItemClick(AdapterView<?> listView, View view, 
      int position, long id) {

      Cursor cursor = (Cursor) listView.getItemAtPosition(position);


      int _id = cursor.getInt(0);
      String _recipe = cursor.getString(1);
      Intent intent = new Intent(Luzon1Activity.this,RecipeInstruction.class);
      intent.putExtra("id", _id);
      intent.putExtra("recipe", _recipe);
      startActivity(intent);
      }
      });

This is my code for the next activity:

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


    dbHelper = new Dbadapter(this);
    dbHelper.open();
    bg = (RelativeLayout) findViewById(R.id.relativeLayout1);

    Bundle extras = getIntent().getExtras();
    if (extras != null){
        id = extras.getInt("id");   
        recipe = extras.getString("recipe");
    }
    Toast.makeText(this, id+"\n"+recipe, Toast.LENGTH_SHORT).show();
    bg.setBackgroundResource(getImageId(this, recipe));



}

My problem is on this part: String _recipe = cursor.getString(1); It always give me the wrong data. I tried to change the number but still it gives me the wrong data.

this is my database:

    package com.pinoycookbook;

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

    public class Dbadapter {

public static final String ROWID = "_id";
public static final String NAME = "foodname";
public static final String ORIGIN = "origin";

public static final String RECIPE = "recipe";

public static final String CATEGORY = "category";

private static final String TAG = "Dbadapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "PinoyCookbook.sqlite";
public static final String SQLITE_TABLE = "Food";
private static final int DATABASE_VERSION = 1;

private final Context mCtx;

private static final String DATABASE_CREATE =
        "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
                ROWID + " integer PRIMARY KEY autoincrement," +
                NAME + " TEXT," +
                RECIPE + " TEXT," +
                ORIGIN + " TEXT," + 
                CATEGORY+ " TEXT,"+
                " UNIQUE (" + ROWID +"));";

private static class DatabaseHelper extends SQLiteOpenHelper {

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


    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.w(TAG, DATABASE_CREATE);
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
        onCreate(db);
    }
}

public Dbadapter(Context ctx) {
    this.mCtx = ctx;
}

public Dbadapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    if (mDbHelper != null) {
        mDbHelper.close();
    }
}

public long createData(String foodname, String recipe, 
        String origin,  int i) {

    ContentValues initialValues = new ContentValues();
    initialValues.put(NAME, foodname);
    initialValues.put(RECIPE, recipe);
    initialValues.put(ORIGIN, origin);

    initialValues.put(CATEGORY, i);

    return mDb.insert(SQLITE_TABLE, null, initialValues);
}

public boolean deleteAllData() {

    int doneDelete = 0;
    doneDelete = mDb.delete(SQLITE_TABLE, null , null);
    Log.w(TAG, Integer.toString(doneDelete));
    return doneDelete > 0;

}


public void insertData() {

    createData("Adobong Manok","adobongmanok","Manila",1);
    createData("Lechon","lechon","Cebu",2);
    createData("Crispy Pata","crispypata","Cebu",2);
    createData("Bulalo","bulalo","Batangas",1);
    createData("Taba ng Talangka Rice","talangkarice","Roxas",2);
    createData("Arroz Caldo","arrozcaldo","Roxas",2);
    createData("Sinigang","sinigang","Manila",1);


}

    }

解决方案

So i recommend you to use getColumnIndex() method rather than hardcode it.

String _recipe = cursor.getString(cursor.getColumnIndex(Dbadapter.RECIPE));

It will ensure that you will get always right field. And if it still get wrong data problem is in query not in Cursor

Note: An usage of static fields that hold column names is always the best practise.

Update:

I've tried it before and it gives me this error: java.lang.IllegalArgumentException: column 'recipe' does not exist

You need to find out your actual table structure. Try to perform this statement:

PRAGMA table_info(Dbadapter.SQLITE_TABLE);

What says docs(source):

This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.

Example:

Here i created for you method for getting tableinfo via PRAGMA:

public String getTableInfo() {
    StringBuilder b = new StringBuilder("");
    Cursor c = null;
    try {
        db = helper.getReadableDatabase();
        String query = "pragma table_info(" + Dbadapter.SQLITE_TABLE + ")";
        c = db.rawQuery(query, null);
        if (c.moveToFirst()) {
            do {
                b.append("Col:" + c.getString(c.getColumnIndex("name")) + " ");                     
                b.append(c.getString(c.getColumnIndex("type")));
                b.append("\n");
            } while (c.moveToNext());
        }
        return b.toString();
    }
    finally {
        if (c != null) {
            c.close();
        }
        if (db != null) {
            db.close();
        }
    }
}

Output will be something like this:

Column: type text
Column: date text

Only for imagination i will give you screen:

这篇关于cursor.getstring()是变在数据库中的错误的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆