1

I am making a simple app to learn using fragment. I want to transfer an string from one activity to a fragment. I did it by Bundle by it does not work. In the fragment class it doesn not accept the code and highlight it as unreachable code. Here is my code: Main Activity: public class MainActivity extends FragmentActivity {

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

        // storing string resources into Array
        //
        setContentView(R.layout.activity_main);
        String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
        //List view
        final ListView list = (ListView)findViewById(R.id.questionsList);
        ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, adobe_products);

         //final TextView text = (TextView)findViewById(R.id.textView1);

        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){

                String selectedFromList =(String) (list.getItemAtPosition(position));


                Fragment fragment = new Fragment();
                Bundle bundle = new Bundle();
                bundle.putString("key", selectedFromList);
                fragment.setArguments(bundle);

            }
        });

        list.setAdapter(adapter);
    }

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


}

Main Activity XML

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/questionsList"
        android:layout_width="144dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.07" >

    </ListView>

    <fragment
        android:id="@+id/article_fragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        class="com.example.layout.MyFragment" />

</LinearLayout>

Fragment:

    public class MyFragment extends Fragment {

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

        View myFragmentView =  inflater.inflate(R.layout.activity_fragment, container, false);

        Bundle bundle = getArguments();
        String selected = bundle.getString("key");

        TextView text = (TextView) myFragmentView.findViewById(R.id.text);
        text.setText(selected);


        // Inflate the layout for this fragment

        return myFragmentView;



    }
}

UPDATE: I just made the changes, I don't have this error anymore, but it still does not open the app. It stops in loading. Here is the catLog:

    02-22 10:45:05.791: E/AndroidRuntime(1867): FATAL EXCEPTION: main
02-22 10:45:05.791: E/AndroidRuntime(1867): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.layout/com.example.layout.MainActivity}: android.view.InflateException: Binary XML file line #20: Error inflating class fragment
02-22 10:45:05.791: E/AndroidRuntime(1867):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-22 10:45:05.791: E/AndroidRuntime(1867):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-22 10:45:05.791: E/AndroidRuntime(1867):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
Dan
  • 47
  • 9

3 Answers3

0

put return at bottom, return means I'm done and finish this method and for fragment.

 private TextView text;

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


        text = (TextView) myFragmentView.findViewById(R.id.text);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.activity_fragment, container, false);


    }

Your bundle operation code won't work, You create a new instance of Fragment but that's it. What should do is :

Put a method in your MyFragment class such as

public void setMyText(String s){

        text.setText(s);
}

and in click listener,

 list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){

            String selectedFromList =(String) (list.getItemAtPosition(position));


               MyFragment f = (MyFragment) getSupportFragmentManager()
                      .findViewById(R.id.article_fragment);
               f.setMyText(selectedFromList);

        }
    });
Orhan Obut
  • 8,756
  • 5
  • 32
  • 42
  • Thanks for your help. I tried it and getting a different error. Just updated my post. Have a look please. – Dan Feb 22 '14 at 15:52
  • Yes it does. And it has a textview with a default text which shows that text perfectly. But when I add this line : `String myInt = bundle.getString("key");` to my fragment class, it stops working. – Dan Feb 22 '14 at 16:03
  • Thanks but it came up with some errors. Firstly, it finds `findViewById(R.id.article_fragment);` as undefined for fragment manager. Also same thing for `fm.setText`. Secondly, I noticed you did not use the setMyText method, or Im wrong ? – Dan Feb 22 '14 at 16:28
  • fm.setText() was typo, it's fm.setMyText, and if your fragment is inflated it should be inside fragmentmanager. The point is you need to find inflated fragment and set the text. – Orhan Obut Feb 22 '14 at 16:37
  • I found the solution. Your code is almost right only it must not be fragmentManager, it myst be my fragment class name so here is the correct line of code: `MyFragment fm = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.article_fragment); fm.setMyText(selectedFromList);` – Dan Feb 25 '14 at 02:35
  • yes, actually that's what I meant but made a typo there. – Orhan Obut Feb 25 '14 at 08:02
0

That return problem has already been stated, I would like to add the following for understanding:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View myFragmentView = inflater.inflate(R.layout.activity_fragment,
            container, false);

           Intent intent = getActivity().getIntent();
           Bundle bundle = this.getArguments();
           String selected = bundle.getString("key");

    //You now are able to use myFragmentView like this: 
    //TextView textView = (TextView)myFragmentView.findViewById(R.id.someTextView);

   //at the end of the file:

  return myFragmentView;

}

This indicates you have put the Arguments to the Fragments bundle when calling it, like this:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("key", value);
fragment.setArguments(bundle);

Edit again: Since your fragment is hardcoded, refer to nr4bts version. You can't take anything from bundle if you never put anything in there.

tritop
  • 1,655
  • 2
  • 18
  • 30
  • Thanks for your help. I tried to use my code and updated my post, but still getting a different error and that cause the app to not even load. Have a look at the code please. – Dan Feb 22 '14 at 15:52
0

A few things, you need to get the existing references outside of the onClick (into the onCreate), and then also, you need to retrieve the Bundle differently.

Check this SO question:

How to transfer some data to another Fragment?

Community
  • 1
  • 1
Booger
  • 18,579
  • 7
  • 55
  • 72