Sii Ann Die Sii Ann Die - 1 year ago 63
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() {
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>() {
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);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Login Gagal")
.setNegativeButton("Ulangi", null)

} catch (JSONException e) {

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 Source

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

// Save your changes

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download