Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Activity before it starts

Tags:

android

junit

I am using the InstrumentationTestCase class in order to unit test some things within an activity.

I need to be able to check the SharedPreferences's contents and edit them, before this activity is launched.

I cannot use the setUp method to create the Activity and access it's SharedPreferences object to edit it, and then close that activity before finishing the setUp method because it apparently is locking the tests processing.

I also cannot access the SharedPreferences after I have launched the activity inside the test because as soon as the Activity is launched, it will already change the SharedPreferences object and act according to it, before I had the chance to get it's reference.

I apparently cannot access the SharedPreferences before either, because I have no Activity object... and as soon as I do, it is already executing code and being launched...

So, my question is, is there any way to access the SharedPreferences (and any other Activity information) of this Activity before I have the Activity actually created through an Intent?

I cannot change it to an ActivityInstrumentationTestCase2 because my test uses a second activity in it's process, so I can't just change to this class and use it's setUp() method to access the SharedPreferences.

like image 969
Luis Miguel Serrano Avatar asked Dec 22 '22 20:12

Luis Miguel Serrano


2 Answers

I found the best simpler way to do this through the instrumentation only, without having to edit the application's architecture or any of the access attributes.

I achieved it through this:

Instrumentation instrumentation = getInstrumentation();
instrumentation.getTargetContext().getSharedPreferences(..);

This way I can access the SharedPreferences before any Activity is launched by the instrumentation.

Thanks for all the help, hints and other alternatives anyway.

like image 102
Luis Miguel Serrano Avatar answered Jan 06 '23 03:01

Luis Miguel Serrano


Well... To tell you frankly.. I am not able to visualize your scenario. But is checking for info in application is doable ?

Create a class which extends android.app.Application and specify class name in Manifests child application element.

Sample Code:

import android.app.Application;

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        //try and access activity info here.
    }
}

When your application is launched first class method to execture is onCreate of your application and has all the lifecyle events of that of any activity..

You must define extended application class in manifest by:

<application
    android:name=".MyApplication"
    android:label="@string/application_name">

I hope this ca give you some overview.

like image 38
Shardul Avatar answered Jan 06 '23 03:01

Shardul