Currently I use this way to get context:
SharedPreferences sharedPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = MyApplication.getAppContext();
sharedPref = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
}
MyApplication class:
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
I'm trying to call a method in MainActivity
from MovieUpdatesService
class
MainActivity
method:
public void checkNow() {
new Thread(() -> {
String site = null;
if (sharedPref.contains("site")) //line 153
site = sharedPref.getString("site", "Not available");
//codes...
}).run();
}
MovieUpdatesService
class:
public class MovieUpdatesService extends JobService {
//codes...
public void doBackgroundWork(final JobParameters params) {
if (jobCancelled)
return;
new MainActivity().checkNow();
Log.d(TAG, "Job finished");
jobFinished(params, false);
}
//codes...
}
I get NullPointerException when running and I think it has something to do with context
Error:
java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.content.SharedPreferences.contains(java.lang.String)' on a null object reference
at com.tashila.movieupdates.MainActivity.lambda$checkNow$0(MainActivity.java:153)
How do I fix this? I'm new to Android so I'm hoping for a simplified answer (: