Android RadioGroup Cannot resolve symbol getCheckedRadioButtonId - android

I am new to android. At the moment I am working on some examples in my starter book "Android 5"
In the example I am working there is some code which is not working.
XML:
<RadioGroup
android:id="#+id/rg_art"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/rb_art_netto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txt_netto"
android:textSize="16dp"
android:checked="true" />
<RadioButton
android:id="#+id/rb_art_brutto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txt_brutto"
android:textSize="16dp" />
</RadioGroup>
Activity:
package com.example.raven.tax_calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
public class FormularActivity extends Activity {
public static final String BETRAG_KEY = "betrag";
public static final String BETRAG_ART = "art";
public static final String UST_PROZENT = "ust";
// Betrag
public void onClickBerechnen(View button) {
final EditText txtBetrag = (EditText) findViewById(R.id.edt_betrag);
final String tmpBetrag = txtBetrag.getText().toString();
float betrag = 0.0f;
if(tmpBetrag.length() > 0 ){
betrag = Float.parseFloat(tmpBetrag);
}
}
// Art des Betrages (Brutto, Netto)
boolean isNetto = true;
final RadioGroup rg = (RadioGroup) findViewById(R.id.rg_art);
switch (rg.getCheckedRadioButtonId()) {
case R.id.rb_art_netto:
isNetto = "true";
break;
case R.id.rb_art_brutto:
isNetto = false;
break;
default:
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.formular_activity);
}
}
rg.getCheckedRadioButtonId is red highlighted and mouse-over says "Cannot resolve symbol"
What am I doing wrong? Can't find an mistake :-(

You should place following block of code into your on click meaning cut it and paste right after your if statement. The issue is with braces and the fact that you assign string into boolean: (isNetto = "true";)
// Art des Betrages (Brutto, Netto)
boolean isNetto = true;
final RadioGroup rg = (RadioGroup) findViewById(R.id.rg_art);
switch (rg.getCheckedRadioButtonId()) {
case R.id.rb_art_netto:
isNetto = true;
break;
case R.id.rb_art_brutto:
isNetto = false;
break;
default:
}

Related

Memorize the last radio button clicked

Assume a group of 4 radio buttons. The user clicks on the first one, then he for example realizes that he made a mistake and he clicked on the 4th one. Is there a way to memorize just the last one clicked and to make the app forgets that the 1st one was clicked too?
Here is the simple example using SharedPreferences. Easier, less cumbersome than Sqlite.
Layout
demo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RadioGroup
android:id="#+id/rank_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkedButton="#+id/first_radio"
android:layout_gravity="center_horizontal"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/first_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First" />
<RadioButton
android:id="#+id/second_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second" />
<RadioButton
android:id="#+id/third_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Third" />
<RadioButton
android:id="#+id/fourth_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fourth" />
</RadioGroup>
</LinearLayout>
Activity
DemoAppActivity.java
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
public class DemoAppActivity extends ActionBarActivity implements
OnCheckedChangeListener {
private RadioButton mFirstRadioButton = null;
private RadioButton mSecondRadioButton = null;
private RadioButton mThirdRadioButton = null;
private RadioButton mFourthRadioButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_app);
initializeRadioGroup();
}
private void initializeRadioGroup() {
mFirstRadioButton = (RadioButton) findViewById(R.id.first_radio);
mSecondRadioButton = (RadioButton) findViewById(R.id.second_radio);
mThirdRadioButton = (RadioButton) findViewById(R.id.third_radio);
mFourthRadioButton = (RadioButton) findViewById(R.id.fourth_radio);
// Fetching last checked position in preferences
int lastCheckedPosition = PreferenceManager
.getDefaultSharedPreferences(this).getInt("last_checked", 0);
Log.d("TAG", "Fetching last saved position " + lastCheckedPosition);
switch (lastCheckedPosition) {
case 1:
mFirstRadioButton.setChecked(true);
break;
case 2:
mSecondRadioButton.setChecked(true);
break;
case 3:
mThirdRadioButton.setChecked(true);
break;
case 4:
mFourthRadioButton.setChecked(true);
break;
default:
mFirstRadioButton.setChecked(true);
break;
}
mFirstRadioButton.setOnCheckedChangeListener(this);
mSecondRadioButton.setOnCheckedChangeListener(this);
mThirdRadioButton.setOnCheckedChangeListener(this);
mFourthRadioButton.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int newCheckedPos = 0;
if (isChecked) {
switch (buttonView.getId()) {
case R.id.first_radio:
newCheckedPos = 1;
break;
case R.id.second_radio:
newCheckedPos = 2;
break;
case R.id.third_radio:
newCheckedPos = 3;
break;
case R.id.fourth_radio:
newCheckedPos = 4;
break;
}
}
if (newCheckedPos > 0) {
Log.d("TAG", "Saving new checked position " + newCheckedPos);
// Saving checked position in preferences
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putInt("last_checked", newCheckedPos).commit();
}
}
}

Unable to imlement drag and drop

I am trying to make a alphabet exam. I have a ImageView11 which shows the a random alphabet which you have to guess. And the imageView_alphabet_image_1 and imageView_alphabet_image_2 will show two options which I have to guess and I will drag the ImageView11 image on correct ImageView which is showing down. But I'm able to do it for only first time when i click on refresh it always showing incorrect toast
<LinearLayout 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:orientation="vertical" >
<Button
android:id="#+id/btn_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh"/>
<LinearLayout
android:id="#+id/dragLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgView_des"
android:layout_width="70dp"
android:layout_height="80dp"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/bottomLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:orientation="horizontal"
android:weightSum="1" >
<ImageView
android:id="#+id/imgView_alphabetImage_1"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_weight="0.25"
android:src="#drawable/a" />
<ImageView
android:id="#+id/imgView_alphabetImage_2"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_weight="0.25"
android:src="#drawable/a" />
</LinearLayout>
package com.example.cleardoubt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener,
OnTouchListener, OnDragListener {
private ImageView _imgView_des;
private ImageView _imgView_alphabetImage_1;
private ArrayList<Integer> _alphabet_arrayList;
private Button _btn_refresh;
private ImageView _imgView_alphabetImage_2;
private ArrayList<Integer> _tempArrayList;
private ArrayList<Integer> _finalTempArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
setContentView(R.layout.activity_main);
_imgView_des = (ImageView) findViewById(R.id.imgView_des);
_imgView_des.setOnClickListener(this);
_imgView_des.setOnTouchListener(this);
_imgView_des.setOnDragListener(this);
_imgView_alphabetImage_1 = (ImageView) findViewById(R.id.imgView_alphabetImage_1);
_imgView_alphabetImage_1.setOnClickListener(this);
_imgView_alphabetImage_1.setOnDragListener(this);
_imgView_alphabetImage_2 = (ImageView) findViewById(R.id.imgView_alphabetImage_2);
_imgView_alphabetImage_2.setOnClickListener(this);
_imgView_alphabetImage_2.setOnDragListener(this);
_btn_refresh = (Button) findViewById(R.id.btn_refresh);
_btn_refresh.setOnClickListener(this);
}
private void initView() {
_alphabet_arrayList = new ArrayList<Integer>();
_alphabet_arrayList.add(R.drawable.a);
_alphabet_arrayList.add(R.drawable.b);
_alphabet_arrayList.add(R.drawable.c);
_alphabet_arrayList.add(R.drawable.d);
_alphabet_arrayList.add(R.drawable.e);
_alphabet_arrayList.add(R.drawable.f);
_alphabet_arrayList.add(R.drawable.g);
_tempArrayList = new ArrayList<Integer>();
_finalTempArrayList = new ArrayList<Integer>();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgView_des:
break;
case R.id.imgView_alphabetImage_1:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_1.getDrawable()
.getConstantState())) {
Toast.makeText(this, "matched", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not matched", Toast.LENGTH_SHORT).show();
}
break;
case R.id.imgView_alphabetImage_2:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_2.getDrawable()
.getConstantState())) {
Toast.makeText(this, "matched", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not matched", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_refresh:
Random random = new Random();
int index = random.nextInt(7);
_imgView_des.setImageResource(_alphabet_arrayList.get(index));
_imgView_des.setVisibility(View.VISIBLE);
_tempArrayList = (ArrayList<Integer>) _alphabet_arrayList.clone();
_tempArrayList.remove(index);
Collections.shuffle(_tempArrayList, random);
for (int j = 0; j < 1; j++) {
_finalTempArrayList.add(_tempArrayList.get(j));
}
_finalTempArrayList.add(_alphabet_arrayList.get(index));
Collections.shuffle(_finalTempArrayList);
Log.e(" _finalTempArrayList after suffel", _finalTempArrayList.toString());
_imgView_alphabetImage_1.setImageResource(_finalTempArrayList.get(0));
_imgView_alphabetImage_2.setImageResource(_finalTempArrayList.get(1));
_finalTempArrayList.clear();
break;
default:
break;
}
}
#Override
public boolean onTouch(View v, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
// ClipData clipData = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(null, shadowBuilder, v, 0);
v.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
#Override
public boolean onDrag(View v, DragEvent e) {
switch (e.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// if (e.getClipDescription().hasMimeType(
// ClipDescription.MIMETYPE_TEXT_PLAIN)) {
// return true;
// } else {
// Toast.makeText(this, "can not accept the image",
// Toast.LENGTH_SHORT).show();
//
// }
// return false;
break;
case DragEvent.ACTION_DROP:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_1.getDrawable()
.getConstantState())) {
ViewGroup viewGroup = (ViewGroup) v.getParent();
viewGroup.removeView(_imgView_des);
v.setBackground(this.getResources().getDrawable(R.drawable.a));
return true;
}
else if(_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_2.getDrawable()
.getConstantState()))
{
ViewGroup viewGroup = (ViewGroup) v.getParent();
viewGroup.removeView(_imgView_des);
v.setBackground(this.getResources().getDrawable(R.drawable.a));
return true;
}
// else {
// return false;
// }
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.v("a", e.getResult() + "");
if (e.getResult()) {
_imgView_des.setVisibility(View.INVISIBLE);
Log.v("asddd", e.getResult() + "");
Toast.makeText(this, " accept the image",
Toast.LENGTH_SHORT).show();
return true;
} else {
_imgView_des.setVisibility(View.VISIBLE);
Toast toast = new Toast(this);
ImageView view = new ImageView(this);
view.setImageResource(R.drawable.unsuccess);
toast.setView(view);
toast.show();
return true;
}
default:
break;
}
return false;
}
}
I checked you code the problem is in your onDrag method.
case DragEvent.ACTION_DROP event did not call because of you did not return flag case DragEvent.ACTION_DRAG_STARTED: event. You have to pass true flag like below code
case DragEvent.ACTION_DRAG_STARTED:
return true;

check if the right radioButton is checked and calculate the score

i have an android application that display a flag and group of radio buttons that each time the user check any radio button the application will display a button that allow to go to the next page using intent .
what i need is that each time the user check the right answer the system must calculate its score until the application finish .
the score will start by 0/0 and will finish after four rounds.
for now i need just to display the score of the user in the second page
i will appreciate any help
MainActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnS;
RadioGroup rdgS;
RadioButton rdS1, rdS2, rdS3, rdS4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rdgS = (RadioGroup) findViewById(R.id.rdg1);
rdgS.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if(rdS1.isChecked()||rdS2.isChecked()||rdS3.isChecked()||rdS4.isChecked()){
btnS.setVisibility(View.VISIBLE);
}
}
});
rdS1 = (RadioButton) findViewById(R.id.rd_s1);
rdS2 = (RadioButton) findViewById(R.id.rd_s2);
rdS3 = (RadioButton) findViewById(R.id.rd_s3);
rdS4 = (RadioButton) findViewById(R.id.rd_s4);
btnS = (Button) findViewById(R.id.btn_s);
btnS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input;
String result = null;
Double dbl;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (v.getId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
i.putExtra("score", 0);
break;
case R.id.rd_s2:
i.putExtra("score", 0);
break;
case R.id.rd_s3:
i.putExtra("score", 25);
break;
case R.id.rd_s4:
i.putExtra("score", 0);
break;
default:
break;
}
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.hint_icon:
ShowAlertDialog();
break;
case R.id.about_icon:
Toast.makeText(this, "developed by Georges Matta",
Toast.LENGTH_SHORT).show();
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void ShowAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hint")
.setMessage("The famouse sport is Bullfighting")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
edited code
rdS1 = (RadioButton) findViewById(R.id.rd_s1);
rdS2 = (RadioButton) findViewById(R.id.rd_s2);
rdS3 = (RadioButton) findViewById(R.id.rd_s3);
rdS4 = (RadioButton) findViewById(R.id.rd_s4);
btnS = (Button) findViewById(R.id.btn_s);
btnS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input;
String result = null;
Double dbl;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (rdgS.getCheckedRadioButtonId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
result = String.valueOf(dbl);
i.putExtra("score", result);
break;
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"
android:background="#drawable/background"
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" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="34dp"
android:src="#drawable/spanish" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Gess the Country of the flag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#CCFF99" />
<RadioGroup
android:id="#+id/rdg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView1" >
<RadioButton
android:id="#+id/rd_s1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Egypt"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="China"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spanish"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/radioGroup1"
android:layout_below="#+id/radioGroup1"
android:text="Italy"
android:textColor="#CCFF99" />
</RadioGroup>
<Button
android:id="#+id/btn_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/rdg1"
android:layout_below="#+id/rdg1"
android:text="Next"
android:visibility="invisible" />
</RelativeLayout>
SecondActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class SecondActivity extends Activity {
TextView txt_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
txt_result = (TextView) findViewById(R.id.txtResult);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("score");
txt_result.setText(value);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
activity_second.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"
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=".SecondActivity" >
<TextView
android:id="#+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Simple solution is to modify your switch case as follows:
...
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (rdgS.getCheckedRadioButtonId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
i.putExtra("score", 0);
break;
case R.id.rd_s2:
i.putExtra("score", 0);
break;
case R.id.rd_s3:
i.putExtra("score", 25);
break;
case R.id.rd_s4:
i.putExtra("score", 0);
break;
default:
break;
}
startActivity(i);
...
...
After this since your are passing in int values, you should use getInt() method. In your oncreate of SecondActivity do this:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = String.valueOf(extras.getInt("score"));
txt_result.setText(value);
}
There is a problem here:
Intent intent = new Intent(MainActivity.this, SecondPage.class);
intent.putExtra("showResult", result);
startActivity(intent);
This should match extras.getString("score"); string in the second activity, so change it to:
Intent intent = new Intent(MainActivity.this, SecondPage.class);
intent.putExtra("score", result);
startActivity(intent);
In your onClick(View v) handler, v refers to the button btn_s, therefore switch (v.getId()) will not work since v.getId() will always return id of the button, i.e. R.id.btn_s.
You need to query states of the radio button separately, for example use
if (rdS1.isChecked()) {
// first ratio button is checked
} else if (rdS2.isChecked()) {
// second is checked
} else if ...
Replace your switch (v.getId()) in onClick(View v) with that if.

How to keep state of RadioButton in Android?

Hi I'm trying to develop an application which runs for every interval time, lets say for every 1 minute it will display some Toast message.
But problem is I'm using RadioButton functionality is perfect but when I tap on one radio button it will be green, but when I close and re-open the activity I'll get as none of the radio buttons selected.
Here is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
//some code
}
break;
}
}
}
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/radio">
<RadioButton android:id="#+id/radio_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_one_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ten_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10 minute"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Please help me to solve this riddle.
Thanks in advance...
This code is useful for store the ratingbar state, when we start new activity, you will see the previous rating state..
package com.example.ratingbar;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class RatingbarMainActivity extends Activity {
RatingBar ratingbarClick;
Button sub_btn;
TextView textRatingView , textRatingViewSave;
Boolean val = true;
float ans = (float) 0.0;
//--------------------------------------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ratingbar_main);
ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
ratingbarClick.setOnRatingBarChangeListener(rateObj);
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
ans = sharePref.getFloat("Get_Rating", 0.0f);
System.out.println("--------------------------------------ans = " + ans);
if(val) {
ratingbarClick.setRating(ans);
}
else {
ratingbarClick.setRating(ans);
}
textRatingView = (TextView) findViewById(R.id.ratingView);
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
//textRatingView.setText(String.valueOf(rating));
ans = ratingbarClick.getRating();
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
SharedPreferences.Editor edit = sharePref.edit();
edit.putFloat("Get_Rating", ans);
edit.commit();
val = false;
}
};
//--------------------------------------------------------------------------------------------
}
---------------------------------------------------------------------------------------------------
activity_ratingbar_main.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" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ratingBar1"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="23dp"
android:text="Select Your Rating Bar Here"
tools:context=".RatingbarMainActivity" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="63dp" />
<TextView
android:id="#+id/ratingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ratingBar1"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Click To Save Rating In TextBox" />
</RelativeLayout>
it is the simplest way to do so,no need of sharedpreference at all.you will get confused while using it.keep the things simple like this
public class MainActivity extends Activity {
Public static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(flag==1)
radio_one_min.setChecked(true);
else if(flag==2)
radio_ten_min.setCheckek(true);
else if(flag==3)
radio_disable.setCheckek(true);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
flag =1;
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
flag=2 ;
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
flag=3;
//some code
}
break;
}
}
}
[EDITED]
I found developer.android.com/training/basics/activity-lifecycle/recreating.html document first, so my first guess was using Bundles and on Save/Resume Instace State methods. However this does not seem to work well. Here's my final attempt at a working solution (using SharedPreferences class, as suggested by some users):
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class MainActivity extends Activity {
final String PREFERENCES = "prefs";
final String RADIO_BUTTON = "prefsval";
SharedPreferences sp;
Editor e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
e = sp.edit();
}
#Override
protected void onResume() {
super.onResume();
if (sp != null) {
if (sp.getInt(RADIO_BUTTON, 0) != 0) {
RadioButton rb;
rb = (RadioButton) findViewById(sp.getInt(RADIO_BUTTON, 0));
rb.setChecked(true);
}
}
}
public void onRadioButtonClicked(View view) {
e.putInt(RADIO_BUTTON, view.getId());
e.apply();
}
}

Android 4 SDK text.getText() error in Eclipse

I been thinking about developing for Android for some time now, and I finally took the plunge.
Eclipse is set up, Android SDK, and ADT Plugin for eclipse is also.
I found a tutorial on line and was following it's instructions.
My problem that I can not figure out is that Eclipse generates and error with the following code, primarily the text.setText() and text.getText() calls, it underlines the text portion of it:
Am I missing an import?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class testActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
// This method is called at button click because we assigned the name to the
// "On Click property" of the button
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radioButton1);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radioButton2);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else {
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit) {
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
}
Instead of your code use this,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class ConvertActivity extends Activity {
private EditText text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
}
// This method is called at button click because we assigned the name to the
// "On Click property" of the button
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else {
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit) {
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/myColor"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal|numberSigned" >
</EditText>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/celsius" >
</RadioButton>
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/fahrenheit" >
</RadioButton>
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClickHandler"
android:text="#string/calc" >
</Button>
</LinearLayout>
You didn't declare the textedit object.
In your onCreate method add:
text = (EditText) findViewById(R.id.editText1);
editText1 maybe different, depending on ur main.xml layout file
Also add, before the onCreate method this:
private EditText text;
Seems like you have not declared text, what is it a TextView or an EditText?
Define it like this
public class testActivity extends Activity {
/** Called when the activity is first created. */
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.yourTextViewId);
}
After declaring it this way you wouldn't see the error.

Categories

Resources