1

这是我们从数据库中获取信息的主要类。我们正在尝试获取我们创建的“条形码”数据库中“名称”列的值。现在,我们无法获得所需的值,而是“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]);
        }
    }
4

1 回答 1

0

您没有以正确的方式处理光标(您也不应该在主 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();
于 2013-04-29T18:56:09.557 回答