Passing data from activity to swipeable view fragment

Ra41P

Ok, I'm new to android programming and here is my problem. I've got an async task that collects json data from a server on a httpget request and updates a listview fragment in a swipeable view. I want a way to send data(a bunch of strings) from the main TabActivity class to the Tab1Fragment class.

I've done my level best at stripping down the code to the essentials.

NOTE: I've tried the bundle method that I've read in other similar questions, but they all end up throwing NULL pointer exceptions in the fragment, meaning the bundle isn't getting sent.(?)

This is my main Tab Activity:

 TabActivity.java
public class TabActivity extends ActionBarActivity  implements ActionBar.TabListener {
private String phoneno;
private static String url = "http://my/url/forjson";

//JSON Node Names 
private static final String TAG_OPERATOR = "operator";
private static final String TAG_REGNO = "Reg No";

public String  operator;
public String regNo;


private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Details", "Others"};
Bundle bundle = new Bundle();

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

        Intent intent = getIntent();
    phoneno = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 
    new JSONParse().execute();

    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getSupportActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());

}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

/*Private Class to parse JSON*/
private class JSONParse extends AsyncTask<String, String, JSONObject> {
       private ProgressDialog pDialog;
      @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(TabActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
      }
      @SuppressWarnings("finally")
    @Override
        protected JSONObject doInBackground(String... args) {

    //*     
    JSONParser jParser = new JSONParser();

        // Getting JSON from URL    
        StringBuilder finalUrl = new StringBuilder();
        JSONObject jsonForData = new JSONObject();
        try{
        finalUrl.append(url);
        jsonForData = jParser.getJSONFromUrl(finalUrl.toString());

        }catch (JSONException e) {
              e.printStackTrace();
            }
        return jsonForData;
      }

       @Override
         protected void onPostExecute(JSONObject json) {
         pDialog.dismiss();
         try {

            Bundle bundle=new Bundle();
            bundle.putString("oper", json.getString(TAG_OPERATOR));
            bundle.putString("regNo", json.getString(TAG_REGNO));

            mAdapter.getData(bundle);

        } catch (JSONException e) {
          e.printStackTrace();
        }
       }
    }
 }

In the above code, please understand that the JSONPasrser class that I've instantiated returns a JSONObject from the url and it works. So, no issues there.

Further, my fragment class is a listview as follows:

Tab1Fragment.java

public class Tab1Fragment extends ListFragment{

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
        String abc = "No Details Presently Available";

        //Fill all string values with something
        String[] values = new String[2];
        for(int i=0;i<values.length;i++)
            values[i] = " ";
        //Make Sure number of elements match
        try{
        values[0] = "Provider: " +  getArguments().getString("oper");//Gives a NULL value
        values[1] = "No: " + +  getArguments().getString("regNo");//Gives a NULL value

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1,values);
        // Assign adapter to ListView
        setListAdapter(adapter); 
        }
        catch(Exception e){
            e.printStackTrace();
            Log.w("Error","The App didn't have enough elements specified to populate the listview");
        }
        return rootView;
    }
 }

The "abc" string that I've hardcoded should ideally have details sent from the TabActivity class.

I want the above fragment to recieve data from the TabActivity class to populate the listview. Any help is appreciated :)

EDIT: I've changed the adapter class as follows based on Illegal Argument's suggestion.

So now, the bundle is passed as TabActivity->TabsPagerAdapter->Tab1Fragment But still, NULL value returned.

My Adapter class is now as follows:

  TabsPagerAdapter.java
 public class TabsPagerAdapter extends FragmentStatePagerAdapter {
 Bundle bundle = new Bundle();

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

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        Fragment fragment = new Tab1Fragment();

        this.bundle.putString("operator", "hi");
        fragment.setArguments(this.bundle);
        return fragment;
    case 1:
        return new Tab2Fragment();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return 2;
}

public void getData(Bundle bundle){
    this.bundle = bundle;
}

}
Illegal Argument

I can see that you have successfully passed data via a bundle. Please remove this. from your code below:

this.bundle.putString("operator", "hi");
    fragment.setArguments(this.bundle);

change it because it is not required to be accessed that way:

bundle.putString("operator", "hi");
    fragment.setArguments(bundle);

On your Tab1Fragment.java you can try something like this:

    if(getArguments()!=null){
String sentString = getArguments().getString("operator");
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Passing location data from fragment to activity in Android

From Dev

Passing data From Activity to Fragment using interface

From Dev

Passing data from an Activity to a fragment that has no onCreate

From Dev

Passing `SharedPreferences` data from Fragment to Activity

From Dev

Passing data from list fragment to new activity

From Dev

Passing data from one activity fragment to a different activity fragement

From Dev

Passing data from Activity to Fragment (by accessing activity from fragment) giving Class Cast Exception

From Dev

Passing data from Activity to Fragment (by accessing activity from fragment) giving Class Cast Exception

From Dev

Firebase data retrieve and passing it from fragment to new activity not working

From Dev

Passing data from a class that 'extends activity' to a class that 'extends fragment'

From Dev

Android Event bus passing data from activity to tab fragment

From Dev

Get empty data when passing variable value from activity to fragment

From Dev

Passing String From Activity to Fragment

From Dev

Passing Object from Fragment to Activity

From Dev

passing string from an activity to a fragment

From Dev

Creating an Intent from a Fragment and passing data back to that Fragment from the Intent activity (Tabbed App)

From Dev

Android, passing Extras from activity, to fragment activity, to fragment

From Dev

Passing Objects from Activity to ViewPager and then to Fragment

From Dev

Passing ArrayList from Fragment class to Activity

From Dev

android passing and retrieving extra from activity to fragment

From Dev

error passing arguments from an activity to a fragment in android

From Dev

Passing a object from my activity to my fragment

From Dev

Passing ArrayList from Fragment class to Activity

From Dev

error passing arguments from an activity to a fragment in android

From Dev

Passing spinner value from activity to fragment

From Dev

sending data from activity to fragment

From Dev

Pass data from an Activity to a fragment

From Dev

Send data to fragment from Activity

From Dev

Passing data from a RecyclerView to Fragment

Related Related

  1. 1

    Passing location data from fragment to activity in Android

  2. 2

    Passing data From Activity to Fragment using interface

  3. 3

    Passing data from an Activity to a fragment that has no onCreate

  4. 4

    Passing `SharedPreferences` data from Fragment to Activity

  5. 5

    Passing data from list fragment to new activity

  6. 6

    Passing data from one activity fragment to a different activity fragement

  7. 7

    Passing data from Activity to Fragment (by accessing activity from fragment) giving Class Cast Exception

  8. 8

    Passing data from Activity to Fragment (by accessing activity from fragment) giving Class Cast Exception

  9. 9

    Firebase data retrieve and passing it from fragment to new activity not working

  10. 10

    Passing data from a class that 'extends activity' to a class that 'extends fragment'

  11. 11

    Android Event bus passing data from activity to tab fragment

  12. 12

    Get empty data when passing variable value from activity to fragment

  13. 13

    Passing String From Activity to Fragment

  14. 14

    Passing Object from Fragment to Activity

  15. 15

    passing string from an activity to a fragment

  16. 16

    Creating an Intent from a Fragment and passing data back to that Fragment from the Intent activity (Tabbed App)

  17. 17

    Android, passing Extras from activity, to fragment activity, to fragment

  18. 18

    Passing Objects from Activity to ViewPager and then to Fragment

  19. 19

    Passing ArrayList from Fragment class to Activity

  20. 20

    android passing and retrieving extra from activity to fragment

  21. 21

    error passing arguments from an activity to a fragment in android

  22. 22

    Passing a object from my activity to my fragment

  23. 23

    Passing ArrayList from Fragment class to Activity

  24. 24

    error passing arguments from an activity to a fragment in android

  25. 25

    Passing spinner value from activity to fragment

  26. 26

    sending data from activity to fragment

  27. 27

    Pass data from an Activity to a fragment

  28. 28

    Send data to fragment from Activity

  29. 29

    Passing data from a RecyclerView to Fragment

HotTag

Archive