我应该在这里为Android上下文使用什么?

时间:2014-06-16 21:27:23

标签: java android android-alertdialog android-context

我试图使用来自" Android Recipes"的代码:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("FetchAndPopTask.doInBackground exception");
builder.setMessage(e.getMessage());
builder.setPositiveButton("OK", null);
builder.create().show();

......但不知道应该替换什么" context"用。我已经尝试过.java文件的课程,直接上课,以及"这个"但他们都没有编译。

在更多上下文中,代码是:

public class SQLiteActivity extends ActionBarActivity {

private FetchAndPopTask _fetchAndPopTask;

. . .

private class FetchAndPopTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        . . .
        try {
            . . .
        } catch (Exception e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this); // <= "context"...?
            builder.setTitle("If I go blind, I'll use a Service Platypus (instead of a Service Dog)");
            builder.setMessage(e.getMessage());
            builder.setPositiveButton("OK", null);
            builder.create().show();
            return result;
    }

我尝试了以下所有方法:

AlertDialog.Builder builder = new AlertDialog.Builder(SQLiteActivity);
AlertDialog.Builder builder = new AlertDialog.Builder(FetchAndPopTask);
AlertDialog.Builder builder = new AlertDialog.Builder(this);

......但没有编译;那么&#34; context&#34;需要在这里吗?

5 个答案:

答案 0 :(得分:3)

AlertDialog.Builder(SQLiteActivity.this)应该可以正常工作

但请看一下this question

修改!!!!! 抱歉,您没有注意到您正在尝试在非UI线程中显示它。请将其放在构造函数或onPreExecute() / onPostExecute()方法

答案 1 :(得分:3)

doInBackground()将在后台线程上运行。您无法在非UI线程上触摸UI。这包括显示对话框。从AlertDialog移除doInBackground()。你可以把它放在例如在UI线程上运行的onPostExecute()。在那里,您可以使用YourActivityName.this引用要用作this的外部课程Context

答案 2 :(得分:1)

您必须将Activity传递给此构造函数。

您必须在FetchAndPopTask课程中添加:

private SQLiteActivity context;

public FetchAndPopTask(SQLiteActivity context) {
    this.context = context;
}

然后,在SQLiteActivity类中,您必须使用this关键字传递此上下文(因为您在活动中,它指的是它):

/*...*/
FetchAndPopTask task = new FetchAndPopTask(this);
task.execute();
/*...*/

答案 3 :(得分:1)

new AlertDialog.Builder(this);

this表示您获得了FetchAndPopTask的指针/引用,因此不使用this,而是使用SQLiteActivity的指针/引用来调用SQLiteActivity.this }}

答案 4 :(得分:1)

为您的类定义构造函数并传递上下文

private class FetchAndPopTask extends AsyncTask<String, String, String> {

private Context mContext;

public FetchAndPopTask(Context context){
    mContext = context;
}

@Override
protected String doInBackground(String... params) {
    . . .
    try {
        . . .
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext); // <= use the variable here
        builder.setTitle("If I go blind, I'll use a Service Platypus (instead of a Service Dog)");
        builder.setMessage(e.getMessage());
        builder.setPositiveButton("OK", null);
        builder.create().show();
        return result;
}