Start fragment after pass data

119 Views Asked by At

I created a Tabbed Activity with 3 fragments. In fragmentA I download data from internet (with 3 AsyncTask) and i pass some data (static string and static arraylist) in fragmentB but I have a problem. FragmentB start when Tabbed Activity start. I want that FragmentB starts after FragmentA ends.

How can i do?

thanks

Sorry for my english

EDIT: 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) {...

        }

    }

}

}

I pass people10 e people12 in FragmentB but if asyntask is more fast I don't see nothing in FragmentB. While if asyntask is slow I see arraylist in FragmentB

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

Here I can not erase AsyncTask otherwise the app crashes, but in this fragment I don't want to download data from internet

2

There are 2 best solutions below

7
TpoM6oH On

The most common way to do it is:

In Activity you create a method

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

Preferably you move this method to an interface, let's call it IDataReceiver, and you make your activity implement this interface.

In fragmentA you need to get a reference to the interface, good place to do it is onAttach():

IDataReceiver receiver = (IDataReceiver)getActivity();

And then when you get the data in AsyncTasks you just call the method on this interface and it will give the data to your second fragment, where you populate your views.

To get the reference to fragmentB in the activity you can use methods of FragmentManager class called findFragmentById or findFragmentByTag

2
Vivek Kumar On
  1. First Create a one more Fragment B class, you can name it something else as for example "fragment_B_static". Remove all codes, leave only onCreateView() methods and which is actually for accessing layout.
  2. In Fragment A, create a method something like "startFragmentB(List list)"

    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. Inside Fragment A . in onPostExecute() method, in the end you can call this method, startFragmentB(people10);

    4.Inside FragmentB.class, do this,

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    List<String> list = getArguments().getStringArrayList("myList");

}