Model.Result.getFormatted_address()' on a null object reference - java

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.

Related

My app force close when call putString on SharedPreference.Editor

The problem occurs when I call putString to SharedPreference.
My program is first run through TileService which runs a ForegroundService then from ForegroundService opens an Activity and in this Activity I call putString to a SharedPreference.
How to make it work perfectly?
TileService
...
#Override
public void onClick()
{
super.onClick();
Intent intent = new Intent(mContext,AdzanService.class);
if(mTileEnabled)
intent.setAction("STOP_SERVICE");
else
intent.setAction("START_SERVICE");
startForegroundService(intent);
mTileEnabled = !mTileEnabled;
}
...
Service
...
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent.getAction().equals("STOP_SERVICE"))
{
stopForeground(true);
stopSelf();
}
...
Activity
...
private void save(){
mEditor.putString("setting_location",((EditText)findViewById(R.id.setting_location)).getText().toString());
mEditor.putString("setting_times",((RadioButton)findViewById(((RadioGroup)findViewById(R.id.setting_times)).getCheckedRadioButtonId())).getTag().toString());
mEditor.apply();
}
...
Error
java.lang.RuntimeException: Unable to start service in.blackant.adzan.AdzanService#873299c with null: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3722)
at android.app.ActivityThread.access$1600(ActivityThread.java:198)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1686)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6693)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
at in.blackant.adzan.AdzanService.onStartCommand(AdzanService.java:97)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3703)
... 8 more
As the error message states, the Intent in your service class is null when you call intent.getAction()
Intent is nullable here according to the docs
The Intent supplied to Context.startService(Intent), as given. This may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.
Adding a null check before you check getAction() will fix the crash, but you might want to look into why your service is being restarted

Android android.media.PlayerBase.PlaybackDetectionCallBack NullPointerException

My app crash only in vivo phones, and the error log is this:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.content.Context.getOpPackageName()' on a
null object reference at
android.media.PlayerBase.PlaybackDetectionCallBack(PlayerBase.java:348)
at android.media.PlayerBase.baseStop(PlayerBase.java:229) at
android.media.MediaPlayer$2.onCompletion(MediaPlayer.java:3578) at
android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:3351)
at android.os.Handler.dispatchMessage(Handler.java:106) at
android.os.Looper.loop(Looper.java:192) at
android.app.ActivityThread.main(ActivityThread.java:6671) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:818)
I believe it is about MediaPlayer which I use to play BGM in my app.
But I can't find out how this happens since the error stack didn't retrieve to my code.
Here is all my code about play BGM.
public void playBgm(final int resId, boolean restartIfSame) {
if(resId == currentBgmRes && !restartIfSame) {
if(!bgmPlayer.isPlaying()) {
bgmPlayer.start();
}
return;
}
if(bgmPlayer.isPlaying()) {
bgmPlayer.stop();
}
_playBgm(resId);
}
private void _playBgm(int resId) {
bgmPlayer.release();
bgmPlayer = MediaPlayer.create(this, resId);
bgmPlayer.setLooping(true);
currentBgmRes = resId;
bgmPlayer.start();
}
The two functions are inside class AppDelegate extends Application, so this should be the application instance.
It doesn't always crash. Since the phone causing the problem is some far-away user's, I can't get the phone in several days. So I'm not sure in what situation it will happen, but it should not happen in any situation.
I figured out the problem.
My MediaPlayer variable has an initial value new MediaPlayer().
When the Activity playing the BGM calls onPause(), I call MediaPlayer.pause().
But calling pause() to a new MediaPlayer() seems to cause crash in some devices, while OK in other devices.
I change the initial value to null, and do the null check whenever I use the object. The crash never happen again.

Fatal Exception. App crashes on start [duplicate]

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.

Saving custom array in shared preferences

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

Nullpointerexception when trying to open SQLite database

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

Categories