Attempt to invoke virtual method 'Context.getSharedPreferences()' on a null object reference - java

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();

Related

SharedPreferences always returning default value for custom object

I am making a simple budget tracking app. I have a Budget class that stores a few variables: the amount, duration, and initial value of budget. I only have one global Budget object inside the fragment, called "budget", and am trying to get it to save. It seems to save fine, but when I try to retrieve it, it returns the default value for some reason. Here are my methods for saving and loading. I only call getBudget() in onCreateView, and only call saveBudget in onResume() and after the budget is edited. Note the log entries.
public void saveBudget(){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
Gson gson = new Gson();
String json = gson.toJson(budget);
Log.d("BTAG", "JSON: " + json);
editor.putString("current budget", json);
editor.commit();
}
public Budget getBudget(){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPref.getString("current budget", null);
Log.d("BTAG", "gson from json: " + gson.fromJson(json, Budget.class));
return gson.fromJson(json, Budget.class);
}
My log says this for my current instance of Budget:
D/BTAG: JSON: {"amount":35.92,"frequency":"monthly","originalAmount":35.92}
D/BTAG: gson from json: null
This shows that it saves without issue, but loading doesn't work. Why is getBudget() not working?
I think the problem might be in:
only call saveBudget in onResume()
You have to save the budget when the app is closing not in onResume(). Check this Android Activity Lifecycle.
Also, I think You shouldn't use hardcoded strings as key. Try to use string resources as in Android docs. If You make a mistake in 'key' You will get the default value.
If You save budget and then load it in another activity the problem might be in getting SharedPreferences instance. To get SharedPreferences use:
SharedPreferences sP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences from different activity
You can try this, I hope this will compile:
public static final String SHARED_PREFS = "NAME_OF_SP";
public static final String NAME_OF_VAL = "budget";
public void saveBudget()
{
SharedPreferences sharedPref = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
Gson gson = new Gson();
String json = gson.toJson(budget);
Log.d("BTAG", "JSON: " + json);
editor.putString(NAME_OF_VAL, json);
editor.apply();
}
public Budget getBudget()
{
SharedPreferences sharedPref = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPref.getString(NAME_OF_VAL, null);
Log.d("BTAG", "gson from json: " + gson.fromJson(json, Budget.class));
return gson.fromJson(json, Budget.class);
}

I am expecting my boolean to be saved in shared preferences as true, however it always saves as false

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();

Can't access SharedPreferences in class that extend Application

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.

unable to find data in sharedpreferences

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");

Android change a stored SharedPreferences value?

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.

Categories

Resources