传递数据后启动片段

时间:2015-10-09 17:47:45

标签: android android-fragments tabactivity

我创建了一个包含3个片段的Tabbed Activity。在fragmentA我从互联网上下载数据(带有3个AsyncTask),我在fragmentB中传递了一些数据(静态字符串和静态字符串),但是我遇到了问题。 当Tabbed Activity启动时,FragmentB启动。我希望FragmentB在FragmentA结束后启动。

我该怎么办?

感谢

抱歉我的英文

编辑:Code FragmentA

public class P2 extends android.support.v4.app.Fragment {
View rootview;

static ArrayList<String> people10 = new ArrayList<String>();
static ArrayList<String> people12= new ArrayList<String>();
  static String nomedapassare;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.activity_parla, container,false);


    Intent intent = getActivity().getIntent();
    String pkg = getActivity().getPackageName();
    Integer valore = intent.getIntExtra(pkg + ".myInt", -1);
    String parla= valore.toString();
    String url4 = url3 + parla



    if (isOnline()) {

        ApplicationSimpleAsyncTask3 asyncTask3 = new ApplicationSimpleAsyncTask3();
        asyncTask3.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, url4);
         ApplicationSimpleAsyncTask2 asyncTask2 = new ApplicationSimpleAsyncTask2();
        asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url2);
        ApplicationSimpleAsyncTask asyncTask = new ApplicationSimpleAsyncTask();
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);


    } else {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Attenzione!");
        builder.setCancelable(false);
        builder.setMessage("Connesione non più presente. Si prega di attivarla nuovamente!");
                  builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                getActivity().finish();
            }

        });
        builder.show();
    }

    return rootview;
}


public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = cm.getActiveNetworkInfo();

    if (ni == null)
        return false;

    return ni.isConnected();
}







public class ApplicationSimpleAsyncTask extends
        AsyncTask<String, String, Document> {

    private final ProgressDialog dialog0 = new ProgressDialog(
            getActivity());

    protected void onPreExecute() { ...

    }

    protected Document doInBackground(String... valore) {
        url = valore[0];

        try {
            doc = Jsoup.connect(url).timeout(0).get();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return doc;
    }


    protected void onPostExecute(final Document doc) {

        try {
            if (this.dialog0.isShowing()) {
                this.dialog0.dismiss();
            }

           ...


           ArrayList<String> people = new ArrayList<String>();

            ArrayList<String> people2 = new ArrayList<String>();

            ...

            for (Element link : sitoVoto) {
                String linkHref = link.attr("href");
                people2.add(linkHref);

            }
            for (Element e : voti) {
                people.add("\n" + e.text() + "\n");
            }

            people10=people;
            people12=people2;





        } catch (Exception e) {...

        }

    }

}

}

我在FragmentB中传递了10个人12但是如果asyntask更快,我在FragmentB中什么也看不到。如果asyntask很慢,我会在FragmentB中看到arraylist

EDIT2:FragmentB

public class V0 extends Fragment {
View rootview;
Document doc = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview=inflater.inflate(R.layout.activity_voti_chiave,container,false);
    Intent intent = getActivity().getIntent(); // l'intent di questa activity
    String pkg = getActivity().getPackageName();
    Integer valore = intent.getIntExtra(pkg + ".myInt", -1);
    String parla = valore.toString();


    ListView listView = (ListView) rootview.findViewById(R.id.listView1);
    final TextView textview = (TextView) rootview.findViewById(R.id.textView20);



    if (isOnline()) {
        ApplicationSimpleAsyncTask asyncTask = new ApplicationSimpleAsyncTask();
        asyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, sito);


    } else {
        ApplicationSimpleAsyncTask asyncTask = new ApplicationSimpleAsyncTask();
        asyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, sito);
    }



    return rootview;
}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = cm.getActiveNetworkInfo();

    if (ni == null)
        return false;

    return ni.isConnected();
}
public class ApplicationSimpleAsyncTask extends
        AsyncTask<String, String, Document> {

    private final ProgressDialog dialog0 = new ProgressDialog(
            getActivity());

    protected void onPreExecute() {

    }

    protected Document doInBackground(String... valore) {
                return doc;
    }


    protected void onPostExecute(final Document doc) {

        try {


            ListView listView = (ListView) rootview.findViewById(R.id.listView1);
            final TextView textview = (TextView) rootview.findViewById(R.id.textView20);



            String text = "Ecco come ha votato " + P2.nomedapassare
                    + " nelle votazioni più importanti della legislatura";

            textview.setText(text);

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                        getActivity(), R.layout.textview, P2.people10);
                listView.setAdapter(adapter);



            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                        long arg3) {
                    Intent newActivity = new Intent(getActivity(),
                            Esito.class);
                    String pkg = getActivity().getPackageName();
                    newActivity.putExtra(pkg + ".Nome", P2.people12.get(arg2));
                    startActivity(newActivity);

                }
            });




        } catch (Exception e) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Attenzione!");
            builder.setCancelable(false);
            builder.setMessage("Connesione non più presente. Si prega di attivarla nuovamente!");
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    getActivity().finish();
                }

            });
            builder.show();
            e.printStackTrace();
        }
    }
}}

这里我无法删除AsyncTask,否则应用程序崩溃,但在这个片段中我不想从互联网上下载数据

2 个答案:

答案 0 :(得分:0)

最常见的方法是:

在“活动”中,您可以创建方法

void onDataReceived(String someData, ArrayList someMoreData)
{
    fragmentB.updateData(someData, someMoreData);
}

最好将此方法移至界面,让我们将其称为IDataReceiver,然后让您的活动实现此界面。

fragmentA中,您需要获得对界面的引用,这样做的好地方是onAttach()

IDataReceiver receiver = (IDataReceiver)getActivity();

然后当您在AsyncTasks中获取数据时,您只需在此界面上调用该方法,它就会将数据提供给您的第二个片段,您可以在其中填充您的视图。

要在活动中获取fragmentB的引用,您可以使用名为FragmentManagerfindFragmentById的{​​{1}}类的方法

答案 1 :(得分:0)

  1. 首先再创建一个Fragment B类,您可以将其命名为其他内容,例如&#34; fragment_B_static&#34;。删除所有代码,只留下onCreateView()方法,实际上是用于访问布局。
  2. 在片段A中,创建类似&#34; startFragmentB(列表列表)&#34;

    的方法
    private void startFragmentB(List<String> list){
      Bundle bundle = new Bundle();
            bundle.putStringArrayList("myList", new ArrayList<>(list));
               Fragment fragment = new FragmentB();
               fragment.setArguments(bundle);
               FragmentTransaction ft =  getFragmentManager().beginTransaction()
              ft.replace(R.id.your_placeholder, fragment);
              ft.commit();
        }
    
  3. 片段内部A.在onPostExecute()方法中,最后可以调用此方法startFragmentB(people10);

    4.Inside FragmentB.class,执行此操作,

  4. @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        List<String> list = getArguments().getStringArrayList("myList");
    
    }