簡體   English   中英

如何在MainActivity類中調用另一個類對象?

[英]How to call another class object in to MainActivity class?

實際上,我正在嘗試實現簡單的SQLiteDatabase程序。 MainActivity類可以正常工作。 當我嘗試調用DBUserAdapter類方法時,我的應用程序正在終止。

主要活動

    btninsert = (Button)findViewById(R.id.insertbtn);
    btninsert.setOnClickListener(insertListener);  
    OnClickListener insertListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        username = txtUserName.getText().toString();
        password = txtPassword.getText().toString();

        DBUserAdapter dbUser = new DBUserAdapter(getApplicationContext());
        dbUser.open();
        if(username.length()>0||password.length()>0){
            if(dbUser.AddUser(username, password)){
                Toast.makeText(getApplicationContext(), "User Successfully Inserted", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(getApplicationContext(), "User Already Existed in Records", Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(getApplicationContext(), "Enter The Values", Toast.LENGTH_SHORT).show();
        }
    }
};

DBUserAdapter類:

    public class DBUserAdapter {

public static final String KEY_ROWID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String TAG = "DBAdapter";

public static final String DATABASE_TABLE = "users";
public static final String DATABASE_NAME = "userdb";
public static final int DATABASE_VERSION = 1;

public static final String DATABASE_CREATE = "CREATE TABLE "+DATABASE_TABLE+" ("+KEY_ROWID+ " INTEGER PRIMARY KEY , "+
        KEY_USERNAME+ " TEXT,"+KEY_PASSWORD+"TEXT)";

private Context context;
private static SQLiteDatabase db;
private static DatabaseHelper DBHelper;

public DBUserAdapter(Context c){
    this.context = c;
    DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper{

    DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        Log.w(TAG, "Upgrading the Database from Version"+oldVersion+"to"+newVersion+",which will gestroy all old data");
        db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE);
        onCreate(db);
        }
    }
    public void open() throws SQLException{

        db = DBHelper.getWritableDatabase();    
    }

    public void close(){

        DBHelper.close();
    }

    public boolean AddUser(String username, String password){

        Cursor mCursor = db.rawQuery("SELECT * FROM"+DATABASE_TABLE+"WHERE username = ?", new String[]{username});

        if(mCursor != null){

            if(mCursor.getCount()>0){
            return false;
            }

        }

        ContentValues values = new ContentValues();
        values.put(KEY_USERNAME, username);
        values.put(KEY_PASSWORD, password);
        db.insert(DATABASE_TABLE, null, values);
        return true;
    }
}

您的幫助將不勝感激。 謝謝...

這是LogCat。

    02-11 01:17:39.484: I/Process(1085): Sending signal. PID: 1085 SIG: 9
    02-11 01:18:49.554: D/gralloc_goldfish(1138): Emulator without GPU emulation detected.
    02-11 01:18:53.444: D/AndroidRuntime(1138): Shutting down VM
    02-11 01:18:53.444: W/dalvikvm(1138): threadid=1: thread exiting with uncaught exception (group=0xb4a2cba8)
    02-11 01:18:53.464: E/AndroidRuntime(1138): FATAL EXCEPTION: main
    02-11 01:18:53.464: E/AndroidRuntime(1138): Process: com.siva.sqlite_app, PID: 1138
    02-11 01:18:53.464: E/AndroidRuntime(1138): java.lang.NullPointerException
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at com.siva.sqlite_app.MainActivity$5.onClick(MainActivity.java:142)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at android.view.View.performClick(View.java:4438)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at android.view.View$PerformClick.run(View.java:18422)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at android.os.Handler.handleCallback(Handler.java:733)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at android.os.Handler.dispatchMessage(Handler.java:95)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at android.os.Looper.loop(Looper.java:136)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at android.app.ActivityThread.main(ActivityThread.java:5017)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at java.lang.reflect.Method.invokeNative(Native Method)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at java.lang.reflect.Method.invoke(Method.java:515)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    02-11 01:18:53.464: E/AndroidRuntime(1138):     at dalvik.system.NativeStart.main(Native Method)
    02-11 01:18:56.244: I/Process(1138): Sending signal. PID: 1138 SIG: 9

我已經發布了我之前使用過的DbAdapter,它工作正常,只要研究一下它,您就會知道如何使用SQLITE數據庫

/ ** *簡單的Notes數據庫訪問幫助程序類。 定義記事本示例的基本CRUD操作,並提供列出所有注釋以及檢索或修改特定注釋的功能。 * *從本教程的第一個版本開始,已經進行了改進,*增加了更好的錯誤處理,並且還使用返回游標代替了*使用內部類的集合(可伸縮性較低,不建議使用)。 * /

public class DbAdapter {
public static final String KEY_ID = "uid";
public static final String USER_NAME = "username";
public static final String USER_TYPE = "usertype";
public static final String KEY_ACCESSKEY = "accesskey";
private static final String TAG = "DbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

/**
 * Database creation sql statement
 */
private static final String DATABASE_CREATE =
    "create table login (uid integer primary key, " + "username varchar(30) not null,"
    + "usertype integer not null, accesskey varchar(10) not null);";

private static final String DATABASE_NAME = "routetracker";
private static final String DATABASE_TABLE = "login";
private static final int DATABASE_VERSION = 4;

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS login");
        onCreate(db);
    }
}

/**
 * Constructor - takes the context to allow the database to be
 * opened/created
 * 
 * @param ctx the Context within which to work
 */
public DbAdapter(Context ctx) {
    this.mCtx = ctx;
}

/**
 * Open the notes database. If it cannot be opened, try to create a new
 * instance of the database. If it cannot be created, throw an exception to
 * signal the failure
 * 
 * @return this (self reference, allowing this to be chained in an
 *         initialization call)
 * @throws SQLException if the database could be neither opened or created
 */
public DbAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    Log.i(TAG, "Database Opened");
    return this;
}

public void close() {
    Log.i(TAG, "Database Closed");
    mDbHelper.close();
}


/**
 * Create a new note using the title and body provided. If the note is
 * successfully created return the new rowId for that note, otherwise return
 * a -1 to indicate failure.
 * 
 * @param title the title of the note
 * @param body the body of the note
 * @return rowId or -1 if failed
 */
public long createLogin(int uid,String userName,int userType,String accessKey) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_ID, uid);
    initialValues.put(USER_NAME, userName);
    initialValues.put(USER_TYPE, userType);
    initialValues.put(KEY_ACCESSKEY, accessKey);
    return mDb.insert(DATABASE_TABLE, null, initialValues);
}

/**
 * Delete the note with the given rowId
 * 
 * @param rowId id of note to delete
 * @return true if deleted, false otherwise
 */
public boolean deleteRow(long rowId) {

    return mDb.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null) > 0;
}

/**
 * Delete all the Rows
 * 
 * @return true if deleted, false otherwise
 */
public boolean deleteAllRow() {
    mDb.delete(DATABASE_TABLE, null, null);
    return true;
}

/**
 * Return a Cursor over the list of all notes in the database
 * 
 * @return Cursor over all notes
 */
public Cursor fetchAllRow() {

    return mDb.query(DATABASE_TABLE, new String[] {KEY_ID,USER_NAME,USER_TYPE,KEY_ACCESSKEY}, null, null, null, null, null);
}

/**
 * Return a Cursor positioned at the note that matches the given rowId
 * 
 * @param rowId id of note to retrieve
 * @return Cursor positioned to matching note, if found
 * @throws SQLException if note could not be found/retrieved
 */
public Cursor fetchRow(long rowId) throws SQLException {

    Cursor mCursor =

        mDb.query(true, DATABASE_TABLE, new String[] {KEY_ID, USER_NAME, USER_TYPE,
                KEY_ACCESSKEY}, KEY_ID + "=" + rowId, null,
                null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

/**
 * Update the Login using the details provided. The note to be updated is
 * specified using the rowId, and it is altered to use the accessKey
 * values passed in
 * 
 * @param rowId id of note to update
 * @param accessKey value to set note title to
 * @return true if the note was successfully updated, false otherwise
 */
public boolean updateRow(int uid,String userName,int userType,String accessKey) {
    ContentValues args = new ContentValues();
    args.put(KEY_ID, uid);
    args.put(USER_NAME, userName);
    args.put(USER_TYPE, userType);
    args.put(KEY_ACCESSKEY, accessKey);
    return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + uid, null) > 0;
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM