Dr. ali Dr. ali - 6 months ago 16
Android Question

call to non-static method from a static method crash

I am trying to call to non-static method from a static method but the app crash and I don't know why this is happened. I would be happy if you can help me understood why this is happened and how I can fix it.

Static function -

public static void myPlace(String place, String titles) {

if (place == "[]") {
// Not found Skip
} else {
Log.d("placea - ", place);
Log.d("titles - ", titles);

BackgroundProcess b = new BackgroundProcess();
b.addNotification();

}


Non Static function -

public void addNotification() {

NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");

Intent notificationIntent = new Intent(this, MyNotification.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);

// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(FM_NOTIFICATION_ID, builder.build());
}


Log -

FATAL EXCEPTION: AsyncTask #3
Process: alon.myplace, PID: 18679
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:4160)
at alon.myplace.BackgroundProcess.addNotification(BackgroundProcess.java:238)
at alon.myplace.BackgroundProcess.myPlace(BackgroundProcess.java:224)
at alon.myplace.PlacesDisplayTask.doInBackground(PlacesDisplayTask.java:33)
at alon.myplace.PlacesDisplayTask.doInBackground(PlacesDisplayTask.java:13)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)


Thanks for any help.

Answer

The problem is with the context which you are passing in

Intent notificationIntent = new Intent(this, MyNotification.class);

this is null.

Please check how you are getting the context. It should be a valid context and should not be null.