数据无法添加到android上的sqlite数据库

时间:2012-06-01 04:50:14

标签: java android sqlite

我正在尝试为Android创建一个登录系统。在此登录系统中,当用户登录时,他的详细信息将被添加到sqlite数据库中,因此当他再次打开此应用程序时,他将保持登录状态。目前的问题是,当我在DatabaseHandler类中调用addUser()方法时,它说不uid的价值。但是当我在logcat中显示json数据时,它会显示uid值。我不知道我在哪里弄错了。请帮我。这是我的代码

LoginActivity

public class LoginActivity extends Activity {
EditText email, password;
Button loginButton, btnLinkToLoginScreen;
TextView login_error;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    email = (EditText)findViewById(R.id.loginEmail);
    password = (EditText)findViewById(R.id.loginPassword);
    loginButton = (Button)findViewById(R.id.btnLogin);
    login_error = (TextView)findViewById(R.id.login_error);
    btnLinkToLoginScreen = (Button)findViewById(R.id.btnLinkToLoginScreen);

 // JSON Response node names
    String KEY_SUCCESS = "success";
    String KEY_ERROR = "error";
    String KEY_ERROR_MSG = "error_msg";
    final String KEY_UID = "uid";
    final String KEY_NAME = "name";
    final String KEY_EMAIL = "email";
    final String KEY_CREATED_AT = "created_at";

    loginButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            //loginButton.setEnabled(false);
            final String useremail = email.getText().toString();
            final String userpassword = password.getText().toString();
            //Toast.makeText(getBaseContext(), useremail, Toast.LENGTH_LONG).show();

            //Log.e("useremail ", useremail);
            //Toast.makeText(getBaseContext(), useremail, Toast.LENGTH_LONG).show();
            if(!useremail.isEmpty() && !userpassword.isEmpty()) {
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.loginUser(useremail,userpassword);
                /*************************************************/
                try {
                    JSONObject obj = json.getJSONObject("user");
                    Log.e("son", obj.getString(KEY_UID));
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                /**************************************************/
                try {
                    if(json != null && json.getString("success") != null) {
                        login_error.setText("");
                        String res = json.getString("success");
                        if(Integer.parseInt(res) == 1) {
                            //loginButton.setEnabled(true);
                            //store user in SQLITE
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");
                            String s = json_user.getString("name") + ", " + json_user.getString("email") + ", " + json.getString("uid") + ", " + json_user.getString("created_at");
                            Log.e("String: ", s);
                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString("name"), json_user.getString("email"), json_user.getString(KEY_UID), json_user.getString("created_at"));
                            //store user in SQLITE ends

                            //launch dashboard screen
                            //Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                            //Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_LONG).show();
                            Intent i = new Intent(getApplicationContext(),
                                    DashboardActivity.class);

                            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(i);
                            finish();
                        }
                    } else {
                        Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                loginButton.setEnabled(true);
                login_error.setText("Enter username and password");
            }
        }

    });

    btnLinkToLoginScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(getApplicationContext(),
                    RegisterActivity.class);
            startActivity(i);
            finish();
        }
    });
}
}

这是我的DatabaseHandler类

public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// 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 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" + ")";
    Log.e("Query: ", CREATE_LOGIN_TABLE);
    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();
    Log.e("Data", uid);
    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
    Log.e("Values: ", values.toString());
    // 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;

    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));
    }
    cursor.close();
    db.close();
    // return user
    return user;
}

/**
 * Getting user login status
 * return true if rows are there in table
 * */
public int getRowCount() {
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int rowCount = cursor.getCount();
    db.close();
    cursor.close();

    // return row count
    return rowCount;
}

/**
 * Re crate database
 * Delete all tables and create them again
 * */
public void resetTables(){
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_LOGIN, null, null);
    db.close();
}

}

这是logcat

06-01 07:38:43.111: W/KeyCharacterMap(32734): No keyboard for id 0
06-01 07:38:43.111: W/KeyCharacterMap(32734): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-01 07:38:43.316: D/CLIPBOARD(32734): Hide Clipboard dialog at Starting input: finished by someone else... !
06-01 07:38:43.316: W/IInputConnectionWrapper(32734): showStatusIcon on inactive InputConnection
06-01 07:38:48.346: D/dalvikvm(32734): GC_EXTERNAL_ALLOC freed 100K, 47% free 3040K/5639K, external 357K/661K, paused 20ms
06-01 07:38:49.521: W/KeyCharacterMap(32734): No keyboard for id 0
06-01 07:38:49.521: W/KeyCharacterMap(32734): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-01 07:38:49.831: D/CLIPBOARD(32734): Hide Clipboard dialog at Starting input: finished by someone else... !
06-01 07:38:49.831: W/IInputConnectionWrapper(32734): showStatusIcon on inactive   InputConnection
06-01 07:39:49.646: D/dalvikvm(582): GC_CONCURRENT freed 115K, 46% free 3028K/5575K, external 319K/661K, paused 7ms+7ms
06-01 07:39:50.271: E/JSON(582): {"tag":"login","success":1,"error":0,"user":{"name":"Zafar Saleem","uid":"4fc0e87ec8ade4.83917704","email":"zafar@gmail.com","created_at":"2012-05-26 17:28:14","updated_at":null}}
06-01 07:39:50.276: E/son(582): 4fc0e87ec8ade4.83917704
06-01 07:39:50.276: W/System.err(582): org.json.JSONException: No value for uid
06-01 07:39:50.276: W/System.err(582):  at org.json.JSONObject.get(JSONObject.java:354)
06-01 07:39:50.296: W/System.err(582):  at org.json.JSONObject.getString(JSONObject.java:510)
06-01 07:39:50.296: W/System.err(582):  at com.zafar.login.LoginActivity$1.onClick(LoginActivity.java:74)
06-01 07:39:50.296: W/System.err(582):  at android.view.View.performClick(View.java:2538)
06-01 07:39:50.296: W/System.err(582):  at android.view.View$PerformClick.run(View.java:9152)
06-01 07:39:50.296: W/System.err(582):  at android.os.Handler.handleCallback(Handler.java:587)
06-01 07:39:50.296: W/System.err(582):  at android.os.Handler.dispatchMessage(Handler.java:92)
06-01 07:39:50.296: W/System.err(582):  at android.os.Looper.loop(Looper.java:130)
06-01 07:39:50.301: W/System.err(582):  at android.app.ActivityThread.main(ActivityThread.java:3691)
06-01 07:39:50.301: W/System.err(582):  at java.lang.reflect.Method.invokeNative(Native Method)
06-01 07:39:50.301: W/System.err(582):  at java.lang.reflect.Method.invoke(Method.java:507)
06-01 07:39:50.306: W/System.err(582):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
06-01 07:39:50.306: W/System.err(582):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
06-01 07:39:50.306: W/System.err(582):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

更改

String s = json_user.getString("name") + ", " + 
           json_user.getString("email") + ", " + 
           json.getString("uid") + ", " + 
           json_user.getString("created_at");

String s = json_user.getString("name") + ", " + 
           json_user.getString("email") + ", " + 
           json_user.getString("uid") + ", " + 
           json_user.getString("created_at");

在LoginActivity.java的第74行