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