0

I have an Activity with two fragments(Frag1, Frag2).

In Frag1, I have an EditText.

While in Frag2, I have a Button and TextView.

What am I trying to do is that whatever I typed in the EditText will appear in the Textview when I click the Button. Here's my code but it's not working because my app crashes whenever i tried to run it:

Frag1:

public class Frag1 extends Fragment {

    EditText edit1;

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

        View v =  inflater.inflate(R.layout.frag2, container, false);       

        edit1 = (EditText) getActivity().findViewById(R.id.edit_1); 
        String str = edit1.getText().toString();

        Intent intent = new Intent(getActivity().getBaseContext(),
                MainActivity.class);
        intent.putExtra("message", str);
        getActivity().startActivity(intent);

        return v;
    }

}

Activity:

public class MainActivity extends FragmentActivity{

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

        viewPager = (ViewPager) findViewById(R.id.pager);
        FragmentManager fragmentManager = getSupportFragmentManager();
        viewPager.setAdapter(new MyAdapter(fragmentManager));

        Intent intent = getIntent();
        String message = intent.getStringExtra("message");

        Bundle bundle=new Bundle();
        bundle.putString("message", message);

        Frag2 fragobj=new Frag2();
        fragobj.setArguments(bundle);
    }
    public class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter (FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int i) {
            Fragment fragment = null;

            if (i == 0)
            {
                fragment = new Frag1();
            }
            if (i == 1)
            {
                fragment = new Frag2();
            }
            return fragment;
        }
        @Override
        public int getCount() {
            return 2;
        }
    }
}

Frag2:

public class Frag2 extends Fragment implements OnClickListener {

    Button button1;
    TextView text1;
    String strtext;

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

        View v =  inflater.inflate(R.layout.frag2, container, false);

        button1 = (Button) getActivity().findViewById(R.id.button1);
        button1.setOnClickListener(this);       
        text1 = (TextView) getActivity().findViewById(R.id.text1);

        strtext=getArguments().getString("message");

        return v;
    }

    @Override
    public void onClick(View arg0) { 

        text1.setText(strtext);
    }

}

LogCat:

12-01 02:47:22.763: D/jdwp(4115): sendBufferedRequest : len=0x31
12-01 02:47:22.769: W/asset(4115): AssetManager-->addDefaultAssets CIP path not exsit!
12-01 02:47:23.061: V/PhoneWindow(4115): DecorView setVisiblity: visibility = 4
12-01 02:47:23.084: V/PhoneWindow(4115): DecorView setVisiblity: visibility = 0
12-01 02:47:23.160: D/AndroidRuntime(4115): Shutting down VM
12-01 02:47:23.160: W/dalvikvm(4115): threadid=1: thread exiting with uncaught exception (group=0x40d819a8)
12-01 02:47:23.178: E/AndroidRuntime(4115): FATAL EXCEPTION: main
12-01 02:47:23.178: E/AndroidRuntime(4115): java.lang.NullPointerException
12-01 02:47:23.178: E/AndroidRuntime(4115):     at lmf.sample5.Frag1.onCreateView(Frag1.java:21)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.View.measure(View.java:15635)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.View.measure(View.java:15635)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.View.measure(View.java:15635)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2200)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.View.measure(View.java:15635)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2165)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1249)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1443)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4872)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.Choreographer.doCallbacks(Choreographer.java:579)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.Choreographer.doFrame(Choreographer.java:548)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.os.Handler.handleCallback(Handler.java:800)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.os.Handler.dispatchMessage(Handler.java:100)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.os.Looper.loop(Looper.java:194)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.app.ActivityThread.main(ActivityThread.java:5371)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at java.lang.reflect.Method.invokeNative(Native Method)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at java.lang.reflect.Method.invoke(Method.java:525)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at dalvik.system.NativeStart.main(Native Method)
walkslowly
  • 417
  • 1
  • 4
  • 16
general_bearbrand
  • 827
  • 5
  • 13
  • 29

3 Answers3

2

To access elements inside fragment you need the inflated view not the parent activity. e.g

This

    edit1 = (EditText) getActivity().findViewById(R.id.edit_1); 

should be changed to this

    edit1 = (EditText) v.findViewById(R.id.edit_1); 

Edit:

According to the log cat now you are getting a null pointer exception in Frag 1 line 21. I think its this line:

   String str = edit1.getText().toString();

When the fragment is created for the first time, edit1 has no text in it and its value is null and you are trying to call toString() on a null object which causes null pointer exception. You should check it for null first. e.g :

    String str =null;
    if(edit1.getText()!==null)
        str = edit1.getText().toString();
Sayed Jalil Hassan
  • 2,535
  • 7
  • 30
  • 42
0

You can do it using two Interface. Your strategy is like this:

TestActivity holds Fragment1 and Fragment2.

Fragment1 has:

EditText etEditHere;

Fragment2 has:

TextView tvFetchedValue;
    Button btnGetValue;

Your motive is write in etEditHere of fragment1 , press btnGetValue of Fragment2, etEditHere text will show in tvFetchedValue of Fragment2.

Here is solution:

You must have remind that, one fragment can't directly communicate with another fragment. But fragments can communicate via activity.

you have to create 2 interface, One for TestActivity, One for Fragment1.

Activity will implements this Interface:

    public interface IActivityTest {
    public String getValueFromFragment1();
}

Fragment1 will implements this interface:

    public interface IFragment1 {
    public String getValueFromEditTextInFragment1();
}

Here, TestActivity implements IActivityTest and it will have getValue() method.

Here , when btnGetValue is pressed then it will call getValueFromEditTextInFragment1() of TestActivity using this way:

tvFetchedValue.setText(((IActivityTest)getActivity()).getValueFromFragment1());

In getValueFromFragment1() method of TestActivity it will call getValueFromFragment1() of Fragment1. Fragment1 will return editText value to TestActivity . TestActivity will return back to Fragment2.

Your Full code is here:

TestActivity Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="YOUR_PACKAGE.Fragment2"
        android:layout_width="fill_parent"
        android:layout_height="200dp"/>

    <fragment
        android:id="@+id/fragmentOne"
        android:layout_marginTop="10dp"
        android:name="YOUR_PACKAGE.Fragment1"
        android:layout_width="fill_parent"
        android:layout_height="200dp" />

</LinearLayout>

Fragment1 Layout:

<FrameLayout 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"
    tools:context="com.nuspay.uddiponmarketplace.fragments.Fragment1">

    <EditText
        android:id="@+id/etEditHere"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20dp"
        android:hint="Write Here"/>

</FrameLayout>

Fragment1 Java File:

public class Fragment1 extends Fragment implements IFragment1 {

    EditText etEditHere;

    public Fragment1() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_fragment1, container, false);

        initView(view);
        return view;
    }

    private void initView(View view) {
        etEditHere= (EditText) view.findViewById(R.id.etEditHere);
    }

    @Override
public String getValueFromEditTextInFragment1() {
    return etEditHere.getText().toString().trim();
}
}

Fragment2 layout file:

<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"
    tools:context="com.nuspay.uddiponmarketplace.fragments.Fragment2"
    android:orientation="vertical">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/tvFetchedValue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Value will come here"
        android:gravity="center"
        android:textSize="17dp"
        android:padding="10dp"/>

    <Button
        android:id="@+id/btnGetValue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Value From Fragment1"
        android:gravity="center"
        android:textStyle="bold"
        android:textSize="17dp"
        android:padding="10dp"/>

</LinearLayout>

Fragment2 java file:

 public class Fragment2 extends Fragment {


        TextView tvFetchedValue;
        Button btnGetValue;
        public Fragment2() {
            // Required empty public constructor
        }


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view=inflater.inflate(R.layout.fragment_fragment2, container, false);

            initView(view);
            return view;
        }

        private void initView(View view) {
            tvFetchedValue= (TextView) view.findViewById(R.id.tvFetchedValue);
            btnGetValue= (Button) view.findViewById(R.id.btnGetValue);

            btnGetValue.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tvFetchedValue.setText(((IActivityTest)getActivity()).getValueFromFragment1());
                }
            });
        }

    }

finally, here is the TestActivity

public class TestActivity extends AppCompatActivity implements IActivityTest {

    Fragment1 fragment1;
    Fragment2 fragment2;

    @Override
    public void onCreate(Bundle iclic) {
        super.onCreate(iclic);
        setContentView(R.layout.activity_test);
        initViews();
    }

    private void initViews() {
        fragment1=new Fragment1();
        fragment2=new Fragment2();

        FragmentTransaction transaction =
                getSupportFragmentManager().beginTransaction();

        transaction.add(R.id.fragmentOne, fragment1);
        transaction.add(R.id.fragmentTwo, fragment2);
        transaction.commit();


    }

    @Override
public String getValueFromFragment1() {

    return fragment1.getValueFromEditTextInFragment1();
}
}

Fragment to Activity Communication answer is here

Thanks and sorry for bad English :)

Community
  • 1
  • 1
Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87
0

You have used the same layout for both fragments : R.layout.frag2

This is giving the null pointer.

TharakaNirmana
  • 10,237
  • 8
  • 50
  • 69