SharedPreferences not working across Activities - java

I'm trying to save some filters/state in one activity, and then use that data in the next activity.
I'm using SharedPreferences, but it isn't working as I'd expected it to.
public class FilterActivity extends Activity {
private static final String TAG = FilterActivity.class.getName();
EditText distanceEditor;
#Override
public void onPause() {
super.onPause();
SharedPreferences preferences = getSharedPreferences(PreferenceKey.FILTER_PREFERENCES_NAME, MODE_WORLD_READABLE);
String distance = distanceEditor.getText().toString();
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
Log.i(TAG, "Wrote max-distance=" + distance);
Log.i(TAG, "Preferences contains distance=" + preferences.getString(PreferenceKey.DISTANCE, "FAIL"));
}
public static class PreferenceKey {
public static final String FILTER_PREFERENCES_NAME = "FilterActivity:" + "Filter_Preference_File";
public static final String DISTANCE = "FilterActivity:" + "DISTANCE";
}
}
Then, the Activity that should use this preference:
public class MapActivity extends MapActivity {
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getSharedPreferences(FilterActivity.PreferenceKey.FILTER_PREFERENCES_NAME, MODE_WORLD_READABLE);
String maxDistance = preferences.getString(FilterActivity.PreferenceKey.DISTANCE, "FAIL");
Log.i(TAG, "Read max-distance=" + maxDistance);
}
}
But the output I get is:
.FilterActivity( 4847): Wrote max-distance=99.9
.FilterActivity( 4847): Preferences contains distance=FAIL
.MapActivity( 4847): Read max-distance=FAIL
Can anyone tell me what I'm doing wrong here?
I am developing against API Level-8.

In the following two lines,
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
two different SharedPreferences.Editors are being returned. Hence the value is not being committed. Instead, you have to use:
SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();

Related

How to receive data from one activity to another - android

I'm trying to send an integer from one activity to another in Android studio. In my source class I have sent the data using putExtra() and in the recipient class, I am trying to receive it using getIntent(). However, I get the error 'Could not resolve method 'getIntent()' in the recipient class. Here is my code:
I'm a total newbie to Android studio as well as Java so if I'm missing something really obvious, please be considerate.
Source Activity:
public class AugmentedImageActivity extends AppCompatActivity {
private ArFragment arFragment;
private ImageView fitToScanView;
// Augmented image and its associated center pose anchor, keyed by the augmented image in
// the database.
private final Map<AugmentedImage, AugmentedImageNode> augmentedImageMap = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);
fitToScanView = findViewById(R.id.image_view_fit_to_scan);
arFragment.getArSceneView().getScene().addOnUpdateListener(this::onUpdateFrame);
}
#Override
protected void onResume() {
super.onResume();
if (augmentedImageMap.isEmpty()) {
fitToScanView.setVisibility(View.VISIBLE);
}
}
/**
* Registered with the Sceneform Scene object, this method is called at the start of each frame.
*
* #param frameTime - time since last frame.
*/
private void onUpdateFrame(FrameTime frameTime) {
Frame frame = arFragment.getArSceneView().getArFrame();
// If there is no frame or ARCore is not tracking yet, just return.
if (frame == null || frame.getCamera().getTrackingState() != TrackingState.TRACKING) {
return;
}
Collection<AugmentedImage> updatedAugmentedImages =
frame.getUpdatedTrackables(AugmentedImage.class);
for (AugmentedImage augmentedImage : updatedAugmentedImages) {
switch (augmentedImage.getTrackingState()) {
case PAUSED:
// When an image is in PAUSED state, but the camera is not PAUSED, it has been detected,
// but not yet tracked.
int value=augmentedImage.getIndex();
Intent i = new Intent(AugmentedImageActivity.this, AugmentedImageNode.class);
i.putExtra("key",value);
startActivity(i);
String text = "Detected Image " + augmentedImage.getIndex();
SnackbarHelper.getInstance().showMessage(this, text);
break;
case TRACKING:
// Have to switch to UI Thread to update View.
fitToScanView.setVisibility(View.GONE);
// Create a new anchor for newly found images.
if (!augmentedImageMap.containsKey(augmentedImage)) {
AugmentedImageNode node = new AugmentedImageNode(this);
node.setImage(augmentedImage);
augmentedImageMap.put(augmentedImage, node);
arFragment.getArSceneView().getScene().addChild(node);
}
break;
case STOPPED:
augmentedImageMap.remove(augmentedImage);
break;
}
}
}
}
Recipient activity:
public class AugmentedImageNode extends AnchorNode {
private static final String TAG = "AugmentedImageNode";
// The augmented image represented by this node.
private AugmentedImage image;
private static CompletableFuture<ModelRenderable> ulCorner;
public AugmentedImageNode(Context context) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
int value = extras.getInt("key");
if (value == 0) {
// Upon construction, start loading the models for the corners of the frame.
if (ulCorner == null) {
ulCorner =
ModelRenderable.builder()
.setSource(context, Uri.parse("models/tinker.sfb"))
//.setSource(context, Uri.parse("models/borderfence-small2.sfb"))
.build();
}
}
}
#SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"})
public void setImage(AugmentedImage image) {
this.image = image;
// If any of the models are not loaded, then recurse when all are loaded.
if (!ulCorner.isDone())// || !urCorner.isDone() || !llCorner.isDone() || !lrCorner.isDone())
{
CompletableFuture.allOf(ulCorner)//, urCorner, llCorner, lrCorner)
.thenAccept((Void aVoid) -> setImage(image))
.exceptionally(
throwable -> {
Log.e(TAG, "Exception loading", throwable);
return null;
});
}
// Set the anchor based on the center of the image.
setAnchor(image.createAnchor(image.getCenterPose()));
// Make the 4 corner nodes.
Vector3 localPosition = new Vector3();
Node cornerNode;
localPosition.set(-0.0f * image.getExtentX(), 0.1f, +0.5f * image.getExtentZ());
cornerNode = new Node();
cornerNode.setParent(this);
cornerNode.setLocalPosition(localPosition);
cornerNode.setLocalRotation(Quaternion.axisAngle(new Vector3(-1f, 0, 0), 90f));
cornerNode.setRenderable(ulCorner.getNow(null));
}
private void setLocalRotation() {
}
public AugmentedImage getImage() {
return image;
}
}
getIntent() method are only available in class which extends the activity[directly or indirectly]
Here is code how to use share preference in your scenario.I hope it will help you.
Instead of below code
Intent i = new Intent(AugmentedImageActivity.this, AugmentedImageNode.class);
i.putExtra("key",value);
startActivity(i);
Use this one
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putInt("Key", "int value");
editor.commit();
And retrieve preference value on your AugmentedImageNode screen using below code
SharedPreferences settings = getSharedPreferences("MyPref", MODE_PRIVATE);
int snowDensity = settings.getInt("Key", 0); //0 is the default value
remove the first three lines of your AugmentedImageNode(Context context) in recipient activity and replace it with following
int value = getIntent().getIntExtra("key",0);
where 0 is just default value.
getintent is working if you are extent Activity and AppCompatActivity
for example:
MainActivity.java
choice_a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
//putExtra(key name,default value);
intent.putExtra("int_key",22);
startActivity(intent);
}
});
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//get intent values
Intent intent = getIntent();
Bundle extras = intent.getExtras();
int value = extras.getInt("int_key");
Log.e("Int_Value", "" + value);
// another way
int i = getIntent().getIntExtra("int_key", 0);
Log.e("Int_Value", "" + i);
}
}
In your code you have extend AnchorNode

Using a global Variable inside a class

I'm using android studio for a project api 21 minimum,
I have an activity with a textfield and a button, when click, I want the text of the textfield stored for the life of the application, I'm using a global variable for that.
I've got a class variable that extends Application:
package com.example.user.variableglobale;
import android.app.Application;
public class Variable extends Application {
private String chiffre;
public String getChiffre() {
return this.chiffre;
}
public void setChiffre(String chiffre) {
this.chiffre = chiffre;
}
inside my main :
final Variable VG = (Variable) getApplication();
final TestVar tV = new TestVar();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tV.testVar(MainActivity.this);
VG.setChiffre(String.valueOf(txt.getText()));
}
});
and here is the java class called with the button:
public class TestVar {
public void testVar(Context context) {
Variable VG = (Variable) context.getApplicationContext();
String temp = VG.getChiffre();
Toast.makeText(context.getApplicationContext(), "test java VG " + temp, Toast.LENGTH_SHORT).show();
}
}
Can anyone explain the way to use global variable inside java class?
When I click on the button, a toast appears with a "null" value for "temp" (seem to be not initialized).
In my example, I tried with "context", to no avail.
ok, finally it work,
inside my onclickListener i have to swap declaration of variable and calling of my class... everything ok
I think a better way to store that variable would be to store it in shared preferences. You can access it in any activity and it persists even if app is closed.
You can use it withoud needing a class for variable like this.
main:
static final String CHIFFRE_KEY = "chiffre_key";
final TestVar tV = new TestVar();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(CHIFFRE_KEY, String.valueOf(txt.getText()));
editor.commit();
tV.testVar(MainActivity.this);
}
});
and testVar method would look like this
public void testVar(Context context) {
String vg = getActivity().getPreferences(Context.MODE_PRIVATE).getString(CHIFFRE_KEY);
Toast.makeText(context.getApplicationContext(), "test java VG " + vg, Toast.LENGTH_SHORT).show();
}
You can read more about Shared Preferences here

Save variable in SharedPreferences based on which button is clicked

Im trying to make an EULA for my app, but there is a different EULA for the different countries we work with.
my idea was that i save a String in SharedPreferences like ZA for South Africa and KE for Kenya. So if you click the South Africa button, it will save the string in SharedPreferences as ZA and the same for Kenya. Once the button has been clicked it the new activity will then load the appropriate EULA by pulling the ZA or KE string from the SharedPreferences. This is what i have at the moment:
Country_select.java
public class country_select extends Activity {
private static final String TAG = "Logs";
public static final String PREFS_NAME = "PrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_select);
final Button za_button = (Button) findViewById(R.id.btn_za);
Button ke_button = (Button) findViewById(R.id.btn_ke);
Log.i(TAG, "created buttons");
za_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "ZA");
editor.commit();
}
});
Log.i(TAG, "set button settings for ZA");
ke_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "KE");
editor.commit();
}
});
Log.i(TAG, "set button settings for KE");
}
I may have this totally incorrect but on the layout file there are 2 buttons, one for KE and one for ZA.
I would like it, when the new activity is loaded to read SharedPreferences whether it has ZA or KE? Is what i have done here correct?
Thank you
I think you're better off with using IntentExtras, in your first activity upon clicking the country button store the value inside a variable and when you want to start the new activity pass the data as an intent extra:
Intent intent= new Intent(getActivity(), NewActivity.class);
intent.putExtra("country", countryCode);
startActivity(intent);
And then inside the new activity you can retrieve the value like this:
String countryCode = getIntent().getExtras().getString("country");
In order to maintain Shared preference across the application i use it this way
, take a look
I saved a AppPrefes class as a seprate class in the package
public class AppPrefes {
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPrefes(Context context, String Preferncename) {
this.appSharedPrefs = context.getSharedPreferences(Preferncename,
Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
/****
*
* getdata() get the value from the preference
*
* */
public String getData(String key) {
return appSharedPrefs.getString(key, "");
}
public Integer getIntData(String key) {
return appSharedPrefs.getInt(key, 0);
}
/****
*
* SaveData() save the value to the preference
*
* */
public void SaveData(String Tag, String text) {
prefsEditor.putString(Tag, text);
prefsEditor.commit();
}
public void SaveIntData(String key, int value) {
prefsEditor.putInt(key, value);
prefsEditor.commit();
}
/**
* delete all AppPreference
*/
public void deleteAll() {
this.prefsEditor = appSharedPrefs.edit();
this.prefsEditor.clear();
this.prefsEditor.commit();
}
In your Activity or Fragment were you would like to get or save data just use it like this
Decalre an object for the AppPrefes class
AppPrefes appPref;
Initialize in onCreate
appPref = new AppPrefes(getActivity(), "type name of your preference");
To save data to the preference use
appPref.SaveData("tag_name", "value to be saved);
To get data from the preference
appPref.getData("tag_name");
You can also save Integer values and clear all preference values if necessary just call the apporopriate methods.
Yes, the storing part is correct. Now you will need to access the stored value in your new activity.
Example-
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String storedCountry = sharedpreferences.getString("Country_Selected"); // could be null value if there is no value stored with Country_Selected tag.

Retrieving SharedPreferences in Android

I'm building my first multi-activity app. I have some geographic coordinates in Activity1 that are defined by the user and are saved to SharedPreferences:
// these strings are used when saving the users' preferred location
private static final String POINT_LATITUDE_KEY = "POINT_LATITUDE_KEY";
private static final String POINT_LONGITUDE_KEY = "POINT_LONGITUDE_KEY";
private static final String TAG = "Activity1";
// actually saves the coordinates to the preferences
private void saveCoordinatesInPreferences(float latitude, float longitude) {
SharedPreferences prefs =
this.getSharedPreferences(getClass().getSimpleName(),
Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putFloat(POINT_LATITUDE_KEY, latitude);
prefsEditor.putFloat(POINT_LONGITUDE_KEY, longitude);
//Log.i(TAG, "latitude is: " + latitude);
//Log.i(TAG, "longitude is: " + longitude);
prefsEditor.commit();
}
These SharedPreferences coordinates then need to be used by Activity2. I'm having trouble retrieving them. Here's a method I have written for retrieval. My variable latitude is not written to the log.
private static final String TAG = "Activity2";
protected void getLatLongPref() {
// adapted from http://mrbool.com/android-shared-preferences-managing-files-using-internal-external-storage/30508
// accessed April 10, 2015
SharedPreferences pref = getApplicationContext().getSharedPreferences("POINT_LATITUDE_KEY", MODE_PRIVATE);
float latitudeUser = pref.getFloat("POINT_LATITUDE_KEY", 0); // getting users chosen latitude
Log.i(TAG, "latitude is: " + latitudeUser);
}
What do you think I'm doing wrong ?
You have used wrong context and preference name for both sharedpreferences. Change the first one to this:
SharedPreferences prefs = getApplicationContext().getSharedPreferences("POINT_LATITUDE_KEY",
Context.MODE_PRIVATE);
Change your first code snippet like this:
private void saveCoordinatesInPreferences(float latitude, float longitude) {
SharedPreferences prefs =
this.getSharedPreferences("myPref", Context.MODE_PRIVATE);
[...]
}
...And your second one like this:
protected void getLatLongPref() {
SharedPreferences pref =
this.getSharedPreferences("myPref", Context.MODE_PRIVATE);
[...]
}
Basically, It has to be the same in both cases. See this also.

onSharedPreferenceChanged isn't called everytime a preference has been changed

I have a problem with onSharedPreferenceChanged is only called the first time when a MultiSelectListPreference has changed. I open my settings activity and change the value which works fine and onSharedPreferenceChanged is getting called. If I open the dialog again, it shows the correct entries selected. I select another entry and hit OK. onSharedPreferenceChanged should now getting called but isn't. If I now open the dialog again, no entries are selected. Am I missing something or did I do somethign wrong?
Here's my preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<MultiSelectListPreference
android:key="operations"
android:title="#string/pref_operations"
android:dialogTitle="#string/pref_operations"
android:entries="#array/pref_operations_entries"
android:entryValues="#array/pref_operations_values"
android:defaultValue="#array/pref_operations_default" />
</PreferenceScreen>
And my settings fragment
public class SettingsFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener
{
public static final String KEY_OPERATIONS_PREFERENCE = "operations";
private MultiSelectListPreference operationsPreference;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
operationsPreference = (MultiSelectListPreference) getPreferenceScreen().findPreference(KEY_OPERATIONS_PREFERENCE);
}
#Override
public void onResume()
{
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
Set<String> operations = operationsPreference.getValues();
String summary = "";
for (String s : operations)
summary += s + " ";
operationsPreference.setSummary(summary);
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause()
{
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(KEY_OPERATIONS_PREFERENCE))
{
Set<String> operations = operationsPreference.getValues();
String summary = "";
for (String s : operations)
summary += s + " ";
operationsPreference.setSummary(summary);
}
}
}
Umm frankly I built my sharedPreferances differently...ill attach my code example and hopefully it'll be of use to you
here goes:
this is the sharedpreferences class
public class AppPreferences {
public static final String KEY_LANG = "language";
final String APP_SHARED_PREFS = AppPreferences.class.getSimpleName(); // Name
// of
// the
// file
// -.xml
private SharedPreferences _sharedPrefs;
private Editor _prefsEditor;
public AppPreferences(Context context) {
this._sharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS,
Activity.MODE_PRIVATE);
this._prefsEditor = _sharedPrefs.edit();
}
public String getlanguage() {
return _sharedPrefs.getString(KEY_LANG, "");
}
public void savelanguage(String text) {
_prefsEditor.putString(KEY_LANG, text);
_prefsEditor.commit();
}
}
to use it youll need to create
in your class
private AppPreferences _appPrefs;
and an example for use is
_appPrefs = new AppPreferences(getApplicationContext());
_appPrefs.savelanguage("English");
language = _appPrefs.getlanguage();
this is how i built it... works like a charm... and not complicated at all
It's because you unregister the listener in your onPause callback method which is invoked when Dialog is shown in an Activity.

Categories