为另一个新手问题道歉。我在MainActivity中有这个代码块应检查用户并根据if else语句返回适当的活动。问题是它跳过if块而我无法弄清楚原因。我所知道的是getID函数在其他类上运行正常。感谢您阅读本文。
public class MainActivity extends Activity {
UserFunctions userFunctions;
@Override
public void onCreate(Bundle savedInstanceState) {
userFunctions = new UserFunctions();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
UserFunctions fn = new UserFunctions();
String id = fn.getID(getApplicationContext());
if("100".equals(id)){
Intent in = new Intent(getApplicationContext(), AdminActivity.class);
startActivity(in);
finish();
}else{
Intent in = new Intent(getApplicationContext(), UserActivity.class);
startActivity(in);
finish();
}
}
}
UserFunction类
/* Get user ID from DatabaseHandler */
public String getID(Context context) {
String id = "";
DatabaseHandler db = new DatabaseHandler(context);
Cursor cursor = db.getUserID();
if(cursor != null) {
while(cursor.moveToNext()) {
id = cursor.getString(0);
}
} else {
id = "";
}
cursor.close();
db.close();
return id;
}
DatabaseHandler类
/* Get user ID from the database */
public Cursor getUserID() {
String qry = "SELECT id FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(qry, null);
return cursor;
}
答案 0 :(得分:3)
您的getID()方法始终返回数据库中最后一个用户的ID。此用户不是id ==“100”,因为您的if语句正在评估为false。
在getUserID中,您选择登录表中的所有记录。然后:
if(cursor != null) {
while(cursor.moveToNext()) {
id = cursor.getString(0);
}
} else {
id = "";
}
如果有任何用户,这将返回最后一个用户的ID,如果没有用户,则返回“”。