My app force close when call putString on SharedPreference.Editor - java

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

Related

problem with Context "getApplicationContext()' on a null object reference"

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

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.

Broadcasting Intent or starting Activity from separate java class: Null object reference error

Moved methods that broadcast intents or start activities (Launch Google Assistant, Volume Up/Down, pause audio) from Service to a separate java class in order to call them using invoke and a string as their name rather than using countless of if statements (the methods are triggered upon a button press from a bluetooth device).
I am getting a NullPointerException Error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.content.Context.sendBroadcast(android.content.Intent)' on a
null object reference
10-19 16:53:25.277 8073-8133/com.example.android.zeno W/System.err:
at
android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:396)
The Java class extends the Service where the methods were previously located.
This is one of the methods (triggers Google Assistant) located in a separate class called ActionsPhonecontrol:
public class ActionsPhonecontrol extends BluetoothLeService {
boolean PCL_googleNow() {
startActivity(new Intent(Intent.ACTION_VOICE_COMMAND).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
return true;
}
This is the method that invokes the other methods from the separate class:
void invokeAction(String method, String className) {
broadcastUpdate(method);
String mType = getPackageName() + "." + className;
//trigger received sound
soundPlay(R.raw.blip1, 500);
try {
Class mClass = Class.forName(mType);
Method mMethod = mClass.getMethod(method);
Object newClass = mClass.newInstance();
String p = (String) mMethod.invoke(newClass);
} catch (Exception e) {
e.printStackTrace();
}
}
Any ideas why it shows the error?

getApplicationContext on a null reference in AppCompatActivity using Picasso

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.

Null pointer exception when calling method from a different class

When I attempt to call the method loadUserList() from another class, I get the following error:
Attempt to invoke virtual method android.content.res.Resources
android.content.Context.getResources() on a null object reference
This is my loadUserList method
public void loadUserList()
{
final ProgressDialog dia = ProgressDialog.show(this, null, getString(R.string.alert_loading));
ParseQuery<ParseObject> query = ParseQuery.getQuery("Chat_User");
query.whereEqualTo("receiver", ParseUser.getCurrentUser());
query.include("sender");
query.findInBackground(new FindCallback<ParseObject>()
{
#Override
public void done(List<ParseObject> li, ParseException e)
{
dia.dismiss();
if (li != null)
{
if (li.size() == 0)
Toast.makeText(com.yarnyard.UserList.this, R.string.msg_no_user_found,
Toast.LENGTH_SHORT).show();
uList = new ArrayList<ParseObject>(li);
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new UserAdapter());
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3)
{
loadUserList();
/*startActivity(new Intent(com.yarnyard.UserList.this, Chat.class)
.putExtra(Const.EXTRA_DATA, uList.get(pos).getUsername()));*/
}
});
}
else
{
Utils.showDialog(
com.yarnyard.UserList.this,
getString(R.string.err_users) + " "
+ e.getMessage());
e.printStackTrace();
}
}
});
}
This is how I am calling it
public void done(ParseException e)
{
UserList UserList = new UserList();
UserList.loadUserList();
}
My error log
07-30 14:14:56.219 13383-13383/com.anonimv2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.anonimv2, PID: 13383
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:85)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at android.content.Context.getString(Context.java:376)
at com.yarnyard.UserList.loadUserList(UserList.java:96)
at com.yarnyard.custom.CustomActivity.onOptionsItemSelected(CustomActivity.java:116)
at android.app.Activity.onMenuItemSelected(Activity.java:2882)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1131)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at android.widget.ActionMenuView.invokeItem(ActionMenuView.java:587)
at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:141)
at android.view.View.performClick(View.java:4832)
at android.view.View$PerformClick.run(View.java:19839)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5321)
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:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
Any advice would be much appreciated.
Normal, non-static methods are called on objects, not on classes. This is a fine point that you really need to learn before using object oriented languages. Only then you will see, in practice, how you can connect objects by passing references.
The UserList objects that you construct in the done method is not the one you want to call, it's just an empty, uninitialized shell.
As I understand, you extend UserList from Context, right?
Then keep in mind that in Android never initial a Context object by yourself, it's framework's job..
In your case, because you create a context instance without attach to any baseContext, so when access to common resource, you got a NPE.
I guess that you are trying to move to a new Fragment or Actvity? Then read these link start activity switch fragment

Categories