I have an activity which needs to modify the SharedPreferences.
public class AddingEmail extends ListActivity implements OnClickListener{
private String newMail;
private SharedPreferences prefs;
private PreferenceManager prefMan;
private EditText emailAdd;
private EditText emailDel;
private ArrayList<String> prefList;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.addingemail);
Log.d("On Addig EMAIL ACTIVITY","on Create");
String name = "com.example.daemon3_preferences";
prefs = this.getSharedPreferences(name, MODE_PRIVATE);
And this is the PreferenceScreen..
public class PreferencesScreen extends PreferenceFragment{
private final String TAG = "PreferencesScreen";
private Set<String> emails;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate");
addPreferencesFromResource(R.xml.prefs);
And I have this error:
java.lang.IllegalArgumentException: File /data/data/com.example.daemon3/shared_prefs/com.example.daemon3_preferences.xml.xml contains a path separator
Why it takes .xml.xml instead of .xml?
Breaking out the comment thread into a formal answer here.
Instead of calling
String name = "com.example.daemon3_preferences";
prefs = this.getSharedPreferences(name, MODE_PRIVATE);
call this:
prefs = PreferenceManager.getDefaultSharedPreferences(this);
PreferenceFragment saves your settings with the PreferenceManager so by attempting to open the default preferences with getSharedPreferences, you might be interfering with the PreferenceManager which could be causing that particular exception.
Related
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();
}
}
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
}
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);
}
}
Am making my first android application with the help of Udacity's tutorial(Weather App).
For setting activity, I have one text box,which holds the location value.
For example say, Texas.
But when am changing that to any other value,it's not reflecting the same in the app. Though,the value in that text box is getting changed.
In the app's SettingActivity I have following code,
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
But as of today addPreferencesFromResource is deprecated,so am not really sure how to proceed in this regard. What do I change it with?
My goal is to change the value in Location's text and when I go on my mainActivity,the weather data should reflect the changed location's data.
Thanks.
Edit:
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
private void updateWeather()
{
FetchWeatherTask weatherTask = new FetchWeatherTask();
SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(getActivity());
String location=prefs.getString(getString(R.string.pref_location_key),getString(R.string.pref_location_default));
weatherTask.execute(location);
}
#Override
public void onStart()
{
super.onStart();
updateWeather();
}
Above is the code through which I update the value.
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
setupActionBar();
}
Above is the code from settingActivity. But as I said, addPreferencesFromResource is deprecated. So this part of code is not really working.
Create a separate class as below to handle all the prefs related operations, storing and restoring...
public class MyPrefs {
Context context;
SharedPreferences systemPrefs;
SharedPreferences.Editor editor;
static MyPrefs prefs;
public static final String DEFAULT_LOCATION = "DEFAULT_LOCATION";
public static final String SOME_DEFAULT_LOCATION = "London";
public static MyPrefs getInstance(Context context){
if(prefs == null){
prefs = new MyPrefs(context);
}
return prefs;
}
private MyPrefs(Context context) {
this.context = context;
this.systemPrefs = context.getSharedPreferences(Constants.USER_PREFS, Activity.MODE_PRIVATE);
this.editor = systemPrefs.edit();
}
public String getDefaultLocation(){
return systemPrefs.getString(DEFAULT_LOCATION, SOME_DEFAULT_LOCATION);
}
public void setDefaultLocation(String newLocation){
editor.putString(DEFAULT_LOCATION, newLocation);
editor.commit();
}
public void clear() {
editor.clear();
editor.commit();
}
}
And to use this in any activity class...
MyPrefs myPrefs = MyPrefs.getInstance(this);
//To get the location stored in prefs
String locationFromPrefs = myPrefs.getDefaultLocation();
//To store the location in prefs
myPrefs.setDefaultLocation("New York");
public class WordDisplay extends Activity {
private int level;
private int group;
private int set;
private WordDisplay mContext=this;
private int l;
private int g;
private int s;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wordset);
set_Word_Display_Event();
loadPreferences();
}
protected void loadPreferences() {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
l= preferences.getInt("Level", 0);
g=preferences.getInt("Group", 0);
s= preferences.getInt("Set", 0);
// Log.d("lll"," - "+preferences.getInt("level",0));
}
#Override
protected void onStop() {
super.onStop();
savePreferences(this.level,this.group,this.set);
}
protected void savePreferences(int level, int group, int set) {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
//preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("Level", l);
editor.putInt("Group", g);
editor.putInt("Set", s);
editor.commit();
//return getPreferences(s).getInt("Set", 0);
}
}
Here, my data could not persist properly. what is the wrong my code. please give good convenience.
Comments of the above code, Also checking but could not any effect.
First, onStop() "might" never be called (see Activity life cycle), practice is to save your data in the onPause() method.
Maybe try to add more logs to see what's going on?
is onStop() called?
what are the saved / loaded values?
etc.
Try it with a final string constant in your class:
public static final String PREFS_NAME = "MyPreferences";
and then always use the member function:
getSharedPreferences(PREFS_NAME, 0);
normally there is no magic to do.
http://developer.android.com/guide/topics/data/data-storage.html#pref