MainActivity.this不是一个封闭类,AsyncTask。

10

我正在尝试第一次创建AsyncTask,但是运气不太好。

我的AsyncTask需要从服务器获取一些信息,然后将新的布局添加到主布局中以显示这些信息。

一切似乎都比较清楚,但是错误消息“MainActivity不是封闭类”让我感到困扰。

似乎没有其他人遇到这个问题,所以我认为我可能错过了非常明显的东西,但我不知道是什么。

此外,我不确定我是否使用了正确的方式来获取上下文,因为我的应用程序无法编译,所以我无法测试它。

非常感谢您的帮助。

以下是我的代码:

public class BackgroundWorker extends AsyncTask<Context, String, ArrayList<Card>> {
    Context ApplicationContext;

    @Override
    protected ArrayList<Card> doInBackground(Context... contexts) {
        this.ApplicationContext = contexts[0];//Is it this right way to get the context?
        SomeClass someClass = new SomeClass();

        return someClass.getCards();
    }

    /**
     * Updates the GUI before the operation started
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    /**
     * Updates the GUI after operation has been completed
     */
    protected void onPostExecute(ArrayList<Card> cards) {
        super.onPostExecute(cards);

        int counter = 0;
        // Amount of "cards" can be different each time
        for (Card card : cards) {
            //Create new view
            LayoutInflater inflater = (LayoutInflater) ApplicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            ViewSwitcher view = (ViewSwitcher)inflater.inflate(R.layout.card_layout, null);
            ImageButton imageButton = (ImageButton)view.findViewById(R.id.card_button_edit_nickname);

            /**
             * A lot of irrelevant operations here
             */ 

            // I'm getting the error message below
            LinearLayout insertPoint = (LinearLayout)MainActivity.this.findViewById(R.id.main);
            insertPoint.addView(view, counter++, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }
    }
}
2个回答

20

很可能Eclipse是对的,你正在尝试从另一个文件(BackgroundWorker)中访问一个类(MainActivity),而该类位于自己的文件中。没有办法做到这一点 - 一个类如何神奇地知道其他类的实例呢?你可以做以下几件事:

  • 将AsyncTask移到MainActivity中,使其成为一个内部
  • 通过构造函数将你的Activity传递给AsyncTask,然后使用activityVariable.findViewById();进行访问(在下面的示例中我使用了mActivity)。或者,如果你的ApplicationContext(使用正确的命名约定,A需要小写)实际上是MainActivity的一个实例,那么你就可以使用ApplicationContext.findViewById();

使用构造函数示例:

public class BackgroundWorker extends AsyncTask<Context, String, ArrayList<Card>>
{
    Context ApplicationContext;
    Activity mActivity;

   public BackgroundWorker (Activity activity)
   {
     super();
     mActivity = activity;
   }

//rest of code...

至于

我不确定我是否使用了正确的方法来获取上下文

没问题。


谢谢您的回复。BackgroundWorker和MainActivity是两个不同的类,分别在两个不同的文件中。我该如何将活动和上下文都传递给AsyncTask?顺便说一下,我使用的是IntelliJ IDEA :) - Allan Spreys

0

上面的例子是内部类,这里是独立的类...

public class DownloadFileFromURL extends AsyncTask<String, String, String> {
ProgressDialog pd;
String pathFolder = "";
String pathFile = "";
Context ApplicationContext;
Activity mActivity;

public DownloadFileFromURL (Activity activity)
{
    super();
    mActivity = activity;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pd = new ProgressDialog(mActivity);
    pd.setTitle("Processing...");
    pd.setMessage("Please wait.");
    pd.setMax(100);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setCancelable(true);
    pd.show();
}

@Override
protected String doInBackground(String... f_url) {
    int count;

    try {
        pathFolder = Environment.getExternalStorageDirectory() + "/YourAppDataFolder";
        pathFile = pathFolder + "/yourappname.apk";
        File futureStudioIconFile = new File(pathFolder);
        if(!futureStudioIconFile.exists()){
            futureStudioIconFile.mkdirs();
        }

        URL url = new URL(f_url[0]);
        URLConnection connection = url.openConnection();
        connection.connect();

        // this will be useful so that you can show a tipical 0-100%
        // progress bar
        int lengthOfFile = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        FileOutputStream output = new FileOutputStream(pathFile);

        byte data[] = new byte[1024]; //anybody know what 1024 means ?
        long total = 0;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            publishProgress("" + (int) ((total * 100) / lengthOfFile));

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // closing streams
        output.close();
        input.close();


    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

    return pathFile;
}

protected void onProgressUpdate(String... progress) {
    // setting progress percentage
    pd.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String file_url) {
    if (pd!=null) {
        pd.dismiss();
    }
    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
    Intent i = new Intent(Intent.ACTION_VIEW);

    i.setDataAndType(Uri.fromFile(new File(file_url)), "application/vnd.android.package-archive" );
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    getApplicationContext().startActivity(i);
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接