I am new to here and java. I am developing an android app with radio buttons which calculates the SGPA of a student. Every subject has it's own credits which gets multiplies by the respective grade and after the addition of all products of the subject, The sum is divided by the total credits...
So far i've completed the xml code properly but i am stuck in the java main activity... I just need an example of only one button or subject and rest i will do on my own... I want to use switch case to first check which radio button is clicked and then do the respective calculations.
XML CODE
<TextView
android:id="#+id/maths"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F44336"
android:text="MATHEMATICS"
android:textAlignment="center"
android:textAllCaps="true"
android:textAppearance="?android:textAppearanceLarge"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F44336"
android:orientation="horizontal">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="horizontal">
<RadioButton
android:id="#+id/Omaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="O"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Aplusmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="A+"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Amaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="A"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Bplusmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="B+"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Bmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="B"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Cmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="C"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Pmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="P"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
</LinearLayout>
AND THE JAVA MAIN ACTIVITY CODE IS
package droidmentor.bnv_with_viewpager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import droidmentor.bnv_with_viewpager.Fragment.CallsFragment;
import droidmentor.bnv_with_viewpager.Fragment.ChatFragment;
import droidmentor.bnv_with_viewpager.Fragment.ContactsFragment;
import static droidmentor.bnv_with_viewpager.R.id.Amaths;
import static droidmentor.bnv_with_viewpager.R.id.Bmaths;
import static droidmentor.bnv_with_viewpager.R.id.Bplusmaths;
import static droidmentor.bnv_with_viewpager.R.id.Cmaths;
import static droidmentor.bnv_with_viewpager.R.id.Pmaths;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
//This is our viewPager
private ViewPager viewPager;
//Fragments
ChatFragment chatFragment;
CallsFragment callsFragment;
ContactsFragment contactsFragment;
MenuItem prevMenuItem;
//Instance Variables For Each Subject
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.viewpager);
//Initializing the bottomNavigationView
bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_call:
viewPager.setCurrentItem(0);
break;
case R.id.action_chat:
viewPager.setCurrentItem(1);
break;
case R.id.action_contact:
viewPager.setCurrentItem(2);
break;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
}
else
{
bottomNavigationView.getMenu().getItem(0).setChecked(false);
}
Log.d("page", "onPageSelected: "+position);
bottomNavigationView.getMenu().getItem(position).setChecked(true);
prevMenuItem = bottomNavigationView.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
/* //Disable ViewPager Swipe
viewPager.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
*/
setupViewPager(viewPager);
}
//This method is called when button is pressed
public void calculate(View view) {
display(9);
}
//This method returns the SGPA
private void display(int number) {
TextView sgpa = (TextView) findViewById(R.id.sgpa);
sgpa.setText("" + number);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
callsFragment=new CallsFragment();
chatFragment=new ChatFragment();
contactsFragment=new ContactsFragment();
adapter.addFragment(callsFragment);
adapter.addFragment(chatFragment);
adapter.addFragment(contactsFragment);
viewPager.setAdapter(adapter);
}
}
I know i can use the user input method with edit text but i have to use radio buttons... :)
try do this to get selected button:
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
Note that if you use textview or other view inside radioGroup not equal to radiobutton you get wrong index.
To get the text of selected button:
RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
String selectedtext = r.getText().toString();
Related
I'm currently making a soundboard app on android studio which has a ton of fragments. The first page on my tab layout is just a normal button view, but my second tabView has another fragmentView within it. The goal is for the first page to just show some normal sounds, and the second tab to have multiple operators to choose specific soundboards for.
Anyways, the app seems to work fine. I can switch from the main tab to the operator tab, and even select operator soundboard pages and be moved to their fragments. However as soon as I try to switch fragments (through my tabview) my app crashes and I get the error:
"Fragment operatorTab{4623fc9} (312d4e58-458c-4f47-8fa3-794fe15f0536)} not attached to a context."**
**at com.jkcarraher.rainbowsixsoundboard.operatorTab.resetAllButtons(operatorTab.java:113)
at com.jkcarraher.rainbowsixsoundboard.operatorTab.access$000(operatorTab.java:31)
at com.jkcarraher.rainbowsixsoundboard.operatorTab$2.onScrollChanged(operatorTab.java:107)
I attached my code below, please let me know if you have any ideas!
MainActivity.java
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.Adapter;
import android.widget.TextView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeAds();
makeSixYellow();
//Create ViewPager (that houses all fragments)
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.view_pager);
setUpViewPager(mViewPager);
//Add & customize tabs
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabTextColors(Color.WHITE, Color.WHITE);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setText("Utility");
tabLayout.getTabAt(1).setText("Voice Lines");
checkPageChange();
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new utilityTab(), "Utility");
adapter.addFragment(new voiceLinesView(), "Voice Lines");
viewPager.setAdapter(adapter);
}
private void makeSixYellow(){
TextView textView = findViewById(R.id.titleText);
String text = "R6 Soundboard";
SpannableString ss = new SpannableString(text);
ForegroundColorSpan fcsYellow = new ForegroundColorSpan(Color.rgb(255,236,141));
ss.setSpan(fcsYellow, 1,2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ss);
}
private void initializeAds(){
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
}
private void checkPageChange(){
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
utilityTab.resetAllButtons();
}
#Override
public void onPageSelected(int position) {
utilityTab.resetAllButtons();
}
#Override
public void onPageScrollStateChanged(int state) {
utilityTab.resetAllButtons();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorHeader"
android:theme="#style/AppTheme.AppBarOverlay">
<TextView
android:id="#+id/titleText"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/avenir"
android:gravity="center_horizontal"
android:text="R6 Soundboard"
android:textColor="#FFF"
android:textSize="30sp" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextColor="#fff"
android:background="#color/colorHeader" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBody"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
voiceLinesView.java (contains fragments so I can select an operator and it will take me to their soundboard fragment)
package com.jkcarraher.rainbowsixsoundboard;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.tabs.TabLayout;
public class voiceLinesView extends Fragment {
private SectionsPageAdapter voiceLinesSectionsPageAdapter;
private ViewPager voiceLinesViewPager;
public voiceLinesView() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_voice_lines_view, container, false);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.voiceLinesFrame, new operatorTab());
fragmentTransaction.commit();
return view;
}
}
fragment_voice_lines_view.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".voiceLinesView">
<FrameLayout
android:id="#+id/voiceLinesFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
operatorTab.java
package com.jkcarraher.rainbowsixsoundboard;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import soup.neumorphism.NeumorphCardView;
import soup.neumorphism.ShapeType;
import static android.view.MotionEvent.ACTION_MOVE;
public class operatorTab extends Fragment {
private ScrollView scrollView;
public static RelativeLayout KapkanButton;
public static RelativeLayout GlazButton;
public static RelativeLayout FuzeButton;
public static RelativeLayout TachankaButton;
voiceLinesView voiceLinesView = new voiceLinesView();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_operator_tab, container, false);
//Initialize ScrollView
scrollView = view.findViewById(R.id.operatorScrollView);
//Initialize buttons 1-4
KapkanButton = view.findViewById(R.id.kapkanButton);
GlazButton = view.findViewById(R.id.glazButton);
FuzeButton = view.findViewById(R.id.fuzeButton);
TachankaButton = view.findViewById(R.id.tachankaButton);
//Make buttons 1-6 pressable
initPressableButton(KapkanButton);
initPressableButton(GlazButton);
initPressableButton(FuzeButton);
initPressableButton(TachankaButton);
scrollResetListener();
return view;
}
#SuppressLint("ClickableViewAccessibility")
private void initPressableButton(final RelativeLayout relativeLayout) {
relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorBody));
final Rect r = new Rect();
relativeLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
// get the View's Rect relative to its parent
view.getHitRect(r);
// offset the touch coordinates with the values from r
// to obtain meaningful coordinates
final float x = event.getX() + r.left;
final float y = event.getY() + r.top;
if(event.getAction() == MotionEvent.ACTION_DOWN) {
relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorButtonPressed));
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP) {
if (r.contains((int) x, (int) y)) {
relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorBody));
//On Click Up
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.voiceLinesFrame, new kapkanVoiceLines());
fr.commit();
}
}else if(event.getAction() == ACTION_MOVE){
if (!r.contains((int) x, (int) y)) {
relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorBody));
}
return true;
}
return false;
}
});
}
private void scrollResetListener(){
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
resetAllButtons();
}
});
}
public void resetAllButtons(){
KapkanButton.setBackgroundColor(getResources().getColor(R.color.colorBody));
GlazButton.setBackgroundColor(getResources().getColor(R.color.colorBody));
FuzeButton.setBackgroundColor(getResources().getColor(R.color.colorBody));
TachankaButton.setBackgroundColor(getResources().getColor(R.color.colorBody));
}
}
fragment_operator_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".operatorTab">
<ScrollView
android:id="#+id/operatorScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorBody">
<RelativeLayout
android:id="#+id/kapkanButton"
android:layout_width="match_parent"
android:layout_height="60sp"
android:orientation="horizontal">
<ImageView
android:id="#+id/kapkanIcon"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="10sp"
android:src="#drawable/ic_kapkan"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/kapkanIcon"
android:layout_marginLeft="10sp"
android:layout_marginTop="15sp"
android:layout_gravity="center"
android:fontFamily="#font/avenir"
android:text="Kapkan"
android:textColor="#ffffff"
android:textSize="25dp" />
<ImageView
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_alignParentEnd="true"
android:layout_marginTop="10sp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_arrow_right" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/glazButton"
android:layout_below="#+id/kapkanButton"
android:layout_width="match_parent"
android:layout_height="60sp"
android:orientation="horizontal">
<ImageView
android:id="#+id/glazIcon"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="10sp"
android:src="#drawable/ic_glaz"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/glazIcon"
android:layout_marginLeft="10sp"
android:layout_marginTop="15sp"
android:layout_gravity="center"
android:fontFamily="#font/avenir"
android:text="Glaz"
android:textColor="#ffffff"
android:textSize="25dp" />
<ImageView
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_alignParentEnd="true"
android:layout_marginTop="10sp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_arrow_right" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/fuzeButton"
android:layout_below="#+id/glazButton"
android:layout_width="match_parent"
android:layout_height="60sp"
android:orientation="horizontal">
<ImageView
android:id="#+id/fuzeIcon"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="10sp"
android:src="#drawable/ic_fuze"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/fuzeIcon"
android:layout_marginLeft="10sp"
android:layout_marginTop="15sp"
android:layout_gravity="center"
android:fontFamily="#font/avenir"
android:text="Fuze"
android:textColor="#ffffff"
android:textSize="25dp" />
<ImageView
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_alignParentEnd="true"
android:layout_marginTop="10sp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_arrow_right" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/tachankaButton"
android:layout_below="#+id/fuzeButton"
android:layout_width="match_parent"
android:layout_height="60sp"
android:orientation="horizontal">
<ImageView
android:id="#+id/tachankaIcon"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="10sp"
android:src="#drawable/ic_tachanka"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/tachankaIcon"
android:layout_marginLeft="10sp"
android:layout_marginTop="15sp"
android:layout_gravity="center"
android:fontFamily="#font/avenir"
android:text="Tachanka"
android:textColor="#ffffff"
android:textSize="25dp" />
<ImageView
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_alignParentEnd="true"
android:layout_marginTop="10sp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_arrow_right" />
</RelativeLayout>
</RelativeLayout>
</ScrollView>
</FrameLayout>
Try to remove the ViewTreeObserver.OnScrollChangedListener when the fragment is destroyed this will avoid any listener that can be attached to a destroyed fragment context not to be triggered whenever you leave and come back to this fragment.
First: make a global field for the listener
public class operatorTab extends Fragment {
...
ViewTreeObserver.OnScrollChangedListener mScrollListener = new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
resetAllButtons();
}
};
Then set the listener wit the created field
private void scrollResetListener(){
scrollView.getViewTreeObserver().addOnScrollChangedListener(mScrollListener);
}
Then remove the listener.. I believe it's typically should be in onDestroyView() >> but also try it in onStop() or onPause if it didn't work
This also will solve memory leak of this listener whenever its callback is triggered after the Fragment's view is destroyed
#Override
public void onDestroyView() {
super.onDestroyView();
scrollView.getViewTreeObserver().removeOnScrollChangedListener(mScrollListener);
}
UPDATE
onStop()/onPause() worked for me
The reason that it didn't work with onDestroyView() because the OperatorTab fragment is a part of one of the ViewPager pages; and by default ViewPager loads a number of close pages in the background to be ready for the next page scroll; loading this pages include some of the fragment lifecycle callbacks like onCreateView, onStart, but not onResume.
When you leave the OperatorTab by scrolling the ViewPager to the next tab/page; onDestroyView() won't be created if the ViewPager decides that OperatorTab is a part of the cached/close pages that the user might return back to it later; and therefore the listener still there and after a few swipes of the pager, the OperatorTab fragment can be detached from the context leaving the listener there with memory leaks...
So, the best way in ViewPager fragment (or any View that loads its fragments in advance) is to stop any listeners once you leave the page, i.e. in onPause or onStop callbacks and not waiting until they are destroyed.
A possible reason for this error is that you are calling getResources() NOT in an Activity without using a context. So, you need to use context.getResources() instead where context may be one of these here . In you instance, I think getContext() will work.
So, I think you should search for all the times you are calling getResources and see if you are using a context or not.
The explanation for this error in a simple way is that you are trying to access the context required in getResources() before the fragment is instantiated.
I have two RadioButtons within a RadioGroup. I also set up a Button, with a setOnClickListener function. When the button is pressed, its supposed to set the float variable gender to a specific value depending on what RadioButton is selected. However, whenever the button is pressed the app crashes.
I've tried setting up a TextView just to see if it would print anything, but the app just crashes when the button is pressed. I looked into the Logcat, and saw that it threw this error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
package com.example.bacwatch;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class ProfileFragment extends Fragment {
private EditText editWeight;
private Button buttonConfirm;
public float gender;
RadioGroup radioGroup;
RadioButton radioButton;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
radioGroup = v.findViewById(R.id.gender_buttons);
editWeight = v.findViewById(R.id.edit_Weight);
buttonConfirm = v.findViewById(R.id.confirm_button);
editWeight.addTextChangedListener(loginTextWatcher);
// Button will input text.
buttonConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Records the gender from the selected radio button.
int radioID = radioGroup.getCheckedRadioButtonId();
radioButton = v.findViewById(radioID);
if (radioButton.getText().equals("Male")) {
gender = (float) .58;
} else {
gender = (float) .49;
}
// Records User's weight (in pounds) and stores it into a variable.
/*float weight = Float.valueOf(editWeight.getText().toString().trim()).floatValue();
// Converts pounds to kilograms.
float kilo_weight = (float) (weight/2.2046);
// Calculates total body water.
float body_water = kilo_weight*gender;*/
// Clears text entries.
editWeight.getText().clear();
}
});
return v;
}
private TextWatcher loginTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String weightInput = editWeight.getText().toString().trim();
buttonConfirm.setEnabled(!weightInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
};
}
XML file:
<?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"
android:background="#android:color/holo_green_light"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender:"
android:textSize="30sp"
android:layout_centerHorizontal="true"
android:id="#+id/gender_text"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/gender_text"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:id="#+id/gender_buttons">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:checked="true"
android:textSize="30sp"
android:id="#+id/male_button"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textSize="30sp"
android:id="#+id/female_button"/>
</RadioGroup>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/gender_buttons"
android:id="#+id/weight_box">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/weight_input">
<android.support.design.widget.TextInputEditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:hint="Weight in Pounds"
android:textSize="30sp"
android:inputType="number"
android:id="#+id/edit_Weight"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/weight_box"
android:layout_centerHorizontal="true"
android:textSize="30sp"
android:text="Confirm"
android:enabled="false"
android:id="#+id/confirm_button"/>
</RelativeLayout>
the app crashes because you tring to get radioButtion from the view that handling the click and not your layout view
radioButton = v.findViewById(radioID);
you have to use another view name to set a difference between them
buttonConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Records the gender from the selected radio button.
int radioID = radioGroup.getCheckedRadioButtonId();
radioButton = v.findViewById(radioID);
if (radioButton.getText().equals("Male")) {
gender = (float) .58;
} else {
gender = (float) .49;
}
......
I want to move the following welcome label and logout button to the tab_profile fragment, right now it's visible in all 4 tabs which i created after successful login
activity_main.xml
<RelativeLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="${relativePackage}.${activityClass}">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome"
android:textSize="20dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#color/lbl_name"
android:textSize="24dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13dp" />
<Button
android:id="#+id/btnLogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="#color/btn_logut_bg"
android:text="#string/btn_logout"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="15dp" />
</LinearLayout>
MainAtivity.java
package gira.cdap.com.giira;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Button;
import android.widget.TextView;
import gira.cdap.com.giira.activity.LoginActivity;
import gira.cdap.com.giira.helper.SQLiteHandler;
import gira.cdap.com.giira.helper.SessionManager;
public class MainActivity extends AppCompatActivity {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
private int[] tabIcons = {
R.drawable.home,
R.drawable.tour,
R.drawable.event,
R.drawable.profile
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[0]));
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[1]));
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[2]));
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[3]));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
tab_profile.xml
<?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"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="tab_profile"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
ProfileActivity.java
package gira.cdap.com.giira.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import gira.cdap.com.giira.R;
public class ProfileActivity extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_profile, container, false);
}
}
PagerAdapter.java
package gira.cdap.com.giira;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import gira.cdap.com.giira.activity.EventActivity;
import gira.cdap.com.giira.activity.HomeActivity;
import gira.cdap.com.giira.activity.ProfileActivity;
import gira.cdap.com.giira.activity.TourActivity;
/**
* Created by Muqshid on 5/10/2016.
*/
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
HomeActivity tab1 = new HomeActivity();
return tab1;
case 1:
TourActivity tab2 = new TourActivity();
return tab2;
case 2:
EventActivity tab3 = new EventActivity();
return tab3;
case 3:
ProfileActivity tab4 = new ProfileActivity();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
From what i understand of your succinct problem, just cut/paste the following:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome"
android:textSize="20dp" />
<Button
android:id="#+id/btnLogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="#color/btn_logut_bg"
android:text="#string/btn_logout"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="15dp" />
In the tab_profile.xml, and you will be good! That's the file you have to work on to personalize your fragment.
I decided to make an app in android for my science exhibition and I have reached a dead end!
I am trying to make a unit converter using radio buttons as the unit selection method.
All is fine but when I select another radio button, the app crashes!
I have no idea what is going on?
Here is my XML layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp" >
<RadioGroup
android:id="#+id/from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left" >
<RadioButton
android:id="#+id/km"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:onClick="radioClicked"
android:text="KiloMeters" />
<RadioButton
android:id="#+id/m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="radioClicked"
android:text="Meters" />
<RadioButton
android:id="#+id/cm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="radioClicked"
android:text="Centimeters" />
</RadioGroup>
<Space
android:id="#+id/Space1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_vertical" />
<EditText
android:id="#+id/KmValue"
android:layout_width="115dp"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginLeft="0dp"
android:ems="10"
android:inputType="numberDecimal" />
<RadioGroup
android:id="#+id/to"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/mTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="38dp"
android:checked="true"
android:onClick="radioClicked"
android:text="Meters" />
<RadioButton
android:id="#+id/cmTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="radioClicked"
android:text="Cenitmeters" />
<RadioButton
android:id="#+id/mmTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="radioClicked"
android:text="Millimeters" />
</RadioGroup>
<TextView
android:id="#+id/MValue"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/cButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Convert" />
</TableLayout>
And here is my Java Activity:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class LengthFragment extends Fragment {
public LengthFragment(){}
double ratio = 1000;
int x=1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_length, container, false);
final EditText km = (EditText) rootView.findViewById(R.id.KmValue);
final TextView meter = (TextView) rootView.findViewById(R.id.MValue);
Button convert = (Button) rootView.findViewById(R.id.cButton);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(km.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "Enter Something Buddy!", Toast.LENGTH_SHORT).show();
} else {
float k = Float.parseFloat(km.getText().toString());
double m = k*ratio;
meter.setText(""+m);
}
}
});
return rootView;
}
public void radioClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.km:
if (checked)
x=1;
break;
case R.id.m:
if (checked) {
x=2;
}
break;
case R.id.cm:
if (checked)
x=3;
break;
case R.id.mTo:
if (checked)
if(x==1) {
ratio=1000;
}
else if(x==2) {
ratio=1;
}
else if(x==3) {
ratio=0.01;
} else {
}
break;
case R.id.cmTo:
if (checked)
if(x==1) {
ratio=100000;
}
else if(x==2) {
ratio=100;
}
else if(x==3) {
ratio=1;
} else {
}
break;
case R.id.mmTo:
if (checked)
if(x==1) {
ratio=1000000;
}
else if(x==2) {
ratio=1000;
}
else if(x==3) {
ratio=10;
} else {
}
break;
}
}
}
I could post whatever may be required for the answer. Please help!
Instead of implementing OnClick to RadioButton just implement RadioGroup setOnCheckedChangeListener :
RadioGroup from = (RadioGroup) rootView.findViewById(R.id.from);
from.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup arg0, int id) {
if (id==R.id.km) {
x=1;
}else if(id==R.id.m){
x=2;
}else if(id==R.id.cm)
x=3;
}
});
Also apply same way setOnCheckedChangeListener for (to) RadioGroup and remove OnClick from xml.
Try adding a different listener for each radio group? Don't just rely on the onClickListener() for the Button.
Try having a setOnCheckedChangeListener for each radio group, e.g.
RadioGroup rgFrom = (RadioGroup) rootView.findViewById(R.id.from);
RadioGroup rgTo = (RadioGroup) rootView.findViewById(R.id.to);
rgFrom.setOnCheckedChangeListener(...)
rgTo.setOnCheckedChangeListener(...)
When the callback is made, i.e. onCheckedChanged, you can update your variables 'x' & 'ratio'
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch(group.getId())
{
case R.id.from:
// Do something to either 'x' or 'ratio'
break;
case R.id.to:
// Do something to either 'x' or 'ratio'
break;
}
}
Refer to the links provided for more detailed information on how to use it.
You can easily do the calculation/conversion when your Button is clicked, instead of having to deal with 'x' or 'ratio'.
Button convert = (Button) rootView.findViewById(R.id.cButton);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do calculations/conversions based on the present state of the 2 radio groups
}
});
I have a piece of code with three RadioButtons within a RadioGroup. I want to set an onCheckedListener that will show the value of the RadioButton in a Toast. However what I have gotten so far is not working. How do I get the value of the RadioButton and display it in a Toast? This is my code:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
RadioGroup rg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
final String value =
((RadioButton)findViewById(rg.getCheckedRadioButtonId()))
.getText().toString();
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast.makeText(getBaseContext(), value, Toast.LENGTH_SHORT).show();
}
});
}
}
XML file:
<RelativeLayout
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="152dp" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 1" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 2" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 3" />
</RadioGroup>
</RelativeLayout>
Tested and working. Check this
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity {
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button btnDisplay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
radioGroup = (RadioGroup) findViewById(R.id.radio);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
xml
<RadioGroup
android:id="#+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_male"
android:checked="true" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_female" />
</RadioGroup>
In case, if you want to do some job on the selection of one of the radio buttons (without having any additional OK button or something), your code is fine, updated little.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio0:
// do operations specific to this selection
break;
case R.id.radio1:
// do operations specific to this selection
break;
case R.id.radio2:
// do operations specific to this selection
break;
}
}
});
}
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
}
}
);
int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();
Hope this works. You can convert your output to string in the above manner.
gender.getCheckedRadioButtonId(); - gender is the id of RadioGroup.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
}
});
For anyone who is populating programmatically and looking to get an index, you might notice that the checkedId changes as you return to the activity/fragment and you re-add those radio buttons. One way to get around that is to set a tag with the index:
for(int i = 0; i < myNames.length; i++) {
rB = new RadioButton(getContext());
rB.setText(myNames[i]);
rB.setTag(i);
myRadioGroup.addView(rB,i);
}
Then in your listener:
myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
int mySelectedIndex = (int) radioButton.getTag();
}
});
just use getCheckedRadioButtonId() function to determine wether if anything is checked, if -1 is the return value, you can avoid showing toast
Radiogroup rgteam;
String team;
rgteam.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
RadioButton rb= (RadioButton) findViewById(checkedId);
team = rb.getText().toString();
}
});
RadioGroup in XML
<?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">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"/>
</RadioGroup>
</RelativeLayout>
activity_main.xml
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:textSize="18dp"
android:text="Select Your Course"
android:textStyle="bold"
android:id="#+id/txtView"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/rdGroup"
android:layout_below="#+id/txtView">
<RadioButton
android:id="#+id/rdbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<Button
android:id="#+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_below="#+id/rdGroup"
android:text="Get Course" />
</RelativeLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioButton android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (RadioButton)findViewById(R.id.rdbAndroid);
angular = (RadioButton)findViewById(R.id.rdbAngular);
java = (RadioButton)findViewById(R.id.rdbJava);
python = (RadioButton)findViewById(R.id.rdbPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = "Selected Course: ";
result+= (android.isChecked())?"Android":(angular.isChecked())?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
});
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
String str="";
// Check which radio button was clicked
switch(view.getId()) {
case R.id.rdbAndroid:
if(checked)
str = "Android Selected";
break;
case R.id.rdbAngular:
if(checked)
str = "AngularJS Selected";
break;
case R.id.rdbJava:
if(checked)
str = "Java Selected";
break;
case R.id.rdbPython:
if(checked)
str = "Python Selected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
Thanks a lot to Chris.
This is my solution:
RadioGroup radgroup_opcionesEventos = null;
private static String[] arrayEventos = {
"CongestiĆ³n", "Derrumbe", "Accidente"
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
radgroup_opcionesEventos = (RadioGroup)findViewById(R.id.rg_opciones_evento);
int i=0;//a.new.ln
for(String evento : arrayEventos) {
//RadioButton nuevoRadio = crearRadioButton(evento);//a.old.ln
RadioButton nuevoRadio = crearRadioButton(evento,i);//a.new.ln
radgroup_opcionesEventos.addView(nuevoRadio,i);
}
RadioButton primerRadio = (RadioButton) radgroup_opcionesEventos.getChildAt(0);
primerRadio.setChecked(true);
}
private RadioButton crearRadioButton(String evento, int n)
{
//RadioButton nuevoRadio = new RadioButton(this);//a.old.ln
RadioButton nuevoRadio = new RadioButton(getApplicationContext());//a.new.ln
LinearLayout.LayoutParams params = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
nuevoRadio.setLayoutParams(params);
nuevoRadio.setText(evento);
nuevoRadio.setTag(evento);
return nuevoRadio;
}
#Override
protected void onResume()
{
radgroup_opcionesEventos.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
//int mySelectedIndex = (int) radioButton.getTag();
String mySelectedIndex = radioButton.getTag().toString();
}
});
super.onResume();
}
I have had problems getting radio buttons id's as well when the RadioButtons are dynamically generated. It does not seem to work if you try to manually set the ID's using RadioButton.setId(). What worked for me was to use View.getChildAt() and View.getParent() in order to iterate through the radio buttons and determine which one was checked. All you need is to first get the RadioGroup via findViewById(R.id.myRadioGroup) and then iterate through it's children. You'll know as you iterate through which button you are on, and you can simply use RadioButton.isChecked() to determine if that is the button that was checked.