【问题标题】:trying to launch a fragment from an async task尝试从异步任务启动片段
【发布时间】:2014-02-12 00:46:43
【问题描述】:

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

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

但我收到此错误:

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

【问题讨论】:

  • 不知道行不行...不过你可以试试把Activity传给AsynkTask。然后,当您想要启动片段时,请从您的 AsynkTask 中的活动实例执行此操作,就像这样: ((CustomActivity) myActivityInstance).methodtolaunchthefragment()... 如果可行,请告诉我。
  • 其他选项是使用 myActivityInstance 调用 getFragmentManager()。之前...
  • Android 在 Android 3.0(API 级别 11)中引入了 Fragment,因此如果您支持 API 级别 developer.android.com/reference/android/support/v4/app/…
  • 卢西亚诺罗德里格斯,我不完全理解你想说什么。这可能有点超出我的 Java 水平

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


【解决方案1】:

始终只从持有活动创建片段是非常好的做法,因此在这种情况下,您要做的是在您的 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();

然后像这样声明你的异步任务

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

    }
});
task.execute(url)

【讨论】:

  • 我不应该能够在我的异步任务中做一些事情,因为我在调用时将活动传递给异步任务:new GetStyledataJSON(getActivity()).execute(url);跨度>
  • 确定您是否将其保留为活动,但您将 getActivity() 用作 context 仅不会为您做任何事情。如果你保持活动,你可以做activity.getFragmentManager(),但就像我说的那样,这不是片段管理的好习惯
  • 查看我的更新,我想我可能会找到一些东西。但是又遇到了一个小错误。
  • 你需要acivity.getSupportFragmentManager()
  • 试图了解如何实现这一点,我可以对代码有一点帮助吗? public interface OnArticleSelectedListener { //在此处添加点击代码 } 然后从我的异步任务中调用该方法?
【解决方案2】:

使用

FragmentManager man= YourActivity.getFragmentManager();

而不是

FragmentManager man= getFragmentManager();

【讨论】:

  • 刚刚尝试过,又出现了一个错误,请检查上面我编辑的主帖中的更新 2
  • 和更新一样,android.app.FragmentManager和android.app.Fragment都可以使用。如果使用android.support.v4.app.Fragment,则不能使用tag .
  • @Mike 和更新一样,都可以使用android.app.FragmentManager 和android.app.Fragment。如果使用android.support.v4.app.Fragment,则不能使用tag 并且你应该扩展 FragmentActivity 然后你可以使用 getSupportFragmentManager().
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
相关资源
最近更新 更多