0

I'm trying to programatically call Home button with another button inside my project. App compiles fine, but when I tap the button that should call Home I receive following error:

Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference

Here is my code (just essentials):

import android.app.Activity;
import android.content.Intent; 
import android.content.Context;

public class ClassName extends ReactContextBaseJavaModule {
  private Context context;

  @ReactMethod
  public void minApp() {
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(startMain);
  }
}

What am I doing wrong?

SOLUTION:

Due to the fact that my app uses react native, the code in bridged method in java file should look as below:

import android.content.Intent; 
import android.content.Context;

public class ClassName extends ReactContextBaseJavaModule {

  @ReactMethod
  public void minApp() {
    Context context = getReactApplicationContext();
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(startMain);
  }
}

Using this we can assign Home button function anywhere we want ;)

vasyl
  • 105
  • 1
  • 10

2 Answers2

2
public void openLauncher(Context context) {
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(startMain);
}

You can just open the launcher using this function.

Qazi
  • 122
  • 6
  • This time I got following error: `Got unknown argument class: Context` – vasyl Sep 25 '18 at 12:11
  • 1
    you haven't initialized the context variable, you should initialize it and set to the current Activity context or you can use `getContext()` or `getApplicationContext()` to be passed into the openLauncher method. – Qazi Sep 26 '18 at 07:29
  • I updated my question and now the code looks as above. App compiles but when I call `minApp()` it throws an error: `Got unknown argument class: Context`. – vasyl Sep 26 '18 at 09:54
  • Problem solved, thank you for your help! – vasyl Sep 26 '18 at 11:55
1

Seems like you haven't initialized context. Make sure to initiate it before calling minApp()

isamirkhaan1
  • 749
  • 7
  • 19