trying to launch a fragment from an async task

给你一囗甜甜゛ 提交于 2019-12-23 04:29:39

问题


I have an async task which is called for a fragment and populates a listview. When I try and set the OnClick for the listview I get an error in my code for setting the fragment to load based on the listview item clicked:

 FragmentManager man= getFragmentManager();
                        FragmentTransaction tran=man.beginTransaction();
                        Fragment_one = new StylePage2();
                        final Bundle bundle = new Bundle();
                        bundle.putString("beerIDSent", bID);
                        Fragment_one.setArguments(bundle);
                        tran.replace(R.id.main, Fragment_one);//tran.
                        tran.addToBackStack(null);
                        tran.commit();

The error shows for the line:

FragmentManager man= getFragmentManager();

The error is, can not resolve method getFragmentManager()

I am assuming you can only access that method from within a fragment, so I am a bit lost on how to launch it from something that extends asynctask.

The full code for the async task is below:

public class GetStyleStatisticsJSON extends AsyncTask<String, Void, String> {

    Context c;
    private ProgressDialog Dialog;


    android.support.v4.app.Fragment Fragment_one;

    public GetStyleStatisticsJSON(Context context)
    {
        c = context;
        Dialog = new ProgressDialog(c);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Analyzing Statistics");

        Dialog.setTitle("Loading");
        Dialog.setCancelable(false);
        Dialog.show();
    }

    protected void onPostExecute(String result){
        //decode json here
        try{
            JSONArray jsonArray = new JSONArray(result);


            //acces listview
            ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourStyleStatistics);

            //make array list for beer
            final List<StyleInfo> tasteList = new ArrayList<StyleInfo>();



            for(int i = 0; i < jsonArray.length(); i++) {

                String style = jsonArray.getJSONObject(i).getString("style");
                String rate = jsonArray.getJSONObject(i).getString("rate");
                String beerID = jsonArray.getJSONObject(i).getString("id");

                int count = i + 1;

                style = count + ". " + style;


                //create object
                StyleInfo tempTaste = new StyleInfo(style, rate, beerID);

                //add to arraylist
                tasteList.add(tempTaste);


                //add items to listview
                StyleInfoAdapter adapter1 = new StyleInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
                lv.setAdapter(adapter1);

                //set up clicks
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        StyleInfo o=(StyleInfo)arg0.getItemAtPosition(arg2);

                        String bID = o.id;

                        //todo: add onclick for fragment to load
                        FragmentManager man= getFragmentManager();
                        FragmentTransaction tran=man.beginTransaction();
                        Fragment_one = new StylePage2();
                        final Bundle bundle = new Bundle();
                        bundle.putString("beerIDSent", bID);
                        Fragment_one.setArguments(bundle);
                        tran.replace(R.id.main, Fragment_one);//tran.
                        tran.addToBackStack(null);
                        tran.commit();



                    }
                });


            }

        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

UPDATE

I tried changing it to this:

FragmentManager man = ((Activity) c).getFragmentManager();

BUt I am getting this error:

Incompatible types.
Required:
android.support.v4.app.FragmentManager
Found:
android.app.FragmentManager

Update 2

I just tried this:

FragmentManager man= MainDraw.getFragmentManager();

and get this error:

Non-static method 'getFragmentManager()' cannot be referenced from a static context

回答1:


It is very good practice to always create fragments from the holding activity only, so in this case what you would do is create a callback (interface) in your onclick to your activity that would create the fragment just like you would if you needed to communicate with your activity from your fragment.

doing this will fix your problem because Activity has getFragmentManager()

EDIT

OnArticleSelectedListener listener;

public interface OnArticleSelectedListener{
    public void onArticleSelected(/*whatever you want to pass in it*/);
}

in your GetStyleStatisticsJSON create a method that sets the listener

public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
   this.listener = listener;
}

then in your onClick just call it

listener.onArticleSelected();

then declare your asynctask like this

GetStyleStatisticsJSON task = new GetStyleStatisticsJSON(getActvity());
task.setOnArticleSelectedListener(new OnArticleSelectedListener(){
    @Override
    public void onArticleSelected(){

    }
});
task.execute(url)



回答2:


Using

FragmentManager man= YourActivity.getFragmentManager();

instead of

FragmentManager man= getFragmentManager();



来源:https://stackoverflow.com/questions/21716402/trying-to-launch-a-fragment-from-an-async-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!