简体   繁体   中英

Getting EditText Value from a Fragment in main Activity

I have placed three edit text in a fragment and want to get the values of the edit text in the fragment from the main activity. I tried the following code but its throwing nullpointerexception in getName() method.

Fragment Class

public class Fragment1 extends Fragment{

EditText name, age, gender;


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

    View view = inflater.inflate(R.layout.frag1, container);

    name = (EditText) view.findViewById(R.id.name);
    age = (EditText) view.findViewById(R.id.age);
    gender = (EditText) view.findViewById(R.id.gender);

    return view;
}

public String getName(){
    String name1 = name.getText().toString().trim();
    return name1;
}
public String getAge(){
    String age1 = age.getText().toString().trim();
    return age1;
}
public String getGender(){
    String gender1 = gender.getText().toString().trim();
    return gender1;
}
}

MainActivity

public class MainActivity extends AppCompatActivity {


Fragment1 f1;
Button b1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1 = (Button) findViewById(R.id.button);
    f1 = new Fragment1();

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, f1.getName() +" "+ f1.getAge() +" "+ f1.getGender(), Toast.LENGTH_SHORT).show();
        }
    });
}
}

Edit:

activity_main.xml

this is my main activity ui

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ganesh.fragtask.MainActivity">

<fragment
    android:id="@+id/fragment"
    android:name="com.example.ganesh.fragtask.Fragment1"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="50dp"
    android:text="Button" />
</RelativeLayout>

Logcat this is the exception i get when i click the button

FATAL EXCEPTION: main
                                                                       Process: com.example.ganesh.fragtask, PID: 6015
                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                                                                           at com.example.ganesh.fragtask.Fragment1.getName(Fragment1.java:33)
                                                                           at com.example.ganesh.fragtask.MainActivity$1.onClick(MainActivity.java:25)
                                                                           at android.view.View.performClick(View.java:5611)
                                                                           at android.view.View$PerformClick.run(View.java:22276)
                                                                           at android.os.Handler.handleCallback(Handler.java:751)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6195)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764)

The thing is f1 = new Fragment1(); you have just created a object for fragment class, but this is not the exact way to call the fragment . You are supposed to set transition using the fragmentManager . If you didn't set in this way, then the frgament Lifecycle method's won't be called. So, in your scenario onCreateView() won't be called and the views are not initialized(As your stackTrace clearly states the view is not initialized). Try the below code

f1 = new MainFragment();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_frame, f1, 
f1 .getClass().getSimpleName()).addToBackStack(null).commit();

I hope you are aware of the other fragment container.ie, having a FrameLayout in MainActivity and adding the Fragment to that container.

Hope this is helpful:)

f1 = new Fragment()

This is not how you add fragments. You are just creating a new fragment instance here. The fragment's onCreateView never gets called because the fragment has not been added. Due to this, the editText variable is null and you get the exception. Please study fragments a little bit.

http://www.vogella.com/tutorials/AndroidFragments/article.html

This is how you add a fragment :

getSupportFragmentManager().beginTransaction().add(R.id.frag_layout_id, f1, "fragment_identifier").commit();

EDIT

Since the question has been edited with the xml, although you have declared the fragment in XML, the f1 instance in your java does not refer to that. To get a handle for the instance added through xml, use this

Fragment_Example f1 = (Fragment_Example)getSupportFragmentManager().findFragmentById(R.id.fragment);

I think you name, age, and gender views are not initialized: try changing your onCreateView() like this

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag1, container);
    name = (EditText) view.findViewById(R.id.your_id);
    age = (EditText) view.findViewById(R.id.your_id);
    gender = (EditText) view.findViewById(R.id.your_id);

    return view;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM