I'm about to write a small app where I have pretty much all the data stored in a custom array which contains of list views. I don't wanna save the data in a different form. This array I like to save in shared preferences. I head a look for other answered questions and tried different ways but none of then worked for me.
In the main activity, I have two small methods:
public class MainActivity extends AppCompatActivity {
public static ArrayList<Item> items = new ArrayList<Item>();
SharedPreferences mPrefs = getBaseContext().getSharedPreferences("KEY12", Context.MODE_PRIVATE);
Gson gson = new Gson();
[...]
protected void savePrefs() {
SharedPreferences.Editor editor = mPrefs.edit();
String json = gson.toJson(items);
System.out.println(json);
editor.putString("items_prefs", json);
editor.commit();
}
protected void loadPrefs() {
String empty_list = gson.toJson(new ArrayList<Item>());
items = gson.fromJson(mPrefs.getString("KEY12", empty_list),
new TypeToken<ArrayList<Item>>() {}.getType());
}
}
I'm calling the loadPrefs(); method in onCreate and savePrefs(); in onResume so everytime when I come back to the main activity, the preferences should be updated.
The error that I get is:
FATAL EXCEPTION: main
Process: com.example.android.calc123, PID: 30579
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.calc123/com.example.android.calc123.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at com.example.android.calc123.MainActivity.(MainActivity.java:61)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
How can I fix this problem or - asking in a different way - what am I doing wrong when dealing with shared preferences?
As the error log say you call getSharedPreferences in a null pointer (getBaseContext)
put in OnCreate mPrefs = getBaseContext().getSharedPreferences("KEY12", Context.MODE_PRIVATE);
Related
Hi this is my first question here, I'm working on a google nearby place app, I'm getting a crash every time I click on the marker place to get the details, and yes I have enabled billing in google developer API
Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.androidnearbyplaces.Model.Result.getFormatted_address()' on a null object reference
at com.example.androidnearbyplaces.ViewPlace$2.onResponse(ViewPlace.java:88)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:81)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$3wC8FyV4pyjrzrYL5U0mlYiviZw.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
This is the ViewPlace.java:88
mService.getDetailPlace(getPlaceDetailUrl(Common.currentResult.getPlace_id())).enqueue(new Callback<PlaceDetail>() {
#Override
public void onResponse(Call<PlaceDetail> call, Response<PlaceDetail> response) {
mPlace = response.body();
place_address.setText(mPlace.getResult().getFormatted_address());
place_name.setText(mPlace.getResult().getName());
}
#Override
public void onFailure(Call<PlaceDetail> call, Throwable t) {
}
});
Quick explanation:
mPlace.getResult() is returning null. NullPointerException is being thrown because you cannot do null.getFormattedAddress(). You cannot call any method on null in Java.
Why does it return null? I cannot tell for sure without seeing more of the code.
Please read more about NullPointerException, maybe in here.
I made nonActivity class, and I use there other nonActivity Database class. When I call method from 1st class I have Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Here is a fragment of my code of both classes:
DataBase.java
public DataBase(Context context) {
super(context, DATABASE_NAME, null, TABLE_VERSION);
}
and ObliczPodatki.java
public class ObliczPodatki extends Application
.
.
.
myDb = new DataBase(this.getApplicationContext());
and the full error message:
Process: com.example.nadgraniav01, PID: 11274
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:116)
at com.example.nadgraniav01.ObliczPodatki.obliczPodatki(ObliczPodatki.java:43)
at com.example.nadgraniav01.DodajNadgranieActivity$2.onClick(DodajNadgranieActivity.java:99)
at android.view.View.performClick(View.java:6669)
at android.view.View.performClickInternal(View.java:6638)
at android.view.View.access$3100(View.java:789)
at android.view.View$PerformClick.run(View.java:26145)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
if I use this instead of this.getApplicationContext() I am getting following erroe
Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
Try this then:
#Override
public void onCreate() {
super.onCreate()
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
....rest of db calls..
}
Use:
myDb = new DataBase(getApplicationContext());
Or,
myDb = new DataBase(Activityname.this);
getApplicationContext is not the context that you should use,
Use this instead
myDb = new DataBase(this);
You have to initialise myDb variable in onCreate() method of ObliczPodatki class.
myDb = new DataBase(getApplicationContext());
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
please I am new to android development.I am working on the flag quiz app on ditel's android 6 for programmers. Although I followed the source code meticulously, I don't seem to be able to run the app successfully, as it crashes almost immediately after coming up. This is the exception I am getting. I would appreciate any help that will solve this problem.
FATAL EXCEPTION: main
Process: com.example.israel.flagquiz, PID: 4644
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.israel.flagquiz/com.example.israel.flagquiz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.israel.flagquiz.MainActivityFragment.updateGuessRows(android.content.SharedPreferences)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.israel.flagquiz.MainActivityFragment.updateGuessRows(android.content.SharedPreferences)' on a null object reference
at com.example.israel.flagquiz.MainActivity.onStart(MainActivity.java:62)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1244)
at android.app.Activity.performStart(Activity.java:6140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
pertinent code in MainActivity
#Override
protected void onStart(){
super.onStart();
if (preferencesChanged){
MainActivityFragment quizFragment = (MainActivityFragment)
getSupportFragmentManager().findFragmentById(R.id.quizFragment);
quizFragment.updateGuessRows(
PreferenceManager.getDefaultSharedPreferences(this));
quizFragment.updateRegions(
PreferenceManager.getDefaultSharedPreferences(this));
quizFragment.resetQuiz();
preferencesChanged = false;
}
pertinent code in Main Activity Fragment
public void updateGuessRows(SharedPreferences sharedPreferences){
String choices = new String();
choices = sharedPreferences.getString(MainActivity.CHOICES, null);
guessRows = Integer.parseInt(choices) / 2;
for (LinearLayout layout: guessLinearLayouts)
layout.setVisibility(View.GONE);
for (int row = 0; row < guessRows; row++)
guessLinearLayouts[row].setVisibility(View.VISIBLE);
}
sharedPreferences is null at this line
choices = sharedPreferences.getString(MainActivity.CHOICES, null);
initialize sharedPreferences in on Start
Add the below line to initialize your shared preferences
If using in an Activity
sharedPreferences = getSharedPreferences("MainActivity", Context.MODE_PRIVATE);
If using in a Fragment
sharedPreferences = getActivity().getSharedPreferences("MainActivity", Context.MODE_PRIVATE);
Once it is initialized, you can read data from shared preferences file.
I'm loading a picture from a url into a bitmap. This code below worked on previous classes that extended Fragment. This time, I'm just copying the code and trying to use it in a class that extends AppCompatActivity. The only difference is how I'm getting context.
public void loadBitmap(String url) {
if (loadtarget == null) loadtarget = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
handleLoadedBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
mContext = MyActivity.this;
Picasso.with(mContext).load(url).into(loadtarget); //giving me null
}
In the original code, where I used it in a Fragment, I had it as
Picasso.with(getActivity()).load(url).into(loadtarget);
So now, since this class extends AppCompatActivity, I thought I could use "this" or MyActivity.this but that didn't work. I've tried initializing a Context variable "mContext" in onCreate and right before I load the image into the bitmap (like above) but neither worked. I've tried this.getApplicationContext() and I've also tried to pass mContext as a parameter in the loadBitmap() method but that didn't work either.
My URL string is correct. I'm just not sure how to tackle this problem after trying, what seems like, everything.
Last piece of information, the exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:112)
at com.salty.seas.Driver.MyActivity.loadBitmap(MyActivity.java:144)
at com.salty.seas.Driver.MyActivity$1.onKeyEntered(MyActivity.java:61)
at com.firebase.geofire.GeoQuery$2.run(GeoQuery.java:126)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
In the comments to the question you said that the activity, the loadBitmap() belongs to, you actually instantiate yourself (in some other fragment) and use it as an utility class.
You should never create activites manually as they are managed by android and they have a lifecycle android maintains.
In your case the activity is not in a correct state (one of its internal fields is null), that's why you get NPE.
For utility methods create utility classes and call those from wherever you want.
I am getting the following line in LogCat that seems to point to a null dbHelper when opening my SQLite DB.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.---.---.GasDataSource.open(GasDataSource.java:29)
at com.---.---.Vehicle.<init>(Vehicle.java:33)
at com.---.---.GasFragment$1$3.onClick(GasFragment.java:212)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Here is the chain of code listed in the Stacktrace (it references three lines):
Instantiate a new Object:
Vehicle v = new Vehicle(getActivity(), vId); // GasFragment.java:212
Open the Datasource inside the Object to load existing properties
public Vehicle(Context mContext, int vehicleId) {
GasDataSource datasource = new GasDataSource(mContext);
datasource.open(); // Vehicle.java:33
Do the actual Open method
database = dbHelper.getWritableDatabase(); // GasDataSource.java:29
Supplemental code: GasDataSource constructor:
public GasDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
I don't understand how dbHelper can be null. The only thing I can think of was the context was null OR thedatabase was closed already because this happened as the app was in the background for a long time and when I opened it up and hit the 'save' button in the Activity (which triggers this code in part).
Can someone possibly identify the cause, if not, what the best way to at least do a null check here? it seems weird to do it on this line (I have never seen it done before in examples): dbHelper.getWritableDatabase();