在 AsyncTask 中使用 getSupportFragmentManager()

Using getSupportFragmentManager() inside AsyncTask

我有一个 Activity,它有一个 Navigation Drawer,它有很多按钮,其中一个指向 fragment
问题是我必须创建一个 AsyncTask 才能从服务器获取一些信息,但我无法在 AsyncTask 中使用 getSupportFragmentManager()。 我尝试使用上下文或 activity,但无法正常工作。
我收到此错误无法解析方法 getSupportFragmentManager()

AsyncTask.java:

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.support.v4.app.FragmentManager;
    import android.util.Log;
    import android.view.View;
    import android.widget.ProgressBar;
    import android.widget.Toast;


    public class AsyncTask extends AsyncTask<Void, Void, String> {
        private Context c;
        private String urlAddress;
        private String token;
        private DatabaseHelper db;
        private Activity mainActivity;

        public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
            this.c = c;
            this.db = databaseHelper;
            this.urlAddress = urlAddress;
            this.mainActivity = activity;
            //GET token FROM database
            this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
        }

        @Override
        protected String doInBackground(Void... params) {
            return this.send();
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);
            if (response != null) {
                //SUCCESS
mainActivity.getSupportFragmentManager().beginTransaction()
                    .add(R.id.content_frame
                            , new SessionsFragment())
                    .addToBackStack("back")
                    .commit();
            } else {
                //NO SUCCESS

            }
        }

        private String send() {
            //CONNECT
            HttpURLConnection connection = Connector.connect(urlAddress);
            if (connection == null) {
                return null;
            }
            try {
                OutputStream outputStream = connection.getOutputStream();
                //WRITE
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                bufferedWriter.write(new DataPackager(token).packData());
                bufferedWriter.flush();
                //RELEASE RES
                bufferedWriter.close();
                outputStream.close();
                //HAS IT BEEN SUCCESSFUL?
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    //GET EXACT RESPONSE
                    InputStream stream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                    StringBuilder buffer = new StringBuilder();
                    String line;
                    //READ LINE BY LINE
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line);
                    }
                    String finalJson = buffer.toString();

                    JSONObject parentObject = new JSONObject(finalJson);
                    JSONObject secondParentObject = parentObject.getJSONObject("data");


                    //json getter and adder to database
                    JSONArray array = secondParentObject.getJSONArray("s");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject finalObject = array.getJSONObject(i);
                        db.SessionsAddJson(finalObject);
                        //RELEASE RES
                        reader.close();
                    }

                    return "c";
                } else {

                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }
            return null;
        }
    }

我通过以下方式调用任务:

new $AsyncTask(getApplicationContext(), db, URL, MyActivity.this).execute();

感谢您的帮助。

你的 activity 应该是 AppCompatActivity 而不是 Activity

试试这个

getActivity().getFragmentManager().beginTransaction()
                .add(R.id.content_frame
                        , new Fragment())
                .addToBackStack("back")
                .commit();

更新:

你应该在构造函数中传递 AppCompatActivity,像这样:

替换 private Activity mainActivity;private AppCompatActivity mainActivity; 另外当你使用它时:更换 new $AsyncTask(getApplicationContext(), db, URL).execute();new $AsyncTask(getApplicationContext(), db, URL, YourCurrentActivity.this).execute(); 请注意 YourCurrentActivity 应该 extends AppCompatActivity

你只是把 AppCompatActivityActivity 搞混了。 Activity 没有 getSupportFragmentManager(),但是 AppCompatActivity 有这个。

如果您使用的是异步任务 class 那么要加载您需要上下文的片段,即特定 activity.

的上下文

因此,将上下文类型转换为要加载片段的相应 activity,并使用特定的 activity fragmentManager 加载片段。

public class sampleAsyncTask extends AsyncTask<Void, Void, Void> {

private YourActivity mActivity;

@Override
protected Void doInBackground(Void... voids) {
    return null;
}

public sampleAsyncTask(Context context) {
    super();
    activity = (YourActivity) context;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    mActivity.getSupportFragmentManager().beginTransaction()
            .add(R.id.content_frame
                    , new Fragment())
            .addToBackStack("back")
            .commit();
}
}

编辑:

在这行代码中,不是将 activity 的通用引用存储为特定的 activity,即您当前的 activity.

private YOURACTIVITY mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
        this.c = c;
        this.db = databaseHelper;
        this.urlAddress = urlAddress;

        //TypeCast to your particular activity
        mainActivity =(YOURACTIVITY) activity;

        this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
    }