【问题标题】:getString method in android does not workandroid中的getString方法不起作用
【发布时间】:2013-04-30 02:56:09
【问题描述】:

这是我们从数据库中获取信息的主要类。我们正在尝试获取我们创建的“条形码”数据库中“名称”列的值。现在,我们无法获得所需的值,而是“a,b,c,d,...”的值(例如;当我们要求第一个时,它返回“a”,它返回“b”当我们使用cursor.getString 方法询问“名称”列中的第二个)值时

    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            DataBaseHelper myDbHelper = new DataBaseHelper(this);
            myDbHelper = new DataBaseHelper(this);
            try {
                myDbHelper.createDatabase();
            } catch (IOException ioe) {
                throw new Error("Unable to create database");
            }

            try {
                myDbHelper.openDataBase();
            } catch(SQLException sqle){
                throw sqle;
            }

            Cursor cursor = myDbHelper.getAllAccounts();

            String[] values = new String[6];
            int i=0;

            //take into the array from the database
            while(cursor.moveToNext()){
                values[i]= cursor.getString(cursor.getColumnIndex("name"));
                i++;
            }

            cursor.close(); 

            //Write to textview
            TextView youtextview = (TextView) findViewById(R.id.textView1);
            youtextview .setText(values[2]);
        }
    }

【问题讨论】:

  • getString method does not work - 是的。您的代码显然没有,但您没有清楚地描述问题所在。 究竟会发生什么?
  • 我实际上的意思是,我得到的不是数据库中 values[2] 的值,而是值“b”。当我将值 [2] 更改为值 [1] 时,我得到了“a”或值 [3],我得到了“c”。在数据库中,我没有像“a”、“b”或“c”这样的数据。顺便说一下,我在 SQLite 数据库浏览器中创建了数据库。我的数据库看起来像:
  • 它有一个 id 列是“整数主键”和 name 列是“文本”。

标签: android sqlite getstring


【解决方案1】:

您没有以正确的方式处理光标(您也不应该在主 UI 线程中进行 DB 调用,这正是您现在正在做的事情)。见:http://developer.android.com/reference/android/database/Cursor.html

static final COL_NAME = "name";
Cursor cursor = myDbHelper.getAllAccounts();
cursor.moveToFirst();
int maxCursorIndex = cursor.getCount();
for(int cursorIndex=0;cursorIndex<maxCursorIndex;cursorIndex+=1){
    values[cursorIndex] = cursor.getString(cursor.getColumnIndex(COL_NAME);
}
cursor.close();

【讨论】:

  • 您还应该检查以确保没有返回空光标。
猜你喜欢
  • 2011-04-18
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多