2014-02-11 4 views
0

На самом деле я пытаюсь реализовать простую программу SQLiteDatabase. Класс MainActivity работает без проблем. когда я пытался вызвать методы класса DBUserAdapter, мое приложение завершается.Как вызвать другой объект класса в класс MainActivity?

MainActivity класс

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 
+0

Использование статической переменной. – InnocentKiller

+0

Сбой при вызове 'AddUser'? – Apoorv

+0

Просьба указать logcat – gilonm

ответ

0

Я разместил DbAdapter, которые я использовал ранее, и она отлично работает только смотреть на него вы получите некоторое представление о том, как использовать базу данных SQLITE

/** * Простые примечания база данных доступ вспомогательный класс. Определяет основные операции 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; 
} 

}

+0

попробуйте приведенный выше код и отредактируйте его, как хотите! я надеюсь, что это будет полезно для вас – arun

+0

Спасибо .. Я буду работать над этим и вернуться к вам .. – user3164399

+0

На самом деле проблема в MainActivity ... Пожалуйста, обратите внимание на то, что один раз ... – user3164399

Смежные вопросы