I'm trying to code global method by extending the Application class.
Specifically I'm trying to add 2 method to rapidly access one value that is stored in the SharedPreferences.
Unfortunately I can't make the SharedPreferences work, here is the code:
package postfixcalculator.mattiarubini.com.postfixcalculator;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
public class PostfixCalculatorExtendApplication extends Application {
public void ChangePreference (boolean flag){
//I'm updating the preference file based on the purchase
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(getString(R.string.purchase_status), flag);
editor.commit();
}
public boolean RetrievePreferences (){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
/*If the file doesn't exist, I create the file and I'm returned with a false value.
* Because if the file was not created it's likely to be the first install.
* If the user acquired the product on the store, it will be able to restore its purchase.*/
boolean flagPurchase = sharedPref.getBoolean(getString(R.string.purchase_status), false);
return flagPurchase;
}
}
I understand that getActivity() doesn't work in an Activity but in a Fragment, I just don't know what to do in this specific case.
Usually in the Activity, to make SharedPreferences works, I just need to use the key word this.
These are the errors I get:
Cannot resolve method 'getActivity()'
Cannot resolve method 'getPreferences(int)'
try getApplicationContext() with getSharedPreferences()
Use
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences .edit();
editor.putBoolean(getString(R.string.purchase_status), flag);
editor.commit();
I use getSharedPreferences("Name of preferences", Context.MODE_PRIVATE); in my Application class.
Try using getApplicationContext() instead of getActivity().
Try this for saving shared Preferences:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit().putString("key","value").apply();
For getting shared preferences value:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.getString("key","");
I hope this will help.
Related
I try to access my sharedpreference from a fragment in my app like this:
SharedPreferences sp_app_prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), MODE_PRIVATE);
String path = sp_app_prefs.getString("path", "");
but I am getting a NullPointerException:
Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
I really don't understand why, it doesn't make sense to me.
Calling this sharedpreference from an activity works totaly fine.
What am I missing?
Here is the full string method:
public String getFilePath(int i) {
File filePath;
SharedPreferences sp_app_prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), MODE_PRIVATE);
String path = sp_app_prefs.getString("path", "");
filePath = new File(path);
}
return String.valueOf(filePath);
}
Hope someone can help me
Although your question is ambiguous.
but i guess you are putting code in onCreateView() method body.
instead you should put your code in onViewCreated() method body.
use following code in onViewCreated() method...
SharedPreferences sharedPreferences = getContext().getSharedPreferences("filename", MODE_PRIVATE);
SharedPreferences.Editor editor= sharedPreferences.edit();
editor.putString("key", "value");
editor.apply();
String text = sharedPreferences.getString("key", null);
Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
I am trying to save a boolean into shared preferences with a value of true but when I log it I keeping seeing it returning a false value. Please see the code below and also bear in mind that this code is within a fragment.
SharedPreferences AppPreferences = getActivity().getSharedPreferences("myPrefs", Activity.MODE_PRIVATE);
boolean propertyManagerLoggedIn = AppPreferences.getBoolean(PROPERTYMANAGER_LOGGEDIN, false);
if(!propertyManagerLoggedIn)
{
SharedPreferences.Editor editor = AppPreferences.edit();
transitionInterface.showDashboardIcons();
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
//boolean vlaue = prefs.getbooleanflag(context, false);
Log.d("tag",""+propertyManagerLoggedIn);
}
else
{
Log.d("tag",""+propertyManagerLoggedIn);
}
and below is the relevant lines of code from my AppPreferences class
public final static String PROPERTYMANAGER_LOGGEDIN = "PROPERTYMANAGER_LOGGEDIN";
public static boolean propertyManagerLoggedn(Context context)
{
TinyDB settings = new TinyDB(context);
return settings.getBoolean(AppPreferences.PROPERTYMANAGER_LOGGEDIN);
}
every time you call edit() a new Editor is being returned to you. Accordingly to the documentation
Create a new Editor for these preferences, through which you can make
modifications to the data in the preferences and atomically commit
those changes back to the SharedPreferences object.
so you can either do
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true).commit();
or
editor.putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
but calling putBoolean on an instance and commit on an other won't probably help
You are calling commit on a different instance.
Basically AppPreferences.edit() will give you a new instance.
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
This is another instance in which you are putting the boolean value.
Use the same instance which you have created.
Your code should look like this:
SharedPreferences.Editor editor = AppPreferences.edit();
transitionInterface.showDashboardIcons();
editor.putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
Here's what I have done.
public void addToFavorites2(View view) {
//ImageButton button = (ImageButton)findViewById(R.id.imageButton);
//button.setImageResource(R.mipmap.star_clicked_button);
int movieId = favoriteMovieId;
SharedPreferences settings = getSharedPreferences("FavoritesIdKey", MODE_PRIVATE);
Log.v("tessssst", String.valueOf(settings.contains(favoriteMovieTitle)));
SharedPreferences.Editor editor = settings.edit();
editor.putString(favoriteMovieTitle, String.valueOf(movieId));
editor.commit();
}
public boolean movieIsInFavorites()
{
Log.v("method check","is working");
SharedPreferences settings = getSharedPreferences("FavoritesIdKey", MODE_PRIVATE);
Log.v("tezzzzzt", String.valueOf(settings.contains(favoriteMovieTitle)));
if(settings.contains(String.valueOf(favoriteMovieId)))
{
Log.v("truth test","true");
return true;
}
Log.v("truth test","false");
return false;
}
In the given code I have created two methods. in the first method when I call
SharedPreferences settings = getSharedPreferences("FavoritesIdKey", MODE_PRIVATE);
settings.contains(FavoriteMovieTitle);
the data is found and returns true.
when I call the same
SharedPreferences settings = getSharedPreferences("FavoritesIdKey", MODE_PRIVATE);
settings.contains(FavoriteMovieTitle);
In the second method, it does not return true. is there a fundamental thing about shared preferences that I am missing? if more information is needed i apologize. both methods are next to each other without anything between them.
edit- I will add that the first method is called when i press a button on the details screen(details screen is already finished setup and showing).
the second method i was calling in the onCreateView attempting to check if the movie is already in the favorites list apon start up.
The first method is called when you press a button and the second method is called in the onCreateView. So the second method is called before the first method. However, you insert favoriteMovieTitle into xml in the first method so when the second method was called, favoriteMovieTitle had not been in xml and it would return false.
To Store/Obtain shared preferences, use the following method In your activity
SharedPreferences settings = this.getSharedPreferences("FavoritesIdKey",
Context.MODE_PRIVATE);
To store value in SharedPreferences
SharedPreferences.Editor editor = settings.edit();
editor.putString(favoriteMovieTitle, String.valueOf(movieId));
To read SharedPreferences in other class write this line if same class
then no need to write this direct use getString
SharedPreferences settings = this.getSharedPreferences("FavoritesIdKey",
Context.MODE_PRIVATE);
If your are in same class the above line not need to write again.
String myvalueInPref = settings.getString(favoriteMovieTitle, "defaultValue");
I create a shared preferences file at login, but I cannot figure out the code to change the preferences inside of my app.
SharedPreferences.java
public void editHospitalId(String hospital_id) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
Editor editor = prefs.edit();
editor.putString(KEY_HOSPITALID, hospital_id);
editor.commit();
}
I have already initialized a value for KEY_HOSPITALID on login:
SharedPreferences.java
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
// create login session
public void createLoginSession(String name, String hospital_id){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_HOSPITALID, hospital_id);
// commit changes
editor.commit();
I suppose I could delete the value and re-add it? But there has to be a way to overwrite it.
SharedPreferences contain data as key-value pairs, so calling putString(KEY, VALUE) will assign VALUE to the KEY, regardless of if it's already set. In short, it deletes previous entry automatically.
When my application installs and is opened for the first time(when there is an internet connection) i want the phone to download some information from my server and insert it into the database.
if the information does not download fully or download at all, this activity should occur untill it fully downloads?
How would i go about doing this?
Use the preferences
in your Activity :
private boolean isFirstLaunch() {
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean isFirstLaunch = settings.getBoolean("isFirstLaunch", true);
Log.i(TAG + ".isFirstLaunch", "sharedPreferences ");
return isFirstLaunch;
}
and from the onCreate call
if (isFirstLaunch()) {
Intent firstLaunchIntent = new Intent(this,
GetStartedActivity.class);
firstLaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(firstLaunchIntent);
// set the bool to false in next activity !
finish();
}
Add a flag in your database, shared preferences or a file that indicates that you've downloaded the data. In onResume, check that flag and whether the device has connectivity. If the flag is false and you have connectivity, attempt to download the data.
If that was successful, update the flag.
Use SharedPreference for this. Create a boolean variable and change it once your operation is complete. In onCreate of your Main/Launcher activity check for this variable and perform operation accordingly. Some psuedo-code.
if (!sharedpreferences.getBoolean("isOpComplete", false)) {
// perform my operation
performOperation();
}
performOperation() {
// Operation complete
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("isOpComplete", true);
editor.commit();
}