0

It may be dumb question but am struggling with this how to pass value between activity and viewpager. Now let me explain my requirement i have two tabs namely task and calls . Having one button in task when user press that it will go to new activity from there will be two forms one is edittext and spinner need to populate listview in task fragment from that activity data so far what i have tried is:

This is my Main activity:

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        //  Bundle bundle=getIntent().getExtras();
        // Intent intent=getIntent();
        //   ActivityView activityView=(ActivityView)intent.getSerializableExtra("yog");
        //     intent.putExtra("yogs",activityView);
        // Bundle bundle=new Bundle();
        // bundle.putSerializable("yogs",activityView);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String yogan = bundle.getString("yog");
            String yogans = bundle.getString("yogs");
            Bundle bundle1 = new Bundle();
            bundle.putString("yoges", yogan);
            bundle.putString("yogesh", yogans);
            Task task = new Task();
            task.setArguments(bundle1);


        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
                switch (position){
                    case 0:
                            Task task=new Task();
                            return task;

                    case 1:
                            Calls calls=new Calls();
                            return calls;

                }
        return null;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
           switch (position){
               case 0:
                   return "Task";
               case 1:
                   return "Call";

            }
        return null;
            }

        }
    }

This is my task fragment(where listview is gets populated)

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;
public class Task extends Fragment
{
    List<ActivityView>activityViews;
    ActivityView activityView=new ActivityView();
    ActivityListAdapter activityListAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootview= inflater.inflate(R.layout.yog,container,false);
        ListView listview=(ListView)rootview.findViewById(R.id.listView);
        if (activityViews == null)
        {
            activityViews = new ArrayList<ActivityView>();

        }
        if(getArguments()!=null) {
            getArguments().getSerializable("yog");
        }
        activityViews.add(activityView);
            activityListAdapter = new ActivityListAdapter(getActivity(), R.id.listView, activityViews);
            listview.setAdapter(activityListAdapter);
            activityListAdapter.notifyDataSetChanged();
            Button btn=(Button)rootview.findViewById(R.id.button2);
            btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(getActivity(), DetailActivity.class);
                startActivity(intent);
            }
        });



        return rootview;
    }

    }

This is the activity where data go to populate listview in task fragment:

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class DetailActivity extends AppCompatActivity {
    ActivityView activityView = new ActivityView();
    // public static String endpoint;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        final EditText editText = (EditText) findViewById(R.id.editText);
        final Spinner spinner = (Spinner) findViewById(R.id.spinner);
        final ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.yog, R.layout.support_simple_spinner_dropdown_item);
        spinner.setAdapter(arrayAdapter);
        final Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activityView.setDescription(editText.getText().toString());
                activityView.setStatus(spinner.getSelectedItem().toString());
              //  Bundle bundle=new Bundle();
               // bundle.putSerializable("yog", activityView);
                Task task=new Task();
                //task.setArguments(bundle);
                android.support.v4.app. FragmentManager fm=getSupportFragmentManager();
                android.support.v4.app.  FragmentTransaction ft=fm.beginTransaction();
                ft.add(R.id.container,task,"");
                ft.commit();

            }
        });
    }
}

Here how to pass data between activity and fragment of viewpager can anybody help me out? Thanks in advance!

M.YOGE
  • 21
  • 2
  • 9

2 Answers2

2

You can use a Bundle to pass datas from an Activity to a Fragment:

In the Activity, create your Bundle and add it to the Fragment

Bundle myBundle = new Bundle();
myBundle .putLong( "exampleId", mExampleId);
myBundle .putString("exampleName", mName);
...
myFragment.setArguments( myBundle  );

Then, when the Fragment is created, get the values in your Bundle using the function getArguments() like:

Long exampleId = getArguments().getLong("exampleId");

And even set a default value if you don't find the key in your Bundle

String exampleName = getArguments().getString( "exampleName", "None"));
Nicolas Cortell
  • 659
  • 4
  • 16
1

You should create a NewInstance method inside your fragment. In short, it could look like this:

public class MyFragment {
    private int value;

    private static final String ARG_VALUE = "argValue";

    public static MyFragment NewInstance(int value) {
        Bundle args = new Bundle();
        args.putInt(ARG_VALUE, value);

        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate() {
        Bundle args = getArguments();
        this.value = args.getInt(ARG_VALUE, 0); // Default 0 if key not found.
    }
}

And you just pass in that value anytime you create the fragment:

MyFragment tenFragment = MyFragment.newInstance(10);

Then it can be used in a fragment transaction or inserted into a FragmentStatePagerAdapter however you need it. The same principle applies to any data type, so you can do this if you need to pass in Strings, or your own serializable object, etc.

AdamMc331
  • 16,492
  • 10
  • 71
  • 133