0

I currently working with a project and stuck on the radio button which getting only the checked radio in xml, I search many case regarding with this concern and still got the same problem.

here is the activity which toasting only the checked radio in xml

package com.example.kapoyei.hatidtubiganapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.kapoyei.hatidtubiganapp.helper.Http;
import com.example.kapoyei.hatidtubiganapp.helper.Network;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class ClientActivity extends Activity implements View.OnClickListener {
    public static String jsonObject;
    SharedPreferences sharedPref;
    Intent i;

    Button btnLogout, btnBreakPoint;
    Spinner spnStation;
    ImageView btnReserve, btnStationList, btnPending, btnHistory;
    TextView txtSelectDate;
    EditText no_container;
    RadioGroup radioGroup;
    RadioButton radioButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);

        btnLogout = (Button) findViewById(R.id.btnLogout);
        btnReserve = (ImageView) findViewById(R.id.btnReserve);
        btnStationList = (ImageView) findViewById(R.id.btnStation);
        btnPending = (ImageView) findViewById(R.id.btnPending);
        btnHistory = (ImageView) findViewById(R.id.btnHistory);

        btnPending.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                i = new Intent(ClientActivity.this, PendingClientOrderActivity.class);
                startActivity(i);
            }
        });

        btnStationList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                i = new Intent(ClientActivity.this, StationList.class);
                startActivity(i);
            }
        });

        btnReserve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ClientActivity.this);
                LayoutInflater inflater = getLayoutInflater();
                view = inflater.inflate(R.layout.layout_dialog_reserve, null);

                spnStation = (Spinner) view.findViewById(R.id.spnStation);
                txtSelectDate = (TextView) view.findViewById(R.id.txtDate);
                no_container = (EditText) view.findViewById(R.id.etContainer);
                radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
                radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
                btnBreakPoint = (Button) view.findViewById(R.id.btnBreakPoint);

                final Calendar c = Calendar.getInstance();

                final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                        c.set(Calendar.YEAR, year);
                        c.set(Calendar.MONTH, month);
                        c.set(Calendar.DAY_OF_MONTH, day);

                        String dateFormat = "MM/dd/yyyy";
                        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);

                        txtSelectDate.setText(sdf.format(c.getTime()));
                    }
                };

                txtSelectDate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new DatePickerDialog(ClientActivity.this,
                                date,
                                c.get(Calendar.YEAR),
                                c.get(Calendar.MONTH),
                                c.get(Calendar.DAY_OF_MONTH)).show();
                    }
                });

                btnBreakPoint.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(no_container.getText().toString().isEmpty() || txtSelectDate.getText().toString().equalsIgnoreCase("-- CLICK TO DATE DELIVER --")) {
                            Toast.makeText(getApplicationContext(), "All fields require", Toast.LENGTH_SHORT).show();
                        } else {
                            /*Bundle bundle = new Bundle();

                            bundle.putString("station", spnStation.getSelectedItem().toString());
                            bundle.putString("date", txtSelectDate.getText().toString());
                            bundle.putString("no_container", no_container.getText().toString());
                            bundle.putString("type", Integer.toString(radioGroup.getCheckedRadioButtonId()));

                            i = new Intent(ClientActivity.this, CheckOut.class);
                            i.putExtras(bundle);
                            startActivity(i);*/
                            String typeOrder = radioButton.getText().toString();
                            Toast.makeText(getApplicationContext(), typeOrder, Toast.LENGTH_LONG).show();
                        }
                    }
                });

                Network network = new Network(getApplicationContext());

                if(network.isNetwork()) {
                    new ClientActivity.GetStationList().execute();
                } else {
                    Toast.makeText(getApplicationContext(), "Coud not get stations", Toast.LENGTH_SHORT).show();
                }

                builder.setView(view);
                builder.setCancelable(true);

                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

        btnHistory.setOnClickListener(this);

        btnLogout.setOnClickListener(this);
     }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btnLogout) {
            finish();

            sharedPref = getSharedPreferences("ht", MODE_PRIVATE);
            SharedPreferences.Editor modify = sharedPref.edit();
            modify.putBoolean("login", false);
            modify.putString("id", "");
            modify.putString("auth", "");
            modify.apply();

            i = new Intent(ClientActivity.this, LoginActivity.class);
            startActivity(i);
        }

        if(view.getId() == R.id.btnHistory) {
            i = new Intent(ClientActivity.this, HistoryActivity.class);
            startActivity(i);
        }
    }

    public class GetStationList extends AsyncTask<Void, Void, String> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(ClientActivity.this);
            pd.setMessage("Getting station ...");
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        protected void onPostExecute(String result) {
            pd.cancel();
            json(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            String data = "";
            jsonObject = "";

            try {
                String link = (String) Http.url + "?type=getstationlist";
                URL getURL = new URL(link);
                HttpURLConnection httpURLConnection = (HttpURLConnection) getURL.openConnection();

                httpURLConnection.setReadTimeout(10000);
                httpURLConnection.setConnectTimeout(15000);
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setDoInput(true);
                httpURLConnection.connect();

                InputStream is = (InputStream) httpURLConnection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                while((data = reader.readLine()) != null) {
                    jsonObject += data;
                }

                Log.i("", jsonObject);

                return jsonObject;
            } catch(Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        public void json(String json) {
            List<String> collectionName = new ArrayList<>();
            if(json != null) {
                try {
                    JSONObject jobj = new JSONObject(json);
                    JSONArray jarray = jobj.getJSONArray("stationlist");

                    String name = "";
                    String id = "";

                    for(int i = 0; i < jarray.length(); i++) {
                        JSONObject obj = jarray.getJSONObject(i);
                        name = obj.getString("name");
                        collectionName.add(name);
                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, collectionName);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spnStation.setAdapter(adapter);

                } catch(Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Connection problem", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

and here is the xml where located the layout of my radio

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="20dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Select Station"
            android:layout_margin="10dp"
            android:textSize="20sp"/>

        <Spinner
            android:id="@+id/spnStation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Date"
            android:layout_margin="10dp"
            android:textSize="20sp"/>

        <TextView
            android:id="@+id/txtDate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="-- CLICK TO DATE DELIVER --"
            android:textSize="15sp"
            android:layout_margin="10dp"
            android:layout_gravity="center"
            android:textAlignment="center"/>
        <EditText
            android:id="@+id/etContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="No. Of Containers"
            android:layout_margin="10dp"/>

        <RadioGroup
            android:id="@+id/radioGroup"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RadioButton
                android:id="@+id/Gallon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Gallon"
                android:checked="true"/>

            <RadioButton
                android:id="@+id/Litre"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Litre" />
        </RadioGroup>

        <Button
            android:id="@+id/btnBreakPoint"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_margin="10dp"
            android:text="Proceed to Check Out" />
    </LinearLayout>
</RelativeLayout>
Raj
  • 2,997
  • 2
  • 12
  • 30
kim nicole
  • 13
  • 6

2 Answers2

0

Why this is happened? Because before you click Break Point button, you change the radio button id but not bind it to your variable, your variable still storing the old value. You need to add this code

radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());

above

String typeOrder = radioButton.getText().toString();

so it will shown

btnBreakPoint.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        ...
        radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
        radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
        String typeOrder = radioButton.getText().toString();
        ...
    }

or you can move the scope of radioGroup assignment to onCreate scope

Frandall
  • 378
  • 1
  • 13
  • now i got this error `java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference` – kim nicole Aug 27 '18 at 04:36
0

You can apply the below codes:

int radioid = radioButtonGroup.getCheckedRadioButtonId();
View radio_button= radioButtonGroup.findViewById(radioButtonID);
int index = radioButtonGroup.indexOfChild(radioButton);

If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.

To get selected RadioButton Text on RadioGroup follow the below code:

 RadioButton radio = (RadioButton)  radioButtonGroup.getChildAt(index);
 String text = radio.getText().toString();
Gourango Sutradhar
  • 1,461
  • 10
  • 16