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));
        }
    }
}
4

2 回答 2

20

Eclipse 可能是正确的,并且您正试图从其自己的文件 () 中的另一个类访问它自己的文件MainActivity内的类 ( )。没有办法做到这一点 - 一个班级应该如何神奇地了解另一个班级的实例?你可以做什么:BackgroundWorker

  • 移动 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...

至于

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

没事。

于 2013-01-02T03:06:22.153 回答
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);
}

}

于 2019-07-14T15:23:55.000 回答