我有下表
private static final String DB_TABLE = "create table user (id integer primary key autoincrement, "
+ "username text not null, password text not null, tel text not null, info text not null, job text);";
如何使用游标获取数据并将其转换为字符串?因为我得到null我应该设置得到吗? 我必须通过用户名和密码获取工作和信息吗?
Cursor theUser = dbHelper.fetchUser(thisUsername, thisPassword);
if (theUser != null) {
// How here also fetch a info and job in String?
startManagingCursor(theUser);
if (theUser.getCount() > 0) {
//saveLoggedInUId(theUser.getLong(theUser.getColumnIndex(DatabaseAdapter.COL_ID)), thisUsername, thePassword.getText().toString());
stopManagingCursor(theUser);
theUser.close();
// String text = dbHelper.getYourData();
Intent i = new Intent(v.getContext(), InfoActivity.class);
startActivity(i);
}
//Returns appropriate message if no match is made
else {
Toast.makeText(getApplicationContext(),
"You have entered an incorrect username or password.",
Toast.LENGTH_SHORT).show();
// saveLoggedInUId(0, "", "");
}
stopManagingCursor(theUser);
theUser.close();
}
else {
Toast.makeText(getApplicationContext(),
"Database query error",
Toast.LENGTH_SHORT).show();
}
}
private static final String LOGIN_TABLE = "user";
//Table unique id
public static final String COL_ID = "id";
//Table username and password columns
public static final String COL_USERNAME = "username";
public static final String COL_PASSWORD = "password";
private static final String KEY_PHONE = "tel";
private static final String INFO = "info";
private static final String JOB = "info";
public Cursor fetchUser(String username, String password) {
Cursor myCursor = database.query(LOGIN_TABLE,
new String[] { COL_ID, COL_USERNAME, COL_PASSWORD },
COL_USERNAME + "='" + username + "' AND " +
COL_PASSWORD + "='" + password + "'", null, null, null, null);
if (myCursor != null) {
myCursor.moveToFirst();
}
return myCursor;
}
提前谢谢!!!
更新:
String name = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.COL_USERNAME));
String phone = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.KEY_PHONE));
String tel = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.KEY_PHONE));
String info = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.INFO));
String job = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.JOB));
String id = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.COL_ID));
我如何写这个请求:
public Cursor fetchAllUsers() {
return database.query(LOGIN_TABLE, new String[] { COL_ID, COL_USERNAME,
COL_PASSWORD }, null, null, null, null, null);
}
答案 0 :(得分:1)
要在各个数据行之间移动,您可以使用moveToFirst()
和moveToNext()
方法。 isAfterLast()
方法允许检查是否已到达查询结果的末尾。
Cursor
提供了键入的get*()
方法,例如getLong(columnIndex)
,getString(columnIndex)
访问结果当前位置的列数据。 " columnIndex"是您要访问的列的编号。
Cursor还提供getColumnIndexOrThrow(String)
方法,该方法允许获取表的列名的列索引。
完成后,需要使用close()
方法调用关闭Cursor。
您的代码应该看起来像这样以获取信息列,但请在您的问题中注意JOB和INFO列具有相同的字符串,因此他们将返回相同的列索引,直到您修复
String info = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.INFO))