Ra41P
Ra41P

Reputation: 774

Passing data from activity to swipeable view fragment

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

}

Upvotes: 0

Views: 2698

Answers (1)

Illegal Argument
Illegal Argument

Reputation: 10358

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

Upvotes: 1

Related Questions