G.V. G.V. - 4 months ago 33
Android Question

How to pass context?

I want to pass the context of the main activity to another class in order to create a Toast.

My main activity calls a class that will delete a file.
The class that deletes files will call a toast if the file does not exist.

Here is my code:

public class MyActivity extends AppCompatActivity
public void onCreate(Bundle savedInstanceState)
// create a file

Button buttoncreate = (Button)findViewById(R.id.create_button);

Button buttondelete = (Button)findViewById(R.id.delete_button);

buttondelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

new DeleteFile();

public class DeleteFile extends AsyncTask {

public Object doInBackground(Object[] params) {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/mydir");
if (!(dir.exists())) {
CharSequence text = "Files do not exist!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);

} else {
File file;
file = new File(dir, "mydata.bmp");



First thing, you need Static Variable to declare global variable in Application Class,
like this

class GlobalClass extends Application {

  public static Context context;

    public void onCreate() {
    context = getApplicationContext();


second you need set this class in AndroidManifest.xml inside application tag
like this:

    android:theme="@android:style/Theme.Black.NoTitleBar" >

then whereever you need to access this data, get Application object by:

 Toast toast = Toast.makeText(GlobalClass.context, text, duration);