Sii Ann Die Sii Ann Die - 4 months ago 10
Java Question

How to used shared prefences to save data that get from database?

I have this button code and it was connect to database

bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();

// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");

if (success) {
String name = jsonResponse.getString("name");
String email = jsonResponse.getString("email");
String alamat = jsonResponse.getString("alamat");
int notelp = jsonResponse.getInt("notelp");
String username = jsonResponse.getString("username");
String password = jsonResponse.getString("password");

Intent intent = new Intent(MainActivity.this, adminarea.class);
intent.putExtra("name", name);
intent.putExtra("email", email);
intent.putExtra("alamat", alamat);
intent.putExtra("notelp", notelp);
intent.putExtra("username", username);
intent.putExtra("password", password);
MainActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Login Gagal")
.setNegativeButton("Ulangi", null)
.create()
.show();
}

} catch (JSONException e) {
e.printStackTrace();
}
}
};


i have a table called admin thats contain field name, email and etc.. how can i take the data from databse then save my data like name, email, alamat and the other to shared prefences. then can you help me to call it to another activity?

Answer

First of all you have to create SharedPreferences

SharedPreferences pref = getApplicationContext().getSharedPreferences("YOUR_PREF_NAME", MODE_PRIVATE); 
Editor edt = pref.edit();

To add value in preference:

edt.putString("name", name);           
edt.putString("email", email);       
edt.putString("alamat", alamat);   
edt.putString("notelp", notelp);     
edt.putString("username",username); 

// Save your changes
edt.commit();

Now for getting data from preference:

String name=pref.getString("name", null);  
String email=pref.getString("email", null);  
String alamat=pref.getString("alamat", null);  
String notelp=pref.getString("notelp", null);  
String username=pref.getString("username", null);

If you want to clear the preference data:

edt.clear();
edt.commit();