How to get Application Context UiAutomator2 (Android) - android

To get context, I use:
Context context = InstrumentationRegistry.getInstrumentation().getContext();
But I didn't found any method like getApplicationContext();
Any leads would be appreciated

Try this way:
Your_Activity.this
Or you can create a public static method to get the Context:
public class App extends Application {
private static Application sApplication;
public static Application getApplication() {
return sApplication;
}
public static Context getContext() {
return getApplication().getApplicationContext();
}
#Override
public void onCreate() {
super.onCreate();
sApplication = this;
}
}
Or get it through a View, using Your_View.getContext()
Hope this help

Related

use static android context in static method

I have a PrefUtils class like this:
public class PrefUtils {
public PrefUtils() {
}
private static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences("APP_PREF", Context.MODE_PRIVATE);
}
public static void storeAccessToken(Context context, String access_token) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putString("Access_Token", access_token);
editor.commit();
}
public static String getAccessToken(Context context) {
return getSharedPreferences(context).getString("Access_Token", null);
}
}
In my MainActivity I have a static method and I should use a static Context for it :
public class MainActivity extends AppCompatActivity {
private static Context mcontex;
// Is It right To Add Context To static Variable???
#SuppressLint("CheckResult")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_method();
}
public static void my_method(){
String access_token =PrefUtils.getAccessToken(mcontex);
// more code ...
}
}
Is it right to add Context to a static variable?
Android Studio says: "Do not place Android Context class in static field".
Does this cause an error like memory leak? And if answer is Yes, what is the right way?
Pass the Context as a parameter to the method rather than keeping the context in a static variable.
public static void myMethod(#NonNull Context context){
String access_token =PrefUtils.getAccessToken(context);
// more code ...
}
The downside of having a static context variable is that there is no guarantee that the non-static onCreate() will have been called before some static initialization code tries to fetch your static Context object. That means your calling code will need to be ready to deal with null values.

getSystemService() is not defined

I am trying to create the below posted method to check if a service is running or not. but getSystemService() is markd with red because it is not defined
and it needs a context. I used the following:
Application.getContext().getSystemService
but still getContext is not defined.
in the code i do the following:
if (ServicesUtils.isServiceRunning(NonStickyService.class.getSimpleName())) {
Log.i(TAG, "++++++++++ SERVICE IS RUNNING +++++++++");
} else {
Log.i(TAG, "++++++++++ SERVICE IS NOT RUNNING +++++++++");
}
please let me know which context i should use.
code1:
public class ServicesUtils {
private static String LOG_TAG = ServicesUtils.class.getName();
public static boolean isServiceRunning(String serviceClassName) {
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
if (runningServiceInfo.service.getClassName().equals(serviceClassName)) {
return true;
}
}
return false;
}
}
code2:
public class App extends Application {
public static com.example.pc_amr.stickyvsnonstickyservice.App instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static com.example.pc_amr.stickyvsnonstickyservice.App getInstance() {
return instance;
} // get the instance
}
Since getSystemService is the part of the Context. And your class has no relation to context. So you have to make an Object of the Context and then you can use context.getSystemService.And make sure to pass the value of context using a constructor to avoid NPE.
You can do something like this
public static boolean isServiceRunning(String serviceClassName,Context context) {
final ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
Try creating a static instance of your Application class:
public class App extends Application {
public static App instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static App getInstance() { return instance; } // get the instance
}
Now if you need context you can simply use App.getInstance(). As we know Application class extends Context.
Remember to register App class

Class throwing Null Pointer Exception

Why does the following method throws an NPE,
public ActivityOne extends Activity{
DataManager dtMan = new DataManager(this)
public onCreate (){
...some source code here...
dtMan.check();
}
}
public class DataManager(){
private Context myContext;
public DataManager (Context context){
myContext = context;
}
Helper helper = new Helper(this);
public boolean check(){
helper.open();
...some source code here...
}
}
When I view the logcat; I get a java.null.pointer exception, so I did something like
public class DataManager(){
private Context myContext;
public DataManager (Context context){
myContext = context;
}
public boolean check(Context context){
**Helper helper = new Helper(context);**
helper.open();
...some source code here...
}
}
And it worked, so what is the difference between the two DataManager in Java/Android programming perspective, thus this approach if I understand correctly must be replicated to as follow:
public class DataManager(){
private Context myContext;
public DataManager (Context context){
myContext = context;
}
public boolean check(Context context){
**Helper helper = new Helper(context);**
helper.open();
...some source code here...
}
public boolean check2(Context context){
**Helper helper = new Helper(context);**
helper.open();
...some source code here...
}
public boolean check3(Context context){
**Helper helper = new Helper(context);**
helper.open();
...some source code here...
}
}
Meaning I just can't declare the Helper Class once and use it anywhere the calling class, did I forgot some fundamentals? Please clarify.
Will the context also lead to memory leaks?, if so, how will I fix it?
#EDIT:
Well I forgot to include the Helper Class
public class Helper{
private Context myContext;
public Helper(Context context){
myContext = context;
}
public void open(){
//do stuff here
}
}
Your code does not work because the DataManager is initialized at field scope in the Activity.
Classes which need a Context should always be initialized in one of the Activity's life cycle methods:
onCreate, onStart, onDestroy, etc.
Like this:
private DataManager dataManager;
public void on create(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
dataManager = new DataManager(this):
}
You also should initialize the Helper class in the DataManager constructor:
public class DataManager(){
private Context context;
private Helper helper;
public DataManager (Context context){
this.context = context;
this.helper = new Helper(this.context);
}
public boolean check(Context context){
helper.open();
//...some source code here...
}
}
To prevent memory leaks you just need to make sure the DataManager class is not a static instance with an Activity Context.
If you don't need an Activity Context but you're also fine with an Application Context you should use it:
public DataManager(Context context){
this.context = context.getApplicationContext();
//...
}
Try put
dtMan = new DataManager(this)
in onCreate method in Activity?

How can I get Context from a common class?

I know I can use getApplicationContext() to get Context from sub class of ListActivity.
but PublicPar is common class, how can I get Context from this class.
public class SMSMain extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Context my=getApplicationContext();
}
}
public class PublicPar {
public static void SetNotification(){
}
}
If you have a common (helper-type) class like your PublicPar class, the best you can do is to pass context as a parameter to each method:
public static void SetNotification(Context context) {
}
Remember to not set this context to any PublicPar class variable to avoid leaking it.
Try this. It should work:
public class SMSMain extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Context my=getApplicationContext();
new PublicPar().SetNotification(SMSMain.this)
}
}
public class PublicPar {
public static void SetNotification(final Context context ){
// You can proceed with using the context here.
}
}
If you don't want to pass the Context around as part of constructor argument, you can expose a static method in the application.
public class MyApplication extends Application {
private static MyApplication myinstance;
public MyApplication() {
myinstance = this;
}
public static Context getAppContext() {
myinstance.getApplicationContext();
}
}

Starting an Android Activity from a static method

I want to start an activity from a static java method on an android device.
I do not have any context or anything passed as parameter to the static function.
For starting the activity I must call "startActivity" with the current running method as "this" pointer. So is there a way to get the current running activity?
You can access only static variables/objects inside static method.
So You need to Implement this way
public class MainActivity extends Activity {
private static Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
}
public static void goToLoginActivity() {
Intent login = new Intent(mContext, LoginActivity.class);
mContext.startActivity(login);
}
}
NOTE : But this is not the proper way to do so, this may cause window leak issue.
Better approach is pass activity/context object as parameter like this.
public static void goToLoginActivity(Context mContext) {
Intent login = new Intent(mContext, LoginActivity.class);
mContext.startActivity(login);
}
Create a Class in your app extending class Application, define a static context and initialise this with your application context. You can expose a static method from this class for accessing defined static reference. Thats it.
class MyApp extends Application{
private static Context mContext;
public void onCreate(){
mContext = this.getApplicationContext();
}
public static Context getAppContext(){
return mContext;
}
}
Now you can use this static method for accessing context anywhere in your app.

Categories

Resources