How to store the array of string in shared preferences? [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
How to store the array of String in SharedPreferences? And please give me an example code for storing array few names and retrieve it in another activity. Thanks in advance

Let me try and help you
First of all set up these class variables in the Activities you want to use SharedPreferences
public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;
Then to store the string values like this
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.putString("key3", "value3");
editor.commit(); // to persist the values between activities
and the finally to access the sharedPreferences in another activity use this
mySharedPreferences = getSharedPreferences(MY_PREFS, prefMode);
String string1 = mySharedPreferences.getString("key1", null);
String string2 = mySharedPreferences.getString("key2", null);
hope this helps you a lil bit.

first activity.
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putString("str"+i, name[i]);
editor.commit();
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
second activity
public class Secondact extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
preferences = getSharedPreferences("testarray", MODE_PRIVATE);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<3;i++)
{
Log.d("aa", preferences.getString("str"+i, " "));
}
}
});
}
}
using set of strings
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
Set<String> values = new HashSet<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
values.add(name[i]);
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putStringSet("str", values);
editor.commit();
}
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
public class Secondact extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
preferences = getSharedPreferences("testarray", MODE_PRIVATE);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Set<String> values = preferences.getStringSet("str", null);
String[] name = values.toArray(new String[values.size()]);
for (int i = 0; i < values.size(); i++) {
Log.d("aa", name[i]);
}
}
});
}
}

Arrays are not supported. However you can store a Set.
SharedPreferences prefs = parent.getContext().getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Set<String> values = new HashSet<String>();
values.add("value 1");
values.add("value 2");
prefs.edit().putStringSet("myKey", values).commit();

Related

Data Lost onresume after returning back from different activities

I am a newbie on android programming and I think I came across a very basic problem. Actually searching stackoverflow for two days but I am not able to find a solution for my situation.
So in summary I am try to make an application for a calculation.
I have 5 activities: MainActivity, ActivityA (selecting something and taking value from ArrayList), ActivityB (again selecting something and taking value from ArrayList), ActivityC (entering value and than taking another value), Activity D (entering value and taking another value)
Then on Mainactivity these values will be used for an equation.
I take values by using intent and I coded intent in onresume.
First I go to ActivityA and select what I want and return back to Mainactivity and I have the required value, but when I do this for ActivityB and return back to Mainactivity, I lost the value from ActivityA because I think program do the intent again for ActivityA also (this is the same for all other activities). So I think I need to somehow separate intent for all activities. I tried using sharedpreferences or creating same string on all activities with different values to use in a if or switch case in onresume part unfortunately I have not succeed it.
public class MainActivity extends AppCompatActivity {
//Değerlerin girildiği text kutucuklarının tanımlanması
EditText designPressure;
EditText corrosionAllowance;
EditText pipeDiameter;
EditText selectedMaterial;
EditText selectedAllowableStress;
EditText selectedPipeClass;
EditText selectedWeldFactor;
EditText selectedTemperature;
EditText selectedTempFactor;
EditText selectedLocation;
EditText selectedDesignFactor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Değerlerin girildiği textkutucuklarının eşleştirilmesi
designPressure = findViewById(R.id.designPressure);
corrosionAllowance = findViewById(R.id.corrosionAllowance);
pipeDiameter = findViewById(R.id.pipeDiameter);
selectedMaterial = findViewById(R.id.selectedMaterial);
selectedAllowableStress = findViewById(R.id.selectedAllowableStress);
selectedPipeClass = findViewById(R.id.selectedPipeClass);
selectedWeldFactor = findViewById(R.id.selectedWeldFactor);
selectedTemperature = findViewById(R.id.selectedTemperature);
selectedTempFactor = findViewById(R.id.selectedTempFactor);
selectedLocation = findViewById(R.id.selectedLocation);
selectedDesignFactor = findViewById(R.id.selectedDesignFactor);
}
#Override
public void onResume(){
super.onResume();
Intent intent = getIntent();
//Malzeme sayfasından bilgi alan kısım
String selectedM = intent.getStringExtra("Material");
selectedMaterial.setText(selectedM);
String selectedAS = intent.getStringExtra("Allowable Stress");
selectedAllowableStress.setText(selectedAS);
//WeldFactor sayfasından bilgi alan kısım
String weldFactors = intent.getStringExtra("Type");
selectedPipeClass.setText(weldFactors);
String eFactor = intent.getStringExtra("eFactor");
selectedWeldFactor.setText(eFactor);
// TempFactor sayfasından bilgi alan kısım
String selectedTF = intent.getStringExtra("selectedTFactor");
selectedTempFactor.setText(selectedTF);
String selectedDT = intent.getStringExtra("selectedDTemp");
selectedTemperature.setText(selectedDT);
}
//SelectMaterial tuşuna basınca MaterialList sayfasına giden toMAterialList onclick metodu
public void toMaterialList(View view){
Intent intentMaterial = new Intent(MainActivity.this, MaterialList.class);
startActivity(intentMaterial);
}
//SelectWeldFactor tuşuna basınca WeldFactor sayfasına giden toWeldFactor onclick metodu
public void toWeldFactor(View view){
Intent intentWeldFactor = new Intent(MainActivity.this, WeldFactor.class);
startActivity(intentWeldFactor);
}
//SelectTempFactor tuşuna basınca TempFactor sayfasına giden toTempFactor onclick metodu
public void toTempFactor(View view){
Intent intentTempFactor = new Intent(MainActivity.this, TempFactor.class);
startActivity(intentTempFactor);
}
public void toDesignFactor(View view){
Intent intentdesignFactor = new Intent(MainActivity.this, DesignFactor.class);
startActivity(intentdesignFactor);
}
public void calculate(View view){
}
}
The problem is that you can not send data from activity B to activity A. if you want that you must use startActivityForResult .you can not get data from an activity that is destroyed.
The best way for you is using sharedpreferences .
//Main Activity
public class MainActivity extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String selectedMaterial = "selectedMaterial";
public static final String selectedAllowableStress = "selectedAllowableStress";
public static final String selectedTemperature = "selectedTemperature";
// For get strings
public static final String _selectedTemperature;
public static final String _selectedAllowableStress;
public static final String _selectedMaterial;
SharedPreferences sharedpreferences;
#Override
public void onResume(){
super.onResume();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
_selectedMaterial=editor.getString(selectedMaterial, "");
_selectedAllowableStress=editor.getString(selectedAllowableStress, "");
_selectedTemperature=editor.getString(selectedTemperature, "");
editor.commit();
}
}
//Activity A
public class ActivityA extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
public static final String selectedMaterial = "selectedMaterial";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(selectedMaterial, "material");
editor.commit();
}
}
//Activity B
public class ActivityB extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
public static final String selectedMaterial = "selectedAllowableStress";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(selectedAllowableStress, "allow");
editor.commit();
}
}

Don't read sharedPreferences from another class

I'm trying to get my app to look first if shared preferences is set. If not it must open a page where you type them in, and then hopefully save them which I will use later. It looks like it either finds some shared preferences or my code is wrong because the main activity opens (the else statement executes).
Here is my Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean check = sharedPreferences.getBoolean("Check",false);
if(check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
And here is the SharedPrefs:
public class SharedPrefs extends MainActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
I must be honest I'm not quite sure where I want Java to look for Shared preferences, "this makes the app run at least.
Inside the SharedPrefs{} class, declare the variable
public static boolean CHECK_VALUE = false;
In the same class inside onClick(View v) method after editor.commit();, set
CHECK_VALUE = true;
And in MainActivity{} class inside OnCreate() method
if(!SharedPrefs.CHECK_VALUE){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
Actually you don't need a SharedPreference to check here. If you really do, then put
editor.putBoolean("check", true);
insideOnClick() method of SharedPrefs{} class and to get it from or to use it in MainActivity
SharedPreferences sharedPreferences = getSharedPreferences(SharedPrefs.MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Check = sharedPreferences.getBoolean("check", false);
if(!check){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}

Save the state of a ToggleButton using SharedPreferences

I have seen other similar questions, but none are working out! I have a toggle button. I want to save the state of the ToggleButton (checked true or false) even when the app is closed/reopened.
My code looks like this below, but it will not run
public class MainActivity extends AppCompatActivity {
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void savePreference(Context context)
{
SharedPreferences.Editor editor = context.getSharedPreferences("toggleState1", 0).edit();
editor.putBoolean("toggleState1", toggle1.isChecked());
editor.commit();
}
private void loadPreference (Context context)
{
SharedPreferences prefs = context.getSharedPreferences("toggleState1", 0);
toggle1.setChecked(prefs.getBoolean("toggleState1", false));
}};
Thanks for the help!
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
should be INSIDE onCreate(), make it the last statement.
Also, it's easier to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Alright I have the answer for future reference. My original attempt did not use shared preferences properly. You must create a "key" and a "name" for the shared preference object. Then call it in code as follows:
public class MainActivity extends AppCompatActivity {
private static final String APP_SHARED_PREFERENCE_NAME = "AppSharedPref";
private final static String TOGGLE_STATE_KEY1 = "TB_KEY1";
ToggleButton toggle1;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(APP_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
toggle1 = (ToggleButton) findViewById(R.id.toggle1);
toggle1.setChecked(GetState());
toggle1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
SaveState(isChecked);
}
});
}
private void SaveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(TOGGLE_STATE_KEY1, isChecked);
editor.commit();
}
public boolean GetState() {
return sharedPreferences.getBoolean(TOGGLE_STATE_KEY1, false);
}
}

How save state of preferenceActivity on Android

I'm trying to develop an application that has a PreferenceActivity two CheckBoxPreference and MainActivity . I want that when you selections and some of them go out to MainActivity , saved, and again she selected only see you 've selected first. I tried all things but nothing work. Help me!!
My code:
public class Preferencias extends PreferenceActivity implements OnPreferenceChangeListener{
Boolean bmusica=true,bvibracion=true;
SharedPreferences prefs;
CheckBoxPreference chMusica,chVibr;
SharedPreferences.Editor gg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferencias);
if(savedInstanceState!=null){
chMusica.setChecked(savedInstanceState.getBoolean("estadoMusica"));
bmusica=savedInstanceState.getBoolean("valorMusica");
chVibr.setChecked(savedInstanceState.getBoolean("estadoVibracion"));
bvibracion=savedInstanceState.getBoolean("valorVibr");
}else{
prefs =this.getPreferenceManager().getSharedPreferences();
gg= prefs.edit();
chMusica = (CheckBoxPreference) findPreference("musica");
chVibr = (CheckBoxPreference) findPreference("vibracion");
chMusica.setChecked(true);
chVibr.setChecked(true);
}
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
if(chMusica.isChecked()){
gg.putBoolean("musica", true);
bmusica=true;
}else{
gg.putBoolean("musica", false);
bmusica=false;
}
if(chVibr.isChecked()){
gg.putBoolean("vibracion", true);
bvibracion=true;
}else{
gg.putBoolean("vibracion", false);
bvibracion=false;
}
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("estadoMusica", chMusica.isChecked());
outState.putBoolean("valorMusica", bmusica);
outState.putBoolean("estadoVibracion", chVibr.isChecked());
outState.putBoolean("valorVibr", bvibracion);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
chMusica.setChecked(state.getBoolean("estadoMusica"));
chVibr.setChecked(state.getBoolean("estadoVibracion"));
bmusica=state.getBoolean("valorMusica");
bvibracion=state.getBoolean("valorVibr");
}
And my MainActivity:
public class MainActivity extends Activity {
Button jugar, preferencias, acercade, maximo, salir;
Vibrator v;
Boolean isVibrar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_land);
v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
jugar = (Button) findViewById(R.id.botonJugar);
preferencias = (Button) findViewById(R.id.botonOpciones);
acercade = (Button) findViewById(R.id.botonAcercaDe);
maximo = (Button) findViewById(R.id.botonPuntuaciones);
salir = (Button) findViewById(R.id.botonSalir);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
isVibrar = sharedPref.getBoolean("vibracion", true);
public void preferencias(View view) {
if (isVibrar==true) {
v.vibrate(200);
}
Intent i = new Intent(MainActivity.this, Preferencias.class);
startActivity(i);
}

Pass value from activity to CustomDialog class

Hi i want to pass a value "username" which i saved through SharedPreferences in my activity to a EditText in a CustomDialog class.
Meaning i want to use EditText.settext (username) in my CustomDialog class.
Can somebody help me to achieve this?
Thank you.
SharedPreference code in Main activity:
public class AndroidLogin extends Activity implements OnClickListener {
public SharedPreferences mPrefs;
...
#Override
protected void onPause() {
super.onPause();
Editor e = mPrefs.edit();
e.putString(USERNM, username);
e.commit();
}
}
Now i want to set the value "USERNM" to the EditText in my CustomDialog class:
public class MyCustomForm extends Dialog {
public SharedPreferences mPrefs;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
EditText userTest = (EditText)findViewById(R.id.txtUserName);
mPrefs = getSharedPreferences("PREFS_NAME", this.MODE_PRIVATE); // does not work
String text = mPrefs.getString("USERNM", "");
userTest.setText(text);
}
}
CustomDialog:
import android.app.Dialog;
...
public class MyCustomForm extends Dialog {
String mTextChange;
public SharedPreferences mPrefs;
public interface ReadyListener {
public void ready(String user, String pass, boolean save);
}
private String usernm;
private String passwd;
private ReadyListener readyListener;
public MyCustomForm(Context context, String user, String pass, ReadyListener readyListener) {
super(context);
this.usernm = user;
this.passwd = pass;
this.readyListener = readyListener;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
setTitle("Login:");
EditText userTest = (EditText)findViewById(R.id.txtUserName);
//mPrefs = getSharedPreferences("PREFS_NAME", this.MODE_PRIVATE);
//String text = mPrefs.getString("USERNM", "");
userTest.setText();
Button buttonConfrim = (Button) findViewById(R.id.btnConfirm);
buttonConfrim.setOnClickListener(new OKListener());
Button buttonCancel = (Button) findViewById(R.id.btnCancel);
buttonCancel.setOnClickListener(new CancelListener());
}
private class OKListener implements android.view.View.OnClickListener {
public void onClick(View v) {
EditText user = (EditText) findViewById(R.id.txtUserName);
EditText pass = (EditText) findViewById(R.id.txtpass);
CheckBox saveuser = (CheckBox) findViewById(R.id.saveuser);
readyListener.ready(user.getText().toString(),pass.getText().toString(), saveuser.isChecked());
MyCustomForm.this.dismiss();
}
}
private class CancelListener implements android.view.View.OnClickListener {
public void onClick(View v) {
MyCustomForm.this.dismiss();
}
}
}
Edit, in my main activity:
public void createDialog(Context context) {
SharedPreferences prefs = context.getSharedPreferences("mPrefs", Context.MODE_PRIVATE);
String user = prefs.getString("USERNM", "");
new MyCustomForm(context, user, user, null); // where the class that is calling this is aa OnTextChangeListener
}
This is how i show the Dialog:
public void getLoginData() throws Exception {
if (checkInternetConnection() == true){
MyCustomForm dialog = new MyCustomForm (this, "", "", new OnReadyListener());
dialog.setContentView(R.layout.inlogdialog);
dialog.show();
}
It's not recommended to pass context around (and by extension views). I would suggest creating a listener for your dialog, maybe something like an OnTextChangedListener#onChange(String).
Create the listener in your activity and pass it to your dialog. Then when the dialog is done, call the listeners onChange(String) method which will be set to fire an event to a UI thread handler to update the edit text. Conversely, you could just pass the handler.
public class MyDialog exteds Dialog implements Dialog.OnClickListener {
OnTextChangeListener mListener;
String mTextChange;
public MyDialog(OnTextChangeListener listener) {
mListener = listener;
// set up your stuff
setOnClickListener(this);
}
...
public void onClick(DialogInterface dialog) {
// Do what ever you need to do to get set mTextChange
mListener.onChange(mTextChange);
}
public static interface OnTextChangeListener {
void onChange(String textChange);
}
Here is how you pass it:
public void createDialog(Context context) {
SharedPreferences prefs = context.getSharedPreferences("MyPreferencesName", Context.MODE_PRIVATE);
String user = prefs.getString("what_ever_string_you_want", "fall_back_user_name");
new MyDialog(user, this); // where the class that is calling this is aa OnTextChangeListener
}

Categories

Resources