How to pass context?

寵の児 提交于 2021-02-18 12:15:07

问题


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() {
        @Override
        public void onClick(View view) {

            new DeleteFile();
        }
    });
}

public class DeleteFile extends AsyncTask {

@Override
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);
        toast.show();

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

}

回答1:


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

class GlobalClass extends Application {

  public static Context context;

   @Override
    public void onCreate() {
    super.onCreate();
    context = getApplicationContext();
    }

  }

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

<application
    android:name=".GlobalClass"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    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);
    toast.show();


来源:https://stackoverflow.com/questions/40892448/how-to-pass-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!