0
public class QRProductActivityPageObject {


    public static void testProductDetail() throws InterruptedException {

        ActivityTestRule<ProductInfoActivity> rule = new ActivityTestRule<ProductInfoActivity>(ProductInfoActivity.class, true, false);
        Intent intent = new Intent();
        intent.setClass(getActivity(), ProductInfoActivity.class);
        rule.launchActivity(intent);
        Thread.sleep(2000);
     }
}

The above syntax show error that you cant access getActivity() in static method . But i want to call this new Activity(ProductInfoActivity) through static method only.Any suggestion??

1
  • 1
    add context into your function : testProductDetail(Context ctx) and use intent.setClass(ctx, ProductInfoActivity.class);
    – Danh DC
    Mar 1, 2016 at 10:19

3 Answers 3

0

Pass context when method call in Activity or fragment and get Activity from context in static method

 public static void testProductDetail(Context context) throws InterruptedException {

ActivityTestRule<ProductInfoActivity> rule = new  ActivityTestRule<ProductInfoActivity>(ProductInfoActivity.class, true, false);
Intent intent = new Intent();
Activity activity = (Activity) context;
intent.setClass(activity , ProductInfoActivity.class);
rule.launchActivity(intent);
Thread.sleep(2000);
 }

Call static method In activity

  testProductDetail(getApplicationContext());

In fragment

  testProductDetail(getActivity().getApplicationContext());
0

Or use the solution I found around here a few weeks ago, it's pretty awesome and elegant. You'd be able to use it anywhere in your APP!

  1. Create a class MyApplication (you could name it differently):

      public class MyApplication extends Application {
      private static Context context;
    
    public void onCreate() {
    super.onCreate();
    MyApplication.context = getApplicationContext();
    }
    
    public static Context getAppContext() {
    return MyApplication.context;
       }
    }
    
  2. Go to your app Manifest file and add to the <application... tag the android:name attribute with the value of the name of the class we created:

    <application
    android:allowBackup="true"
    android:icon="@drawable/appico"
    android:label="@string/app_name"
    android:name="MyApplication"
    

Now you can get the context for your app from any class like that

MyApplication.getAppContext();

0

You don't need to call getActivity(). Instead of using setClass() method which requires you to give a context object, you can use setClassName(String packageName, String className) method. Try this:

Intent intent = new Intent();
intent.setClassName("package.name.of.your.app", 
        ProductInfoActivity.class.getName());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.