0

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 (:

Tashila Pathum
  • 109
  • 2
  • 11
  • `new MainActivity()` is an illegal call. You aren't allowed to instantiate an Activity like that (and expect everything to work). What you want to achieve doesn't require an Activity at all! Also, why are you creating a new thread in your JobService and why are you calling `jobFinished` before the job has finished? – Zun Dec 10 '19 at 08:15
  • @Zun Could you explain a way around this? Thanks. – Tashila Pathum Dec 10 '19 at 08:18
  • "Stop doing pretty much all the things he mentioned" is a good way around this. – EpicPandaForce Dec 10 '19 at 08:22
  • Just put the code that's inside your `new Thread(() -> {` in your JobService. – Zun Dec 10 '19 at 08:22
  • @EpicPandaForce I used `MainActivity.getInstance().checkNow()` and it worked. I meant that kind of "way around this". – Tashila Pathum Dec 10 '19 at 11:58
  • https://stackoverflow.com/a/4947166/2413303 – EpicPandaForce Dec 10 '19 at 13:21

2 Answers2

3

In MainActivity, onCreate is called when you startActivity. So, when you call new MainActivity(), onCreate not get called and sharedPref not intialized. I suggest you to move sharePref to a sigleton class that manage all of preferences in your app.

class AppPref {
  SharedPreferences sharedPref;
  private static AppPref instance;

  private AppPref(Context context) {
    sharedPref = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
  }

  static AppPref getInstance(Context context) {
    if (instance == null) {
      instance = new AppPref(context);
    }
    return context;
  }

  public void someMethod() {
    // ....
  }
}

// Somewhere in your app
AppPref.getInstance(context).someMethod()
Tuan Luong
  • 3,902
  • 1
  • 16
  • 18
  • I didn't exactly use this solution but I used `getInstance()` thing to call the method in `MainActivity` and it worked. Thanks. – Tashila Pathum Dec 10 '19 at 11:57
0

I used the following way to solve this problem:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static MainActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance = this;
    }

    public static MainActivity getInstance() {
        return instance;
    }

    public void myMethod() {
       // do something...
    }
)

AnotherClass.java

public Class AnotherClass() {
     // call this method
     MainActivity.getInstance().myMethod();
}

Reference: https://stackoverflow.com/a/47241833/10389123

Tashila Pathum
  • 109
  • 2
  • 11