尝试从异步任务启动片段

时间:2014-02-12 00:46:44

标签: android android-listview android-fragments android-asynctask

我有一个异步任务,它被调用一个片段并填充一个listview。当我尝试为列表视图设置OnClick时,我的代码中出现错误,根据单击的listview项设置要加载的片段:

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

该行显示错误:

FragmentManager man= getFragmentManager();

错误是,无法解析方法getFragmentManager()

我假设你只能从一个片段中访问该方法,所以我对如何从扩展asynctask的东西启动它有点迷失。

异步任务的完整代码如下:

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

}

更新

我尝试将其更改为:

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

BUt我收到此错误:

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

更新2

我刚试过这个:

FragmentManager man= MainDraw.getFragmentManager();

并收到此错误:

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

2 个答案:

答案 0 :(得分:3)

总是只从保持活动创建片段是非常好的做法,所以在这种情况下你要做的就是在你的onclick中为你的活动创建一个回调(接口)来创建片段,就像你想象的那样需要通过片段与您的活动进行沟通。

执行此操作可以解决您的问题,因为ActivitygetFragmentManager()

修改

OnArticleSelectedListener listener;

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

GetStyleStatisticsJSON中创建一个设置侦听器的方法

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

然后在你的onClick上调用它

listener.onArticleSelected();

然后声明你的asynctask就像这样

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

    }
});
task.execute(url)

答案 1 :(得分:0)

使用

  

FragmentManager man = YourActivity.getFragmentManager();

而不是

  

FragmentManager man = getFragmentManager();