I'm writing a simple photo gallery app. I want people to scroll through the images and have the ability to add them to a 'favorites' list.
I have constructed a Favorite class that's global (put the class in a cGlobal class that defines it as static).
Now I have this working and I want to be able to save the state of the favorite -- the idea is as follows:
When the app first starts up, it will load the favorites list from the preferences in the main activity.
In the gallery activity it will save the favorite state in the preferences.
It seems like when I load the preferences form the main activity it comes up as null. But I can read what I write to it in the gallery activity. I have the following test code:
In main Activity, when the app starts:
//////////////////////////////////////////////////////////////////////////////////
public class MainActivity extends cBaseView implements OnClickListener {
/** Called when the activity is first created. */
String tr;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// load in favrets from prefences
SharedPreferences pre=getPreferences(MODE_PRIVATE);
// This does not work and tr is equal to no value.
tr=pre.getString("label","no value");
// add listeners
///////////////////////////////////////////////////////////////////////////////
Gallery Activity
public void onCreate(Bundle savedInstanceState) {
// test code
SharedPreferences pre=getPreferences(MODE_PRIVATE);
pre.edit().putString("label","ted").commit();
// tr is set to ted, got the data
tr=pre.getString("label","no value");
}
When you use getPreferences, here is what you get, according to the javadoc of activity :
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity. This simply calls the underlying
getSharedPreferences(String, int) method by passing in this activity's
class name as the preferences name.
You should getSharedPreferences with the same name, to get preferences shared by different activities.
Related
I`m trying to pass 3 int values to another class using shared preferences. But the issue is that only first value gets added the remaining two values only default values are shown.
The shared prefs editor is committed;
The main function is fragment activity,the second one is fragment
This getsharedprefs is used to access the shared preferences from fragment
here is my code
{
SharedPreferences sharedPreferences;
SharedPreferences.Editor sharedPrefsEditor;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help_images);
sharedPreferences=getSharedPreferences("values",MODE_PRIVATE);
sharedPrefsEditor=sharedPreferences.edit();
sharedPrefsEditor.putInt("length",length);
sharedPrefsEditor.putInt("response1",intentResponse1);
sharedPrefsEditor.putInt("response2",intentResponse2);
sharedPrefsEditor.commit();
}
this is my second class
{
sharedPreferences=this.getActivity().getSharedPreferences("values",
Context.MODE_PRIVATE);
length=sharedPreferences.getInt("length",-1);
intentResponse1=sharedPreferences.getInt("response1",0);
intentResponse1=sharedPreferences.getInt("response2",-1);
}
all the variables are declared properly,
this is my first question in stack overflow, so kindly bear any mistakes i made
I'm getting a compiler error cannot resolve method findPreference when I try to intialize an OnSharedPreferencesChanged listener in my MainActivity. According to the answer here:
findPreference() should be called from a class implementing PreferenceActivity interface
but I don't understand what the code to do this would be. How can I get rid of the compiler error and successfully set listeners for preference changes?
MainActivity.java
public class MainActivity extends FragmentActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
//Test preference menu
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_wood")) {
Preference woodPref = findPreference(key); //COMPILER ERROR HERE
MainActivity.getGLSurfaceView().setTexture("");
// Set summary to be the user-description for the selected value
woodPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
}
findPreference is a method which is part of both PreferenceFragment and PreferenceActivity - these are the Fragments/Activities that actually show your Preference screen (the activity is deprecated and you should be using the PreferenceFragment).
You're trying to use it in your MainActivity. This doesn't work because the Preference objects don't actually exist on this screen (they exist in another activity that usually have a PreferenceFragment as part of it). If you need to get access to a preference value of a preference in an activity that is not your preference screen, use SharedPreferences, something like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getBoolean(R.bool.saved_high_score_default);
boolean wood = sharedPref.getBoolean(pref_wood, defaultValue);
You can check out the documentation for further examples.
If your MainActivity is supposed to be a screen that shows settings, then you should probably rename it and include a preference fragment inside of it.
I believe you're also going to run into trouble with setSummary because the Preference is not part of this activity, it's part of the activity where you actually modify the preferences. setSummary is used to update the actual UI of the Preference so that if you, for example, select one of three values when using a list preference, it shows the value you just selected on the screen.
I am new to Android and I am trying to handle the settings according to the instructions in
http://developer.android.com/guide/topics/ui/settings.html
I used the fragment based solution as the one directly in the activity was deprecated:
public class SettingFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingFragment())
.commit();
}
}
The settings are correctly displayed in the app, yet when I try to retrieve their values with:
sharedPref= PreferenceManager.getDefaultSharedPreferences(Dashboard.dashboard);
startDayTime=sharedPref.getString(SettingsActivity.day_switch_start, "");
startNightTime=sharedPref.getString(SettingsActivity.night_switch_start, "");
it complaints that values day_switch_start and night_switch_start might not be resolved. In fact, when I explode the values recognized by SettingActivity, I get a long list of capitalized strings part of the standard settings, but not my own strings.
Those were in fact just entered in the xml file and linked from the SettingFragment, so I doubt context Dashboard.dashboard I passed has any reference to it. Yet there are no instructions on how to pass the settings references to a specific context and moreover they say that the settings should be available from anywhere. I am stuck, any solution?
Thanks,
Please check the reference you linked again, especially the Reading Preferences section. When you set the preference key to, e.g., day_switch_start then you must use the same String when reading the preference, e.g.,
startDayTime=sharedPref.getString("day_switch_start", "");
You can also store the preference key to a constant like in the linked example:
public class SettingsActivity extends PreferenceActivity {
public static final String KEY_PREF_DAY_SWITCH_START = "day_switch_start";
// ...
and then access it when reading the preference:
startDayTime=sharedPref.getString(SettingsActivity.KEY_PREF_DAY_SWITCH_START, "");
Edit: I'm not sure what Dashboard.dashboard should represent but this should work:
sharedPref= PreferenceManager.getDefaultSharedPreferences(this);
I know that I can pass some values between Activities using intent.
However, if I want to pass whole Activity to another Activity I think it is not good approach.
Is there another way to do that?
I have Settings Activity in which I am changing some Colors. So after I come back to my Main Activity I would like to apply those colors. To do this, I need access to MainActivity fields after I change Color value, so inside PreferenceActivity. In other words, I want to have access to Main activity fields from PreferenceActivity class. Any ideas?
You should be using a SharedPreference and then accessing that in your main activity. I recommend you reading up at http://developer.android.com/guide/topics/ui/settings.html because it seems like you are implementing your settings activity incorrectly. The part you might be specifically interested in is the "Read Preferences" section. However, I strongly suggest you read through the whole thing and then implement your settings the proper way.
Updated answer with the 3 different ways (that I can think of):
1) Start your preference activity using startActivityForResult(), then in your onActivityResult() access the SharedPreference and make your necessary changes. See here
2) Register a SharedPreferenceChangeListener with your MainActivity, which will be called when any changes happen to your SharedPreference. See here for a detailed discussion. Also see my initial response.
3) In your MainActivity's onResume(), access the SharedPreference and then make your changes there. I do not like this method because you will be cluttering onResume() with more logic and you will also probably have to have a variable that keeps track of the state of the variable you are interested in.
I would personally go with option 2 because the callback was created for this exact purpose.
I think you could pass the value by using method putExtra(name, value).
And after you start new activity you can get the value you pass before by using method getStringExtra(name).
Shared preferences can be used. If you want your changes to be reflected right away add listener. Refer to SharedPreferences.onSharedPreferenceChangeListener. Its an easy way to do.
If you want to lots of changes required in many activity from you change in any one.
And access last modify data from all Activity and modify also.
for example.
Constants.java
public class Constants
{
public static String name;
}
In your MainActivity you have an editText.
MainActivity.java
public class MainActivity extends Activity {
private EditText yourName;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourName = (EditText) findViewById(R.id.yourName);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Constants.name = yourname.getText().toString();
Intent intent = new Intent(getApplicationContext(),Activity2.class);
startActivity(intent);
}
});
}
In your Activity2 you have an TextView and that getting value which you enter in MainActivity.java without pass in Intent.
Activity2.java
public class Activity2 extends Activity {
private TextView yourName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourName = (TextView) findViewById(R.id.tv_yourName);
// directly use ferom serializable class
yourname.setText(Constants.name);
}
like that you use many values from all activity and modify from all activity.
In my Android application I have to use common string value for all activities. "commonValue" is the common string value that I want to use in all activities. Relevant code of the main activity like this :
public class TestActivity extends Activity {
public String commonValue;//THE COMMON STRING FOR ALL ACTIVITIES
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonValue = "DemoValue";
}
}
In my next activity I created an object of "TestActivity" class and tried to assign "testValue" string to another string named "str"
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testlist);
TestActivity obj = new TestActivity();//OBJECT OF MAIN ACTIVITY
String str = obj.commonValue;
}
but the "str" value in second activity does not equal to the value assigned in my first activity. Why is that & How can I do this?
Thanks!
Put your value in string.xml
<string name="common_value">DemoValue</string>
and use in any activity like this..
String common_value = getApplicationContext().getString(R.string.common_value);
Start using SharedPreferences in your app.
In your first activity you would do
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("commonValue", "DemoValue");
editor.commit();
In your second activity
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String str = settings.getString("commonValue", null);
Try this -
TestActivity.java
public class TestActivity extends Activity {
public static String commonValue;//THE COMMON STRING FOR ALL ACTIVITIES
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonValue = "DemoValue";
}
}
another activity
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.testlist);
String str = TestActivity.commonValue;
}
If the value is always the same you can create a public static final variable and access it via TestActivity.COMMON_VALUE.
If you want to pass around a value between to Activities you should use Intents and add an extra with the value you want to pass.
As Sana has suggested, use SharedPreferences.
Alternatively, use a global constant class. If you want to stick with what you have, then you could try:
String str = TestActivity.this.commonValue;
Your existing code is creating a new instance of the activity, so it's not going to have the value you had set.
To pass data between activities use Bundle. and methods,
intent.putExtra()
and If you want to set data to be global to your app, then create an application class, and save the data there.
We have an Application file for each app you can declare the variable there and as the Application file can get from any activity so using the public getter setter and can get/set that
there are vaious oter metjod you can sue as mention on developer.android http://developer.android.com/resources/faq/framework.html
Singleton class
A public static field/method
A HashMap of WeakReferences to Objects (almost same as my above solution )
Persistent Objects
take a look on them as well
The reason why commonValue doesn't equal what you set in TestActivity onCreate method is because that function hasn't been called yet.
The solution for this is already mentioned by others. Like putting the value in a bundle.