6

I am creating the fragment dynamically without xml file now i want to call the method inside the fragement from parent activity so how can i do it can any body know about it , i found lots of question but they are doing with xml

Fragmentactivity

 public class HomeActivity extends FragmentActivity implements OnClickListener {

        public static final String TAG = HomeActivity.class.getSimpleName();
        PageIndicator mIndicator;
        //Spinner spinner1;
        ImageView serversetting,dropdown;
        TextView selectrange;
        int num,counter=0;
        String url,apiUser,apipass,TestAccount;
       /* public static HomeActivity newInstance() {
        return new HomeActivity();
        }*/

        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_parent);
        ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
        selectrange=(TextView)findViewById(R.id.selectrange);
        serversetting=(ImageView)findViewById(R.id.settingsserver);
        dropdown=(ImageView)findViewById(R.id.dropdown);
        mViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
        mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
        mIndicator.setViewPager(mViewPager);

        selectrange.setOnClickListener(this);
        dropdown.setOnClickListener(this);
        serversetting.setOnClickListener(this);

        /*spinner1 = (Spinner) findViewById(R.id.spinner1);
        List<String> list = new ArrayList<String>();
        list.add("Current Month");
        list.add("Last Month");
        list.add("Last 5 Days");
        list.add("Last 10 Days");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            R.layout.spinner_layout,R.id.spinnerTarget,list);
        //dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        serversetting.setOnClickListener(this);
        spinner1.setAdapter(dataAdapter);
        spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos,
                    long id) {
                // TODO Auto-generated method stub
                Toast.makeText(parent.getContext(), 
                        "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });*/
        }


        public class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public Fragment getItem(int position) {
           /* Bundle args = new Bundle();
            args.putInt(TextViewFragment.POSITION_KEY, position);
            return TextViewFragment.newInstance(args);*/
            Fragment f=new Fragment();  
            switch(position) {
                case 0:
                    f= new SalesGraphFragment();

                    break; 
                case 1:
                    f=new OrderGraphFragment();
                    break;
                case 2:
                    f=new UserGraphFragment();
                    break; 
            }
            return f;
        }


        /*@Override
        public CharSequence getPageTitle(int position) {
            return "Fragment # " + position;
        }*/

        }

        @Override
        protected void onStart()
        {
         super.onStart();   
         EasyTracker.getInstance().activityStart(this);
        }

        @Override
        protected void onStop()
        {
         super.onStop();
         EasyTracker.getInstance().activityStop(this);
        }

        void SelectRangeDialog()
        {
        final CharSequence[] list = {"All time","Current Month","Last Month","Today","YesterDay"};
        AlertDialog.Builder alert = new AlertDialog.Builder(HomeActivity.this);

        if(counter==0)
        {
         num=1;
         counter++;
        }

        alert.setTitle("Range");
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
                dialog.dismiss();



                //selectrange.setText(list[which]);
        //      new ChangeStatusAsync().execute();
            }
        });
        /*if(status.equals("Order Pending"))
            num=0;
        else if(status.equals("Upfront Received"))
            num=1;
        else if(status.equals("Payment Complete"))
            num=2;*/
        alert.setSingleChoiceItems(list,num, new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                //newstatus=list[which].toString(); 
                 selectrange.setText(list[which]);
                 num=which;
            }
        });
        alert.show();
      }


        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
            case R.id.settingsserver:
                 Intent settings=new Intent(HomeActivity.this,SettingsActivity.class);
                 startActivity(settings);
                break;

            case R.id.selectrange:
                SelectRangeDialog();
                break;

            case R.id.dropdown:
                SelectRangeDialog();

                break;

            default:
                break;
            }

        }

    }

Fragment

public class SalesGraphFragment extends Fragment {

    public static final String POSITION_KEY = "com.burnside.embeddedfragmenttest.POSITION";
    public static final String TITLE_KEY = "com.burnside.embeddedfragmenttest.TITLE";
    Object saleData[];
    String strSales="";
    TextView txt;
    public  Object b;
    List array;
    public  Object [] objects;
    public static SalesGraphFragment INSTANCE;
    LinearLayout layout;
    String sessionId,url,amount,apiUser,apipass,TestAccount;
    MagentoStoreLogin sales=new MagentoStoreLogin();
    public ProgressDialog order_dialog;
    public static SalesGraphFragment newInstance(Bundle args) {
    SalesGraphFragment fragment = new SalesGraphFragment();
    fragment.setArguments(args);
    ProgressDialog order_dialog; 
    return fragment;
    }

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

    try{
        TestAccount=getActivity().getIntent().getExtras().getString("TestAccount");
        if(TestAccount==null)
            TestAccount="";
        if(TestAccount.equals("TestAccount"))
        {
            url =getActivity().getIntent().getExtras().getString("defaulturl");
            apiUser=getActivity().getIntent().getExtras().getString("defaultapiuser");
            apipass=getActivity().getIntent().getExtras().getString("defaultapipass");

                System.out.println(url + apipass + apiUser);


        }
        else
         {
          url=PreferenceConnector.readString(getActivity(),PreferenceConnector.URL, null);
          System.out.println("URL is:"+url);
          apiUser=PreferenceConnector.readString(getActivity(),PreferenceConnector.APIUSER, null);
          apipass=PreferenceConnector.readString(getActivity(),PreferenceConnector.APIPASS, null);  
          new saleDetail().execute();
          new GraphValue().execute();
          System.out.println(url + apipass + apiUser);
         }
            if(url!=null&&url!="")
            { 
                //Load the first 12 items
            //  counter=0;


             }
            else
            {
              Toast.makeText(getActivity(),"Please do the API settings first", 1).show();
            }


        }
        catch(Exception e)
        {
            Toast.makeText(getActivity(),"Please do the settings first Exception", 1).show();
        //   uName.setText("");
        //   password.setText("");
        }
      }

    public static SalesGraphFragment getSaleInstance() 
    {
        return INSTANCE;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         setHasOptionsMenu(true);
    return inflater.inflate(R.layout.sales_fragment, container, false);



    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if(!TestAccount.equals("TestAccount"))
    {
    GraphViewSeries exampleSeries = new GraphViewSeries(new GraphViewData[] {
            new GraphViewData(5, 2.0d)
            , new GraphViewData(4, 1.0d)
            , new GraphViewData(3, 3.0d) // another frequency
            , new GraphViewData(2, 2.0d)
            , new GraphViewData(1, 1.0d)
            , new GraphViewData(0, 6.0d)
    });

    // graph with dynamically genereated horizontal and vertical labels
    GraphView graphView;

        graphView = new LineGraphView(
                getActivity() // context
                , "" // heading
        );
    graphView.addSeries(exampleSeries); // data

//  LinearLayout layout = (LinearLayout) findViewById(R.id.graph1);
//  layout.addView(graphView);

    // graph with custom labels and drawBackground


        ((LineGraphView) graphView).setDrawBackground(true);
    // custom static labels
//  graphView.setHorizontalLabels(new String[] {"2 days ago", "yesterday", "today", "tomorrow"});
//  graphView.setVerticalLabels(new String[] {"high", "middle", "low"});
    //graphView.addSeries(exampleSeries); // data
    //graphView.setViewPort(2, 5);
    //graphView.setBackgroundColor(Color.WHITE);
//  graphView.set
    layout = (LinearLayout) view.findViewById(R.id.salesgraph);
    txt=(TextView) view.findViewById(R.id.salesamount);


    txt.setText(getData());
    layout.addView(graphView);
    }
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Add your menu entries here
         inflater.inflate(R.menu.optionmenus, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    // Handle click events
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {

       case R.id.aboutus:
          Intent aboutus=new Intent(getActivity(),AboutUs.class);
          startActivity(aboutus);
              return true;

       case R.id.settings:
            Intent settings=new Intent(getActivity(),SettingsActivity.class);
            startActivity(settings);
                return true;

       default:
          return super.onOptionsItemSelected(item);
    }
    }


    public String getData()
    {

        return strSales;
    }
    public void setSessionId(String sessionId)
    {
     this.sessionId=sessionId;            
    }
    public class saleDetail extends AsyncTask<Void,Integer,Object> 
    {

        ProgressBar progressBar;

        @Override
       protected Object doInBackground(Void... params) {

              try 
              { if(sessionId==null)

                {   
                    sessionId=sales.login(url, apiUser, apipass);
                    setSessionId(sessionId);
                }

                   b=sales. getSaleInfo(sessionId,url);


            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("Getting Order Error:"+e.getMessage());

            //customer_results=null;
            }
        //}

            return b;



     }
       @Override
       protected void onPreExecute() 
           {    
            order_dialog = ProgressDialog.show(getActivity(),"Getting Sales Information...", "Please wait while loading", true);
           }

       protected void onPostExecute(final Object object) 
      {    

           order_dialog.dismiss();

           if(object!=null)
           {
           System.out.println("Dismiss Called");
           Map<String, Double> mappedData=(Map)object;
            Double sales=mappedData.get("Total Sale");

            double finalValue = Math.round( sales * 100.0 ) / 100.0;

            strSales=""+finalValue;
            txt.setText(finalValue+"");
           //setData(object);

          }
          else
          {
              Toast.makeText(getActivity(),"You Dont have our package", 10).show();

         }
      }
}

    public class GraphValue extends AsyncTask<Void,Integer,Object[]> 
    {

        ProgressBar progressBar;

        @Override
       protected Object[] doInBackground(Void... params) {

              try 
              { if(sessionId==null)

                {   
                    sessionId=sales.login(url, apiUser, apipass);
                    setSessionId(sessionId);
                }

                   objects=sales.getGraphValue(sessionId,url);


            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("Getting Order Error:"+e.getMessage());

            //customer_results=null;
            }
        //}

            return objects;



     }
       @Override
       protected void onPreExecute() 
           {    
        //  order_dialog = ProgressDialog.show(getActivity(),"Getting Sales Information...", "Please wait while loading", true);
           }

       protected void onPostExecute(final Object object[]) 
      {    

         //  order_dialog.dismiss();

         //  System.out.println("Data length is:"+object.length);
          // System.out.println("Dismiss Called");
           for(Object obj:object)
           {
               extractDate(obj);
           }

      }
    private void extractDate(Object obj) {
        // TODO Auto-generated method stub


            Map map=(Map)obj;

            System.out.println(map.get("getCreatedAt"));



        }


    }



}
UnderGround
  • 450
  • 1
  • 3
  • 17
  • 1
    please add code..you prob need to use a listener to communicate between activity and fragment, but have to see your code. – Dory Zidon Jun 03 '13 at 12:42
  • current code sample? can't FragmentManager get your fragment by id or tag? – donfede Jun 03 '13 at 12:44
  • yes but the proper way is not to just cast it and call it but to use interfaces to de-couple of the fragment from the activity.. – Dory Zidon Jun 03 '13 at 12:47

4 Answers4

19
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_holder);
if (fragment instanceof MyFragment)
    ((MyFragment) fragment).myFragmentMethod();
Ken Wolf
  • 23,133
  • 6
  • 63
  • 84
  • it give Incompatible conditional operand types Fragment and SalesGraphFragment – UnderGround Jun 03 '13 at 13:38
  • `SalesGraphFragment` extends `Fragment` right? Make `Fragment fragment` is the same `Fragment` class as there are 2: `android.support.v4.app.Fragment` and `android.app.Fragment`. You need to use the same one you used in `public class SalesGraphFragment extends Fragment` – Ken Wolf Jun 03 '13 at 13:51
  • yes i have change to android.support.v4.app.Fragment to both but stil getting error – UnderGround Jun 03 '13 at 13:56
  • Well incompatible types just means that your SalesGraphFragment somehow doesn't inherit from the Fragment in your `instanceof` line. Fix that and it will work. (http://stackoverflow.com/questions/2551337/instanceof-incompatible-conditional-operand-types) – Ken Wolf Jun 03 '13 at 13:59
  • android.support.v4.app.Fragment fragment =getFragmentManager().findFragmentById(R.id.salesgraph); i am getting that error here – UnderGround Jun 03 '13 at 14:02
  • Change it to `Android.app.Fragment fragment`. Also the id needs to be the id of your fragment holder – Ken Wolf Jun 03 '13 at 14:03
  • but i so that i have to increase my api level and i have to support min 8 api – UnderGround Jun 03 '13 at 14:04
  • what i actually want to do is that when my spinner change in the activity it would change the graph or update the graph – UnderGround Jun 03 '13 at 14:15
  • I'm sorry, I'm not familiar with your method of adding fragments, I thought they were added dynamically like this: (http://stackoverflow.com/questions/7849490/android-adding-fragments-dynamically). I'm unable to help further. Good luck – Ken Wolf Jun 03 '13 at 14:20
7

If at all you are using ViewPager to render the fragment use this code in your parent Activity.

if(viewPager.getCurrentItem() == 1) //First fragment
{
     FragmentOne frag1 = (FragmentOne)viewPager.getAdapter().instantiateItem(viewPager, viewPager.getCurrentItem());
     frag1.edittext1.setText(phone);
}
else if(viewPager.getCurrentItem() == 2) //Second fragment
{
     FragmentTwo frag2 = (FragmentTwo)viewPager.getAdapter().instantiateItem(viewPager, viewPager.getCurrentItem());
     frag2.edittext2.setText(phone);
}
Naveen T P
  • 6,955
  • 2
  • 22
  • 29
2

I would create a new abstract class that extends Fragment.

SalesGraphFragment, OrderGraphFragment and UserGraphFragment would extend this new class and they would implement the method that you want to call from the activity.

From the activity, you can call this method in this way :

adapter.getItem(X).myMethod();

SJSSoft
  • 723
  • 2
  • 10
  • 28
Alex248
  • 427
  • 4
  • 15
1

well in some cases, in special when defined with XML... then this would be:

        [your fragment class here] blabla =( [your fragment class here])getSupportFragmentManager()

 .findFragmentById(R.id.myfragment_id);

 blabla.method_x();
Miguel
  • 3,349
  • 2
  • 32
  • 28