实现扩展SQLiteOpenHelper的类

时间:2014-02-08 12:13:27

标签: java android sqlite

基本上我有两个类,一个扩展一个活动,另一个扩展SQLiteOpenHelper;

 public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
DashboardActivity da;
// Database Name
private static final String DATABASE_NAME = "android_api";

// Login table name
private static final String TABLE_LOGIN = "login";

// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public  String emaili;
public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
            + KEY_ID + " INTEGER PRIMARY KEY," 
            + KEY_NAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE,"
            + KEY_UID + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

    // Create tables again
    onCreate(db);
}

/**
 * Storing user details in database
 * */
public void addUser(String name, String email, String uid, String created_at) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, name); // Name
    values.put(KEY_EMAIL, email); // Email
    values.put(KEY_UID, uid); // Email
    values.put(KEY_CREATED_AT, created_at); // Created At

    // Inserting Row
    db.insert(TABLE_LOGIN, null, values);
    db.close(); // Closing database connection
}

/**
 * Getting user data from database
 * */
public HashMap<String, String> getUserDetails(){
    HashMap<String,String> user = new HashMap<String,String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN+"WHERE uid=9";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if(cursor.getCount() > 0){
        user.put("name", cursor.getString(1));
        user.put("email", cursor.getString(2));
        user.put("uid", cursor.getString(3));
        user.put("created_at", cursor.getString(4));
    }
    emaili = getUserDetails().get("email");

    cursor.close();
    db.close();
    // return user
    return user;
}

在我的活动类中,我试图将String emaili onCreate方法的值作为;

String email = db.emaili;

在顶部创建SQLite类的实现之后;

DatabaseHandler db;

错误是:

02-06 07:06:38.772: E/AndroidRuntime(26874): FATAL EXCEPTION: main
02-06 07:06:38.772: E/AndroidRuntime(26874): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidhive/com.example.androidhive.DashboardActivity}: java.lang.NullPointerException
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.app.ActivityThread.access$700(ActivityThread.java:143)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.os.Looper.loop(Looper.java:137)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.app.ActivityThread.main(ActivityThread.java:4950)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at java.lang.reflect.Method.invokeNative(Native Method)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at java.lang.reflect.Method.invoke(Method.java:511)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at dalvik.system.NativeStart.main(Native Method)
02-06 07:06:38.772: E/AndroidRuntime(26874): Caused by: java.lang.NullPointerException
02-06 07:06:38.772: E/AndroidRuntime(26874):    at com.example.androidhive.DashboardActivity.onCreate(DashboardActivity.java:48)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.app.Activity.performCreate(Activity.java:5177)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
02-06 07:06:38.772: E/AndroidRuntime(26874):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)

这是DasboardActivity类;

public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;

DatabaseHandler db;
Button btnFileUp;
Button btnViewData;





@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dashboard);
    // Buttons
    /**
     * Dashboard Screen for the application
     * */        
    // Check login status in database
    Button mondayEdit= (Button)findViewById(R.id.button1);
       String email = db.emaili;
       Log.i("EMAIL", ""+email);
//  email = db.getUserDetails()<
    userFunctions = new UserFunctions();
    if(userFunctions.isUserLoggedIn(getApplicationContext())){
        setContentView(R.layout.dashboard);

        btnViewData = (Button) findViewById(R.id.button1);

        btnViewData.setOnClickListener(new View.OnClickListener() 
        {   public void onClick(View v) 
            {   
                Intent intent = new Intent(getApplicationContext(), AllProductsActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);      

                    finish();
            }
        });




        btnFileUp = (Button) findViewById(R.id.button2);

        btnFileUp.setOnClickListener(new View.OnClickListener() 
        {   public void onClick(View v) 
            {   
                Intent intent = new Intent(getApplicationContext(), FileUploadTest.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);      
                    finish();
            }
        });


        btnLogout = (Button) findViewById(R.id.btnLogout);

        btnLogout.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                userFunctions.logoutUser(getApplicationContext());
                Intent login = new Intent(getApplicationContext(), LoginActivity.class);
                login.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(login);
                // Closing dashboard screen
                finish();
            }
        });

    }else{
        // user is not logged in show login screen
        Intent login = new Intent(getApplicationContext(), LoginActivity.class);
        login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(login);
        // Closing dashboard screen
        finish();
    }




}

public void onBackPressed(View v){
      Intent dashboard = new Intent(this, DashboardActivity.class);
      dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      dashboard.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    // Close all views before launching Dashboard
      // this.finish();
       startActivity(dashboard);  
}




}

1 个答案:

答案 0 :(得分:0)

将emaili var设为静态,以便您可以通过类的名称来调用它

static String emaili=null; 

String email =db.emaili;