jjzjj

java - cursor.getstring() 在数据库中获取错误的字段

coder 2023-12-10 原文

所以这是我的代码:

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

这是我下一个 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));
}

我的问题出在这部分: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 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);
    }
}

最佳答案

所以我推荐你使用getColumnIndex()方法而不是对其进行硬编码。

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

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

注意:使用包含列名称的静态字段始终是最佳实践。

更新:

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

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

PRAGMA table_info(Dbadapter.SQLITE_TABLE);

文档是怎么说的(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.

示例:

我在这里为您创建了通过 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();
        }
    }
}

输出将是这样的:

Column: type text
Column: date text

只为想象我给你屏幕:

关于java - cursor.getstring() 在数据库中获取错误的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15680853/

有关java - cursor.getstring() 在数据库中获取错误的字段的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  4. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  7. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  8. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  9. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  10. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

随机推荐