从Asynctask调用另一个活动的方法

时间:2014-06-27 09:45:51

标签: android android-activity android-fragments android-asynctask

我在方法"No enclosing instance of the type MainFragmentActivity is accessible in scope" -

中收到语法错误 - buildReport

enter image description here

buildReport方法 -

public void buildReport(View v)
{
    //Syntax error here
    new VerifyDialogue(MainFragmentActivity.this).execute(dateRange); 
}

这是我的AsyncTask类 -

class VerifyDialogue extends AsyncTask<String, String, String> {
public MainFragmentActivity activity;

public VerifyDialogue(MainFragmentActivity a)
{
    //this is how I am getting instance of another activity
    this.activity = a; 
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Initializing Please Wait");
    pDialog.setTitle("Loading");
    pDialog.setCancelable(true);
    pDialog.show();
}


protected String doInBackground(String... args) {
    return "";
}

protected void onPostExecute(String result) {
    //there are records in the sync queue
    AlertDialog.Builder alert = 
            new AlertDialog.Builder(
    ReportsTypeActivity.this);
    alert.setTitle("User Records!");
    alert.setMessage("You have records on the server.");

    alert.setPositiveButton("FIX", 
            new DialogInterface.OnClickListener() {
    public void onClick(
            DialogInterface dialog, 
            int whichButton) 
            {
      dialog.cancel();

        //Calling method of activity MainFragmentActivity
        activity.nonsyncscreen(); 
    }
    });

    AlertDialog alertDialog = alert.create();
    alertDialog.show();                 
}

2 个答案:

答案 0 :(得分:1)

您只能在嵌套类中使用MainFragmentActivity.this。所以“在范围内无法访问MainFragmentActivity类型的封闭实例”意味着您的方法buildReport(View v)不在MainFragmentActivity

内的嵌套类中

可能的解决方案,将MainFragmentActivity的实例传递给ReportsTypeActivity

的构造函数

另一种可能的解决方案:

Mainfragment class:

{ 
    private static MainFragmentActivity instance;

    public onCreate(...){
        instance = this;
    }

    public static MainFragmentActivity getInstance(){
        return instance;
    }
}

ReportsTypeActivity级:

public void buildReport(View v)
{
    //Syntax error here
    new VerifyDialogue(MainFragmentActivity.getInstance()).execute(dateRange); 
}

编辑:getInstance()应该是静态的

答案 1 :(得分:0)

我有一个正在运行的例子......

new MatchStreamListTask(this, URL, listview).execute();

如果你在外部添加它,你必须传递上下文..

public class MainFragmentActivityTask extends AsyncTask<String, Void, String> 
{
    Activity context;

    ListView listview;

    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();


    public MainFragmentActivityTask (Activity coontext,String URL,ListView listview ) 
    {
        this.context=coontext;

        this.URL=URL;

        this.listview=listview;
    }