0

I have an Activity which has a Navigation Drawer that has many buttons and one of them is leading to a fragment.
The problem is that I have to make an AsyncTask to get some information from the server but I can't get to use getSupportFragmentManager() inside the AsyncTask. I tried to use context or activity but I can't get it to work.
I get this error cannot resolve method 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;
        }
    }

I call the task by:

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

Thank you for your help.

Zacktamondo
  • 1,891
  • 3
  • 17
  • 33

4 Answers4

1

Your activity should be AppCompatActivity not Activity

shmakova
  • 6,076
  • 3
  • 28
  • 44
1

Upd.:

You should pass the AppCompatActivity in constructor, like this:

Replace private Activity mainActivity; with private AppCompatActivity mainActivity; Also when you use it: replace new $AsyncTask(getApplicationContext(), db, URL).execute(); with new $AsyncTask(getApplicationContext(), db, URL, YourCurrentActivity.this).execute(); Notice that YourCurrentActivity should extends AppCompatActivity.

You just confuse AppCompatActivity with Activity. Activity haven't getSupportFragmentManager(), but AppCompatActivity have this.

Hetfieldan24
  • 198
  • 11
  • Please, post your AsyncTask code completely. And the part of the code where you use AsyncTask. – Hetfieldan24 Sep 20 '17 at 12:31
  • What exactly does not work? If you did everything as I wrote, you can not have this error: "cannot resolve method 'getsupportfragmentmanager()'", because of AppCompatActivity have this. – Hetfieldan24 Sep 20 '17 at 12:35
  • 1
    Try to replace 'private Activity mainActivity;' with 'private AppCompatActivity mainActivity;' Also when you use it: replace 'new $AsyncTask(getApplicationContext(), db, URL).execute();' with 'new $AsyncTask(getApplicationContext(), db, URL, YourCurrentActivity.this).execute();' Notice that YourCurrentActivity should extends AppCompatActivity. – Hetfieldan24 Sep 20 '17 at 12:50
  • 1
    You just confuse AppCompatActivity with Activity. Activity haven't getSupportFragmentManager(), but AppCompatActivity have this. – Hetfieldan24 Sep 20 '17 at 12:55
  • It worked thank you please edit your answer or post a new one so I can accept it. – Zacktamondo Sep 20 '17 at 12:59
1

If you are using an asyntask class then to load fragment you need context,i.e context of particular activity.

So typecast the context to the respective activity where you want to load the fragment and onPostExecute load the fragment using particular 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();
}
}

EDIT:

In this line of code instead of storing generic reference of activity typecast to particular activity i.e your current 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());
    }
Sharath kumar
  • 4,064
  • 1
  • 14
  • 20
0

try this

getActivity().getFragmentManager().beginTransaction()
                .add(R.id.content_frame
                        , new Fragment())
                .addToBackStack("back")
                .commit();
umesh vashisth
  • 339
  • 3
  • 16