如何在应用程序中使用共享首选项保存 JSON 对象响应

how to save JSONObject reponse using Shared Preferences in App

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"
    }
  }

好吧,既然你已经在 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
}

如果您只想在服务器响应的共享首选项中存储 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. 

如果您的共享偏好没有给定键的任何值,则默认值为 returns,否则为键存储的值为 returns