Подтвердить что ты не робот

MainActivity.this не является закрывающим классом AsyncTask

Я пытаюсь создать AsyncTask в первый раз, но мне не очень повезло.

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

Ответ 1

Eclipse, вероятно, прав, и вы пытаетесь получить доступ к классу (MainActivity), который находится внутри него собственного файла из другого класса, который находится в его собственном файле (BackgroundWorker). Невозможно это сделать - как волшебный волшебник должен знать об этом другом классе? Что вы можете сделать:

  • Переместите AsyncTask таким образом, что это inner класс в MainActivity
  • Передайте свою активность в 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...

Что касается

Я не уверен, правильно ли я использовал контекст

Это нормально.

Ответ 2

Выше приведен пример внутреннего класса, вот автономный класс...

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

}