2

I am trying to pass values through a Bundleusing setArguments() from an activity to another class extends Fragment when I press one of the listed items in a ListView.

As shown below, I used a Log.i statement to know if the Bundle received is null or not. Unfortunately, it is always null and consequently, no data shows on the designated TextView of the class that extends Fragment. What I am missing or what is wrong with the code.

FragmentClass:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    View view = inflater.inflate(R.layout.fragmentclasslayout, null);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    if (getArguments() != null) {
        Log.i(TAG, "getArgument is not null");
        int value = getArguments().getInt("pos");           
        TextView tv = (TextView) getView().findViewById(R.id.tvID);
        tv.setTextSize(value);
        tv.setText("size = "+value*10);
    }else {
        Log.i(TAG, "getArgument is null");
    }
}

MainClass_implements_onItemSelectedListener:

setContentView(R.layout.mainactivity);

    ListView mListView = (ListView) findViewById(R.id.list);
    ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
            R.layout.listviewlayout, R.id.tv, string);
    mListView.setAdapter(mArrayAdapter);
    mListView.setOnItemSelectedListener(this);
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub

    Fragment f = new FragmentClass();
    Bundle bundle = new Bundle();

    bundle.putInt("pos", (position+1));
    FragmentClass fc = new FragmentClass().newInstance(bundle);
    //f.setArguments(bundle);

    FragmentTransaction t =
            getFragmentManager().beginTransaction();
            t.replace(R.id.fragment00ID, f);
            t.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            t.addToBackStack(null);
            t.commit();
}

mainActivity_layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
tools:ignore="MergeRootFrame">

<ListView
    android:id="@+id/list"
    android:layout_width="100px"
    android:layout_weight="1"
    android:layout_height="match_parent" />
<fragment
    android:name="com.example.fragmentwithlistview.FragmentClass"
    android:id="@+id/fragment00ID"
    android:layout_toRightOf="@+id/list"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_weight="4" />

FragmentClass_layout:

<FrameLayout 
xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:ignore="MergeRootFrame"
android:background="#FFFFFF">

<TextView
    android:id="@+id/tvID"
    android:textColor="#000000"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

Ajeet Choudhary
  • 1,969
  • 1
  • 17
  • 41
  • how are you setting arguments – Illegal Argument May 28 '14 at 11:07
  • @IllegalArgument please have alook at the method `onitemselected' it is `bundle.putInt("pos", (position+1));` is that what you mean? –  May 28 '14 at 11:09
  • R.id.fragment00ID refers to your activity layout you want to replace right?? – Illegal Argument May 28 '14 at 11:10
  • yes, i will post the layout as well shortly –  May 28 '14 at 11:12
  • anything to do with addToBackStack(null)? – kevin May 28 '14 at 11:19
  • @kevin no, i just used `addToBackStack(null)` so later when the app. works, i know how `addToBackStack(null)` works –  May 28 '14 at 11:23
  • @IllegalArgument i posted the entire layoout –  May 28 '14 at 11:23
  • The first answer of this shall help: https://stackoverflow.com/questions/5658675/replacing-a-fragment-with-another-fragment-inside-activity-group – kevin May 28 '14 at 11:27
  • @kevin i think they mainly talking about replacing a fragment with another programmatically, which already did –  May 28 '14 at 11:47
  • @Amr The point is you cannot replace a fragment hard coded in xml. The `FragmentTransaction.replace` code in your `onItemSelected` failed silently (I assume), the fragment is still the one in your xml, which does not contain any arguments. – kevin May 28 '14 at 12:37

2 Answers2

1

Better use a static method for instantiating:

public class FragmentClass extends Fragment {

  public static FragmentClass newInstance(Bundle b) {
    FragmentClass fragment = new FragmentClass();
    fragment.setArguments(b);

    return fragment;
  }

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragmentclasslayout, null);

      if (getArguments() != null) {
          Log.i(TAG, "getArgument is not null");
          int value = getArguments().getInt("pos");           
          TextView tv = (TextView) view.findViewById(R.id.tvID);
          tv.setTextSize(value);
          tv.setText("size = "+value*10);
      } else {
          Log.i(TAG, "getArgument is null");
      }

      return view;
  }
}

Then simply call that method and pass the arguments-bundle as a parameter:

Bundle bundle = new Bundle();
bundle.putInt("pos", (position+1));
FragmentClass f = FragmentClass.newInstance(bundle);

Also, don't use onActivityCreated for fetching the arguments in your FragmentClass, use onCreateView or if required onStart or onResume. Have a look at fragment-lifecycles: http://developer.android.com/guide/components/fragments.html#Lifecycle

Blacklight
  • 3,809
  • 2
  • 33
  • 39
  • I triied your suggestion but still no data appears? –  May 28 '14 at 11:21
  • I tried it, the same thing again, no data output, the fragment area is aemptyt –  May 28 '14 at 11:28
  • AFAIK, in `onCreateView` one can't initialise the view's using `getview.finditembyid()` because the view has not fully initialised yet. but inside it we can initialise objects and instantiate them. am I right? –  May 28 '14 at 11:31
  • Why are you instantiating your fragment outside of `onItemSelected`? I guess that's where your problem is then, look at kevin's comment. In `onCreateView` you inflate your view and use `findViewById` on that view. – Blacklight May 28 '14 at 11:32
  • I just noticed in your edit: not `new FragmentClass().newInstance`, just `FragmentClass.newInstance`. Other than that it's hard to give more advice, pay attention to how you use the `FragmentManager` as well as to the Fragment lifecycles. – Blacklight May 28 '14 at 11:48
  • Very wrong again, please pay attention! I edited my answer again. You do NOT use the constructor anymore if you use `newInstance`. – Blacklight May 28 '14 at 12:12
  • kindly please bear with me, i cant figure out where my mistake is, is it in the body of onCreateView or in onitemselected? –  May 28 '14 at 12:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/54629/discussion-between-blacklight-and-amr). – Blacklight May 28 '14 at 12:28
0

You can use in passing Activity

Bundle bundle = new Bundle();
    bundle.putString("model", strDeckNumber);

                    final FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();
                    Frag1 newFragment = new Frag1();
                    newFragment.setArguments(bundle);
                    t.replace(R.id.fragment_container, newFragment);
                    t.addToBackStack(TAG);
                    t.commit();

Receiving Fragment

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

            strSeriesNumber = getArguments().getString("model");
}
Richa
  • 3,165
  • 1
  • 22
  • 26