从片段中的radiogroup获取所选单选按钮值

时间:2016-11-09 06:26:44

标签: android fragment radio

虽然已经讨论过这个问题,但我无法理解为什么会出现NullPointerException错误。我想从RadioButton中的RadioGroup获取选定的Fragment值,如下面的代码所示。错误在行中:

radioButton = (RadioButton) rootView.findViewById(selectedId);

我为radioButton获取NULL。有人可以澄清为什么吗?

public class Booking extends Fragment {

  public Context _context = getActivity();
  private String JSON_URL;
  private SharedPrefManager sharedPrefManager;

  private RadioGroup radioGroup;
  private RadioButton radioButton;
  private Button getQuotes;

  public Booking() {
    // Required empty public constructor
  }

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

    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_booking, container, false);

    sharedPrefManager = new SharedPrefManager(getActivity());

    return rootView;
  }

  public void onViewCreated(View rootView, Bundle savedInstanceState){
    super.onViewCreated(rootView, savedInstanceState);
    final View v = rootView;

    // Spinner element
    Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);

    radioGroup = (RadioGroup) rootView.findViewById(R.id.radio);
    getQuotes = (Button) rootView.findViewById(R.id.getQuotes);

    // Spinner Drop down elements
    List<String> categories = new ArrayList<String>();
    categories.add("4 Night / 5 Days");
    categories.add("5 Night / 6 Days");
    categories.add("6 Night / 7 Days");
    categories.add("7 Night / 8 Days");

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
      getActivity(), android.R.layout.simple_spinner_item, categories);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);

    // Spinner click listener
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Log.d("tag", "String item="+position);

        if(position == 0) {
          JSON_URL = "http://kaushika.tigrimigri.com/gcmMulticast2/getPackages.php";
        }
      getJSON(JSON_URL, v);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
  });

  String text = spinner.getSelectedItem().toString();
  sharedPrefManager.addSpinner(text);

  addListenerOnButton();
}

public void addListenerOnButton(){  
  getQuotes.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View rootView) {
      // get selected radio button from radioGroup
      int selectedId = radioGroup.getCheckedRadioButtonId();
      Log.d("tag","selectId" + selectedId);

      // find the radiobutton by returned id
      radioButton = (RadioButton) rootView.findViewById(selectedId);
      Log.d("tag","radioButton" + radioButton);
      Log.d("tag","radioButton.getText()" + radioButton.getText());

      //String radiovalue = ((RadioButton) rootView.findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
      //sharedPrefManager.addRadio(radioButton.getText().toString());

      Toast.makeText(
          getActivity().getApplication(),
          radioButton.getText(),
          Toast.LENGTH_LONG)
        .show();
    }
  });
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Booking Options"
        android:layout_marginBottom="5dp"/>

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/spinner_title"/>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:focusableInTouchMode="true">

        <HorizontalScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:focusableInTouchMode="true">
            <TableLayout
                android:id="@+id/table"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:focusableInTouchMode="true">
            </TableLayout>
        </HorizontalScrollView>
    </ScrollView>

    <RadioGroup
        android:id="@+id/radio"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Economy"/>
        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Standard"/>
        <RadioButton
            android:id="@+id/radio3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delux"/>
        <RadioButton
            android:id="@+id/radio4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Super Delux"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Select fare option" />
    </RadioGroup>

    <Button
        android:id="@+id/getQuotes"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:layout_marginBottom="24dp"
        android:padding="12dp"
        android:background="@drawable/button"
        android:text="Get Quotes"/>
</LinearLayout>

Logcat:

11-09 12:11:28.814 24299-24299/san.com.andamanecstacy1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: san.com.andamanecstacy1, PID: 24299
    java.lang.NullPointerException
    at san.com.andamanecstacy1.Booking$1.onClick(Booking.java:92)
    at android.view.View.performClick(View.java:4487)
    at android.view.View$PerformClick.run(View.java:18746)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5077)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:4)

将rootView作为全局变量,因为您的方法&#39; addListenerOnButton()&#39;获得空视图。

如下:

public class Booking extends Fragment {

public Context _context = getActivity();
private String JSON_URL;
private SharedPrefManager sharedPrefManager;

private RadioGroup radioGroup;
private RadioButton radioButton;
private Button getQuotes;
private View rootView;

public Booking() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_booking, container, false);

    sharedPrefManager = new SharedPrefManager(getActivity());

    return rootView;
}


public void onViewCreated(View rootView, Bundle savedInstanceState){
    super.onViewCreated(rootView, savedInstanceState);
    final View v = rootView;

    // Spinner element
    Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);

    radioGroup = (RadioGroup) rootView.findViewById(R.id.radio);
    getQuotes = (Button) rootView.findViewById(R.id.getQuotes);

    // Spinner Drop down elements
    List<String> categories = new ArrayList<String>();
    categories.add("4 Night / 5 Days");
    categories.add("5 Night / 6 Days");
    categories.add("6 Night / 7 Days");
    categories.add("7 Night / 8 Days");

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);


    // Spinner click listener
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {

            Log.d("tag", "String item="+position);

            if(position == 0) {
                JSON_URL = "http://kaushika.tigrimigri.com/gcmMulticast2/getPackages.php";
            }

            getJSON(JSON_URL, v);

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


    String text = spinner.getSelectedItem().toString();
    sharedPrefManager.addSpinner(text);

    addListenerOnButton();

}

public void addListenerOnButton(){

    getQuotes.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            // get selected radio button from radioGroup
            int selectedId = radioGroup.getCheckedRadioButtonId();
            Log.d("tag","selectId" + selectedId);

            // find the radiobutton by returned id
            radioButton = (RadioButton) rootView.findViewById(selectedId);
            Log.d("tag","radioButton" + radioButton);
            Log.d("tag","radioButton.getText()" + radioButton.getText());

            //String radiovalue = ((RadioButton) rootView.findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();

            //sharedPrefManager.addRadio(radioButton.getText().toString());

            Toast.makeText(getActivity().getApplication(), radioButton.getText(), Toast.LENGTH_LONG).show();

        }

    });
}

我没试过,但我希望这有效。