在执行后

时间:2015-06-23 01:46:38

标签: android android-fragments android-asynctask

我有一个调用异步任务的片段。异步任务完成后,我希望片段完全重新加载。

基本上,我的片段会加载随机评论。然后,用户使用底部的星形条评价评论。当他们点击星形条时,异步任务会运行将评级提交到我的数据库。一旦提交,我想要加载另一个评论。

我的异步代码如下所示:

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

    Context c;

    public AddNoteRate(Context context)
    {
        c = context;
    }

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

    protected void onPostExecute(String result){

        Fragment Fragment_three;
        FragmentManager man= c.getFragmentManager();
        FragmentTransaction tran = man.beginTransaction();
        Fragment_three = new RateReviews();
        tran.replace(R.id.main, Fragment_three);//tran.
        tran.addToBackStack(null);
        tran.commit();




    }

    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= c.getFragmentManager();

1 个答案:

答案 0 :(得分:1)

getFragmentManager()Activity的方法,而不是Context

由于你可能传递Activity作为context参数,你可以通过以下方式解决这个问题:

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

但从长远来看,最佳做法是直接将ActivityFragmentManager作为参数传递给AsyncTask