Darshan Jain
Darshan Jain

Reputation: 21

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

This is my Server response:

{
  "tag":"login",
  "success":1,
  "error":0,
  "user":{
    "email":"[email protected]",
    "password":"7a4fb4770d2c404b0c48abd49f4c5f6a",
    "id":"118"
    }
  }

Upvotes: 1

Views: 2857

Answers (2)

Yograj Shinde
Yograj Shinde

Reputation: 839

If you want to store only id in shared preference from you server responce, you can do it like,

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. 

Default value will be returns if your shared preference dose not have any value for given key, else value stored for key is returns

Upvotes: 4

nstosic
nstosic

Reputation: 2614

Well, since you already have the id in the json_user object, just do this:

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

Then later to retrieve it, use:

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
}

Upvotes: 0

Related Questions