How to keep state of RadioButton in Android? - 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();
}
}

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

TimePicker + CheckBox

I've got a TimePicker in my app and i want to add above it a CheckBox that if it checked the TimePicker won't work. This is my TimePicker: http://developer.android.com/guide/topics/ui/controls/pickers.html#TimePicker.
How can I do that? I want the timePicker to look the same as the example.
I will put here the entire project also for others to use it if they ever need it:
Short description: A program that let's you get the time set by user and show it in the bottom of the page, after you press Done button.Used intent to get from one activity to another.
--------Main Activity-------
package com.example.chxboxtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button start_intent_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start_intent_button = (Button) findViewById(R.id.start_intent_button);
start_intent_button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_intent_button: {
Intent intent = new Intent(this,TimePickerTest.class);
startActivity(intent);
}
break;
}
}
}
-------------Main Activity 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"
>
<Button
android:id="#+id/start_intent_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Intent Time Picker"
android:layout_centerInParent="true"
/>
</RelativeLayout>
-------------TimePicker class ---------------
package com.example.chxboxtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class TimePickerTest extends Activity implements OnClickListener{
private CheckBox cBox;
private TimePicker tPicker;
private TextView showTime;
private Button done;
private String hour;
private String minute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_picker_layout);
initButtons();
}
private void initButtons() {
tPicker = (TimePicker) findViewById(R.id.time_picker);
showTime = (TextView) findViewById(R.id.get_time);
done = (Button)findViewById(R.id.done);
cBox = (CheckBox) findViewById(R.id.time_picker_checkbox);
cBox.setOnClickListener(this);
done.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
//If check enable or disble timePicker
case R.id.time_picker_checkbox: {
if (((CheckBox) v).isChecked()) {
Toast.makeText(this, "CHECKED", Toast.LENGTH_SHORT).show();
tPicker.setEnabled(false);
} else {
Toast.makeText(this, "NOT CHECKED", Toast.LENGTH_SHORT).show();
tPicker.setEnabled(true);
}
}
break;
//If Done button pressed get time selected by user
case R.id.done:{
tPicker.clearFocus();
// re-read the values, in my case i put them in a Time object.
hour = tPicker.getCurrentHour().toString();
minute = tPicker.getCurrentMinute().toString();
if(tPicker.getCurrentMinute().intValue() < 10){
String setTimeText = hour+ " : " + "0" + minute;
showTime.setText(setTimeText);
}else{
String setTimeText = hour+ " : " + minute;
showTime.setText(setTimeText);
}
}
break;
default:
break;
}
}
}
-------------TimerPicker 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/timer_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
android:layout_toRightOf="#+id/time_picker_checkbox"
android:text="Check this to Cancel Alarm" />
<CheckBox
android:id="#+id/time_picker_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
android:layout_centerHorizontal="true" />
<TimePicker
android:id="#+id/time_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/time_picker"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Done" />
<TextView
android:id="#+id/get_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="Time"
android:textColor="#FF0000"
android:textSize="25sp" />
</RelativeLayout>
-------------Manifest.xml-----------
**<activity
android:name="com.example.chxboxtest.TimePickerTest"
android:configChanges="orientation|keyboardHidden">
</activity>**
Dont forget to add TimePicker class as activity.
BestPracice add all xml text in strings.xml
Cheers
Here's an functional example with all your requirements.
Tested and 100% functional :)
Put this in 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"
>
<TextView
android:id="#+id/timer_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check this to Cancel Alarm"
android:layout_above="#+id/time_picker"
android:layout_toRightOf="#+id/time_picker_checkbox"
/>
<CheckBox
android:id="#+id/time_picker_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
/>
<TimePicker
android:id="#+id/time_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
And Here is your java code:
package com.example.chxboxtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private CheckBox cBox;
private TimePicker tPicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initButtons();
}
private void initButtons() {
tPicker = (TimePicker) findViewById(R.id.time_picker);
cBox = (CheckBox) findViewById(R.id.time_picker_checkbox);
cBox.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.time_picker_checkbox: {
if (((CheckBox) v).isChecked()) {
Toast.makeText(this, "Deactivate",Toast.LENGTH_SHORT).show();
tPicker.setEnabled(false);
} else {
Toast.makeText(this, "Activate",Toast.LENGTH_SHORT).show();
tPicker.setEnabled(true);
}
}
break;
default:
break;
}
}
}
If you want this example in a custom dialog please let me know.
Cheers,

Android onclick Buttons Sequence

I have 5 buttons every one has letter (Button "H",Button "E"Button "L"Button "L"Button "O") which make the word "HELLO". what I need is to make on click sequence to these buttons so if I click "H" first and "E" second until complete the word the app will do something, But if I click "L" first will give me some error message.
Any Idea to do this sequence?
Thanks
Just have an Array like this:
int[] tracker = new int[5];
and when you click a button, say "H", set tracker[0] = 1;
but when you click a button, say "L", check whether all the previous button values are 1. If yes, then set the corresponding tracker to 1 else, show an error message, and do not make any change to the tracker Array.
Something Like this:
onHClick{
tracker[0] = 1;
}
onEClick{
for(int i=0; i<1; i++){
if(tracker[i] == 0){
//show error message and return;
}else{
tracker[1] = 1;
return;
}
}
}
You can do something like
When activity started you just make other button Enabled = false of something like that. But make the first button Enabled. Don't make the Visible=false.
Now on click of Button "H" make enable Button "E" and so on.
So user will only have to click the button in sequence. Button can not be presses in any random manner.
Try this and let me know that it works or not.
Very Interesting and exactly same to your requirement..check once..
If you give any string other than HELLO also works better.
public class ButtonTest extends Activity
{
private String result="";
String sampleText = "HELLO";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
int noOfBtns = sampleText.length();
LinearLayout ll = (LinearLayout)findViewById(R.id.btnlay);
final TextView tvtext = (TextView)findViewById(R.id.result);
final Button[] btns = new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setText(sampleText.substring(i,i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
System.out.println(j+" "+result.length());
if(j == result.length())
{
result = result+btns[j].getText().toString();
if(sampleText.startsWith(result))
{
tvtext.setText(result);
}
}
else
{
Toast.makeText(getApplicationContext(), "Wrong Button Pressed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/result"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textColor="#fff"/>
<LinearLayout
android:id="#+id/btnlay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Try the following
package com.example.buttonsequence;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ArrayList<Button> buttonList=null;
TextView resultTextView=null;
Button buttons[]=null;
String helloStr="HELLO";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
buttons=new Button[5];
this.resultTextView=(TextView) this.findViewById(R.id.result_text);
this.resultTextView.setText("");
buttons[0]=(Button)this.findViewById(R.id.h_button);
buttons[1]=(Button)this.findViewById(R.id.e_button);
buttons[2]=(Button)this.findViewById(R.id.l_button);
buttons[3]=(Button)this.findViewById(R.id.l2_button);
buttons[4]=(Button)this.findViewById(R.id.o_button);
for(int k=0;k<5;k++)
buttons[k].setOnClickListener(onClickListener);
Button button=(Button)this.findViewById(R.id.exit_button);
button.setOnClickListener
(
new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
);
}
OnClickListener onClickListener=new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Button b=(Button)v;
buttonList.add(b);
int size=buttonList.size();
if(size>0)
{
StringBuilder resultBuilder=new StringBuilder();
for(int i=0;i<size;i++)
{
Button tempButton=buttonList.get(i);
if(tempButton==buttons[i])
{
resultBuilder.append(helloStr.charAt(i));
if(i==4)
{
resultTextView.setText(resultBuilder.toString()+" clicked");
buttonList.clear();
}
else
{
resultTextView.setText(resultBuilder.toString()+" clicked");
}
}
else
{
buttonList.remove(i);
Toast.makeText(getApplicationContext(), "No correctly clicked", Toast.LENGTH_SHORT).show();
break;
}
}
}
else
{
resultTextView.setText("Invalid pressed");
}
}
};
}
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/h_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="H" />
<Button
android:id="#+id/e_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E" />
<Button
android:id="#+id/l_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/l2_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/o_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" />
<TextView
android:id="#+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/exit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
I don't know exactly your flow but you can try this.
set Tag to each button as its Text, like this.
b.setTag("H");
and than after like this.
Button b;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = (String) v.getTag();
name +=s;
if( "HELLO".startsWith(name)){
<VALID>
}else{
<ERROR>
}
}
});
}
check the variable name on each button click with your original word i.e. HELLO like above.

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.

Taking double numbers back to previous activity

This is what i want to do with my application:
Open overview screen, go to calculator by button.
Than multiply two numbers.
By clicking calculate the intent will finish.
Outcome of multiply will be shown in first (main) activity.
I do not know how to do the last bit, someone any idea?
Code first (main) activity, OverviewpageActivity.java
package com.tip.calc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class OverviewpageActivity extends Activity {
private TextView multiplydisplay2;
private Button btntocalculator;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview);
multiplydisplay2 = (TextView)findViewById(R.id.multiplydisplay2);
btntocalculator = (Button)findViewById(R.id.btntocalculator);
btntocalculator.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
Intent intent = new Intent(OverviewpageActivity.this,
TipcalcActivity.class);
startActivity(intent);
}
});
}
}
Code calculator acticvity, TipcalcActivity.java:
package com.tip.calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TipcalcActivity extends Activity {
private EditText number1;
private EditText number2;
private TextView multiplydisplay;
private Button btncalculate;
private Button btnreset;
private double number1calc = 0;
private double number2calc = 0;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
number1 = (EditText)findViewById(R.id.number1);
number2 = (EditText)findViewById(R.id.number2);
multiplydisplay = (TextView)findViewById(R.id.multiplydisplay);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ reset(); }});
}
private void calculate() {
// check if zero
if(number1.getText().toString().trim().length() < 1 ){number1calc=0;}
else{number1calc=Double.parseDouble(number1.getText().toString());}
if(number2.getText().toString().trim().length() < 1 ){number2calc=0;}
else{number2calc=Double.parseDouble(number2.getText().toString());}
//calculate
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
finish();
}
private void reset() {
multiplydisplay.setText("");
number1.setText("");
number2.setText("");
finish();
}
}
Layout file, overview.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- multiply -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="multiply:" />
<TextView
android:id="#+id/multiplydisplay2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="20dp" />
</LinearLayout>
<Button
android:id="#+id/btntocalculator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To the calculator" />
</LinearLayout>
Use startActivityforResult instead of startActivity in OverviewpageActivity.java and also override OnactivityResult in OverviewpageActivity.java.
Then in second activity you can set the result using setResult. Pass the intent in setresult which will have the double value.
In OnactivityResult you can get the intent from which you can extract double

Categories

Resources