0

別の初心者の質問に対する謝罪。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;

    }
4

1 に答える 1

3

getID()メソッドは、常にデータベースの最後のユーザーのIDを返します。ifステートメントがfalseと評価されているため、このユーザーはid=="100"ではありません。

getUserIDで、ログインテーブルのすべてのレコードを選択します。それで:

if(cursor != null) {
    while(cursor.moveToNext()) {
        id = cursor.getString(0);
    }
} else {
    id = "";
}

ユーザーがいる場合は最後のIDを返し、ユーザーがいない場合は「」を返します。

于 2012-11-12T15:33:03.140 に答える