san g san g - 1 month ago 16
Android Question

Getting selected radio button value from radiogroup in fragment

Although this question has been discussed already but I am not getting why I am getting this NullPointerException error. I am trying to get a selected radio button value from radiogroup in fragment as shown in below code. The error is in the line:

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

I am getting NULL for radioButton. Can somebody clarify why?

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();

}

});
}


The 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>


The 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)

Answer

Make rootView as global variable because your method 'addListenerOnButton()' getting null view.

as below:

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();

        }

    });
}

I did not try this but I hope this works.