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

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

问题描述

所以这是我的代码:

  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);
}

这是我下一个活动的代码:

  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 +\\\
+ recipe,Toast.LENGTH_SHORT).show();
bg.setBackgroundResource(getImageId(this,recipe));
}



我的问题是这部分: String _recipe = cursor.getString(1)
它总是给我错误的数据。我试图改变数字,但仍然给我错误的数据。



这是我的数据库:

  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上下文mCtx;

private static final String DATABASE_CREATE =
CREATE TABLE如果不存在+ SQLITE_TABLE +(+
ROWID +整数PRIMARY KEY自动递增+
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,升级数据库从版本+ oldVersion +到
+ newVersion +,这将销毁所有旧数据);
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);
}
}


解决方案

我建议您使用 getColumnIndex() 而不是硬编码。

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

这将确保您始终获得正确的字段。如果仍然得到错误的数据问题是在查询不在游标



注意:使用保存列名的静态字段始终是最佳做法。



更新:




我之前尝试过,它给我这个错误:
java.lang.IllegalArgumentException:column'recipe'不存在


你需要找出你的实际表结构。尝试执行此语句:

  PRAGMA table_info(Dbadapter.SQLITE_TABLE); 

docs( source ):


此pragma为命名表。
结果集中的列包括列名,数据类型,
是否可以为NULL和列的默认值。
对于不是主键的
部分的列,结果集中的pk列为零,并且是主键中的列的索引
键为列的一部分的主键。




示例:



通过 PRAGMA 获取tableinfo的方法:

  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(\\\
);
} while(c.moveToNext());
}
return b.toString();
}
finally {
if(c!= null){
c.close();
}
if(db!= null){
db.close();
}
}
}

 列:键入文本
列:日期文本
pre>

只有为想象力,我会给你屏幕:




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 gives 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天全站免登陆