get Context in non-Activity class [duplicate]

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows: class YourNonActivityClass{ // variable to hold context private Context context; //save the context recievied via constructor in a local variable public YourNonActivityClass(Context context){ this.context=context; } } … Read more

How can I share a SharedPreferences file across two different android apps?

It is better to set private mode for the file. App needs to be signed with same set of certificates to share this file. Set sharedUserId in both apps to be same. <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.hello” android:versionCode=”1″ android:versionName=”1.0″ android:sharedUserId=”com.example”> …. Get Context from other package: mContext = context.createPackageContext( “com.example.otherapp”, Context.MODE_PRIVATE); mPrefs = mContext.getSharedPreferences(“sameFileNameHere”, Activity.MODE_PRIVATE); Get items … Read more

Why does AlertDialog.Builder(Context context) only accepts Activity as a parameter?

An Activity inherits a Context. AlertDialog.Builder specifies a Context argument because it can then be used by ANY class that is a subclass of Context, including an Activity, ListActivity, Service, … (There is a common coding idiom behind this – you can learn more about it by reading Item I8 (on Interfaces and Abstract classes) … Read more

getting context in AsyncTask

You need to do following things. when you want to use AsyncTask, extend that in other class say MyCustomTask. in constructor of new class, pass Context Example public class MyCustomTask extends AsyncTask<Void, Void, Long> { private Context mContext; public MyCustomTask (Context context){ mContext = context; } //other methods like onPreExecute etc. protected void onPostExecute(Long result) … Read more

What is the difference between Activity and Context?

As far as I understand: Context is the Base Object. So every Activity same as Application derives from Context. This means that every Activity and every Application IS a Context; From developer.android.com Activity java.lang.Object ↳ android.content.Context ↳ android.content.ContextWrapper ↳ android.view.ContextThemeWrapper ↳ android.app.Activity And Application java.lang.Object ↳ android.content.Context ↳ android.content.ContextWrapper ↳ android.app.Application An Application context lasts, … Read more

getApplicationContext(), getBaseContext(), getApplication(), getParent()

getApplicationContext() Application context is associated with the Applicaition and will always be the same throughout the life cycle. getBasecontext() should not be used, just use Context instead of it which is associated with the activity and could possible be destroyed when the activity is destroyed. getApplication() is available to Activity and Services only. Although in … Read more