Static Way to Get 'Context' in Android

Static way to get 'Context' in Android?

Do this:

In the Android Manifest file, declare the following.

<application android:name="com.xyz.MyApplication">

</application>

Then write the 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;
}
}

Now everywhere call MyApplication.getAppContext() to get your application context statically.

Best way to get an Application Context into a static method in Android

The better way would be to pass the Activity object as parameter to the static functions.

AFAIK, there is no such method which will give you the application context in the static method.

How a static method get context from the calling activity?

Basically there are several types of context. In your case you can get it from v.getContext();

How to pass context to a static method?

Your problem is not sending the Context. Your problem is:

private static Context context;

If you are absolutely certain that you need something like that, replace it with:

private static Application context;

Adjust your method to take an Application as a parameter, and have your call to that method use getApplication() instead of getApplicationContext().

IOW, your code is reasonably safe — you are using the Application context — but the details of your code is making Lint nervous.

How to get this Context in a static method

public class DetailMapView extends FragmentActivity {
public static void updateLocation(Context context, String number, String LatLong){
LatLogDBAdapter dbHelper = new LatLogDBAdapter(context);

}

}

Add a Context as a parameter to your static method, and pass it in when you call the method.

Can an Android Context inside an activity be static?

I am confused if I can make context static. Is there any side effects
to it?

You can declare a context as static but it is not recommended in Android, because it might lead to a memory leak in your app.

is there any other way I can access my resources without using
context?

No, you need a context instance to access resources in your app.

Back to your case, the easiest way is passing a context as param of the method.

private static SpannableStringBuilder setTextColor(Context context, SpannableStringBuilder Text, int spanLength, boolean isSuggestion) {
int color = context.getResources().getColor(isSuggestion ? R.color.blur : R.color.red);

addressText.setSpan(new ForegroundColorSpan(color),
addressText.length() - 1 - spanLength,
addressText.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

return Text;
}

Inside your activity, pass this as context when calling setTextColor, for example.

setTextColor(this, new SpannableStringBuilder(), 0, false); 

How to reference getSharedPreferences from a static context that is not an Activity

to use the sharedPreferences you need to have the activity, so there's a lot of options here:

  • if you're using fragments then you need activity to get applicationContext,
    you can get an activity by calling requireActivity() on your fragment object.

  • then get a SharedPreferences reference to your data through this line of code.

Context context = requireActivity().getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
"mySharedPrefData", Context.MODE_PRIVATE);
  • then you can send this sharedPref reference through the adapter constructor when you initialize it.
    so your adapter constructor code should look like this :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewholder> {
SharedPreferences myShared ;
public MyAdapter (SharedPreferences shared){
myShared = shared ;
}
}

which from now on you can use the myShared variable to access your shared preferences inside your adapter.

N.B : if you're not using fragments and initializing your adapter inside your main activity directly, then you can skip the requireActivity part and your shared preferences code will look like this instead

Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
"mySharedPrefData", Context.MODE_PRIVATE);

Update

  • since there's some confusion let me clarify that you should use the getApplicationContext() call inside your activity, assuming you initialize your adapter in onCreate method inside activity, then your MainActivity code might look like this :
public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
...
Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
"mySharedPrefData", Context.MODE_PRIVATE);
MyAdapter myAdapter = new myAdapter(sharedPref);
...
}
}

N.B : three dots (...) means that I don't care about your code written here.

Update

  • if you don't have the permission to edit the adapter constructor parameters then what about making a setter to it.

MyAdapter.java

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewholder> {
SharedPreferences myShared ;
public MyAdapter (SomeOtherParameter){...}
public void setMyShared(SharedPreferences shared){
myShared = shared ;
}
}
  • then after initializing your adapter, you set the shared Preferences to it

MainActivity.java

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
...
Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
"mySharedPrefData", Context.MODE_PRIVATE);
MyAdapter myAdapter = new myAdapter(SomeOtherParameter);
myAdapter.setMyShared(sharedPref);
...
}
}

N.B : if you used the code above then don't use the myShared object in any case in the adapter constructor to avoid NullPointerException



Related Topics



Leave a reply



Submit