如何使用App中的共享首选项保存JSONObject响应

时间:2015-01-20 09:34:55

标签: android json sharedpreferences

public class MainActivity extends Activity implements OnPreparedListener,
    OnClickListener {

Button login;
Button register;
EditText pass_word;
EditText mail;
TextView loginErrormsg;


private static final String TAG = null;
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_EMAIL = "email";
private static String KEY_PASSWORD = "password";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    setContentView(R.layout.activity_main);

    mail = (EditText) findViewById(R.id.email);
    pass_word = (EditText) findViewById(R.id.password);
    loginErrormsg = (TextView) findViewById(R.id.login_error);
    login = (Button) findViewById(R.id.btnlogin);
    register = (Button) findViewById(R.id.btnregister);

    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            String email = mail.getText().toString();
            String password = pass_word.getText().toString();
            UserFunctions userFunctions = new UserFunctions();
            JSONObject json = userFunctions.loginUser(email, password);
            // JSONObject userinfo = json.getJSONObject("user");

            // check for login response
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    loginErrormsg.setText("");
                    String res = json.getString(KEY_SUCCESS);


                    if (Integer.parseInt(res) == 1) {
                        Log.d("Login Successful!", json.toString());

                        // user successfully logged in
                        // Store user details in SQLite Database
                        DatabaseHandler db = new DatabaseHandler(
                                getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        // Clear all previous data in database
                        userFunctions.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_EMAIL),
                                json_user.getString(KEY_PASSWORD));

                        Intent dashboard = new Intent(
                                getApplicationContext(),
                                LoginActivity.class);
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);

                        // Close Login Screen
                        finish();
                    } else {
                        // Error in login
                        loginErrormsg
                                .setText("Incorrect username/password");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

    register.setOnClickListener(new View.OnClickListener() {

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

        }
    });

}

public static void setUserObject(Context c, String userObject, String key) {
    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(c);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString(key, userObject);
    editor.commit();
}
public static String getUserObject(Context ctx, String key) {
    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);
    return userObject;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
 }

这是我的服务器响应:

{
  "tag":"login",
  "success":1,
  "error":0,
  "user":{
    "email":"sridhar@gmail.com",
    "password":"7a4fb4770d2c404b0c48abd49f4c5f6a",
    "id":"118"
    }
  }

2 个答案:

答案 0 :(得分:4)

如果您只想从服务器响应中存储共享首选项中的id,则可以这样做,

JSONObject jsonObject = new JSONObject("Your response from server");
JSONObject jsonObject1 = jsonObject.getJSONObject("user");
String id = jsonObject1.getString("id");

SharedPreference sp = getApplicationContext().getSharedPreferences(
            "sharedPrefName", 0); // 0 for private mode

Editor editor = sp.edit();
editor.putString("key_name",id); // key_name is the name through which you can retrieve it later.
editor.commit();


// To retrieve value from shared preference in another activity
 SharedPreference sp = getApplicationContext().getSharedPreferences(
            "sharedPrefName", 0); // 0 for private mode
String id = sp.getString("key_name","defaultvalue"); // key_name is the key you have used for store "id" in shared preference. and deafult value can be anything. 

如果您的共享偏好不具有给定键的任何值,则默认值将返回,否则为key存储的值将返回

答案 1 :(得分:0)

好吧,因为你已经在json_user对象中拥有了id,所以就这样做:

String userId = json_user.optString("id");
if(!userId.isEmpty()) {
    getSharedPreferences(YOUR_PREFERENCE_NAME, MODE_PRIVATE).edit().putString(YOUR_USER_ID_KEY_NAME, userId).commit();
}

然后稍后检索它,使用:

String userId = getSharedPreferences(YOUR_PREFERENCE_NAME, MODE_PRIVATE).getString(YOUR_USER_ID_KEY_NAME, null);
if(userId != null) {
    //Successfully retrieved user id
}
else {
    //Id not found in preferences
}