Camper1233 Camper1233 - 6 months ago 31
Java Question

Android studio shared preferences store to device storage

I'm a new android app developer. I was making an app and i would like to store the balance integer using shared preferences but I'm not sure how to do it. I did a lot of googling and I'm still confused. Could anyone please put the shared preferences to store the balance integer in my code? Here's the code.

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
int balance = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Click counter
final TextView text = (TextView) findViewById(R.id.balance_text);
assert text != null;
text.setText(balance + " $");
final ImageButton button = (ImageButton) findViewById(R.id.click_button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
balance++;
text.setText("" + balance + " $");
}
});
}

}

Answer

Please find the below code to get the values from sharedpreferences

public class MainActivity extends AppCompatActivity {
int balance;;
private SharedPreferences preferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Hide notification bar
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //Click counter
    final TextView text = (TextView) findViewById(R.id.balance_text);
    assert text != null;
    // to retreuve the values from the shared preference
    preferences = PreferenceManager.getDefaultSharedPreferences(this);
    balance = preferences.getInt("balance", 0);
    text.setText(balance + " $");
    final ImageButton button = (ImageButton) findViewById(R.id.click_button);
    assert button != null;
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            balance++;
            text.setText("" + balance + " $");
        }
    });
}

}

Use these lines to save to shared preference. You can use this on your onBackPressed()

@Override
public void onBackPressed() {
    super.onBackPressed();
    SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("balance", balance);
        editor.apply();
}
Comments