Get Context Java Android example

getContext() getApplicationContext() method Java Android example source

 
Context myContext_1 = ThisClassName.this; // to open a Dialog
Context myContext_2 = getContext();
Context myContext_3 = this.getContext();
Context myContext_4 = this;
Context myContext_5 = this.getApplicationContext ();
 
 
	OnClickListener getImageBtnOnClick = new OnClickListener() {
		public void onClick(View view) {
			Context context = view.getContext();
 
		}
	};
// Toast 
Toast.makeText(getApplicationContext(), "Context == getApplicationContext "
   , Toast.LENGTH_SHORT).show();
 
 
 
// store Context in public class
public class MyActivity extends Activity { 
    public static Context myCnt = null; 
    ... 
    protected void onCreate(Bundle icicle) { 
         ... 
        myCnt = this; 
        MyStorage.setContext(myCnt); 
        // or
        // MyStorage.setContext(this);        
 
        // cntxFromStorage == this
        Context cntxFromStorage = MyStorage.getContext();
        ... 
        }; 
    }; 
 
public class MyStorage
{
    private static Context cntStorageContext = null;
 
 
    public static Context getContext() { 
        return cntStorageContext;
     }
 
    public static void setContext(Context context) {
	 MyStorage.cntStorageContext = context;
	  }
 
 
    }; 
 
class DataBaseHelper extends SQLiteOpenHelper {
// get MyActivity context 
Context cnt = MyStorage.getContext();
 
}
This entry was posted in Android Examples Code and tagged , , , , . Bookmark the permalink.


Comments are closed.

11,534 views