I am trying to make a pedometer.
So as can be seen, once the acceleration of one particular direction exceeds 1, the counter increments by 1. Then I wanna display the count number in the textView.
However, the textView is always displayed as "TextView" instead of the desired number.
Any idea? Thanks!
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
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;
public class MainActivity extends Activity implements SensorEventListener {
Button startButton;
Button pauseButton;
Button resetButton;
TextView textView;
private SensorManager sensorManager;
private long lastUpdate;
private boolean isCalibrated = false;
private int referrenceAxis;
private int stepCounts = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
// start button
startButton = (Button) findViewById(R.id.button1);
startButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
// pause button
pauseButton = (Button) findViewById(R.id.button2);
pauseButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
// reset button
resetButton = (Button) findViewById(R.id.button3);
resetButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
init();
}
#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;
}
public void init() {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
long actualTime = System.currentTimeMillis();
if (isCalibrated && (actualTime - lastUpdate > 500)) {
if (event.values[referrenceAxis] > 1) {
stepCounts++;
textView.setText(String.valueOf(stepCounts));
}
}
lastUpdate = actualTime;
}
if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
if (!isCalibrated) {
if ((event.values[0] >= event.values[1])&&(event.values[0] >= event.values[2]))
referrenceAxis = 0;
if ((event.values[1] >= event.values[0])&&(event.values[1] >= event.values[2]))
referrenceAxis = 1;
if ((event.values[2] >= event.values[0])&&(event.values[2] >= event.values[1]))
referrenceAxis = 2;
isCalibrated = true;
}
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
protected void onResume() {
super.onResume();
// register this class as a listener for the sensors
sensorManager
.registerListener(this, sensorManager
.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),
SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
// unregister listener
super.onPause();
sensorManager.unregisterListener(this);
}
}
XML is as follows:
<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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_centerHorizontal="true"
android:text="#string/button2" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/button3" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/textview" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="14dp"
android:text="#string/step_mumber"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
In Here :
textView.setText(stepCounts); //<<<
you are passing Integer Value to TextView.setText method that's why you are getting Resources$NotFoundException . show Integer value in TextView as:
textView.setText(String.valueOf(stepCounts));
Or simpler just use ""+number in setText() method.
Related
I am developing an android step counter that starts counting when i press a button and stops when i press the button again. The problem is that the counter always misses the first few steps i am using the step counter sensor introduced in android kitkat 4.4. I also tried the step detector sensor but had the same results.
I tried changing the delay when registering the sensor to fastest, game, normal, and I even tried to set the delay to 0 but nothing worked
Is there a way i can fix this?
this is a simple app that shows my problem
https://github.com/omaressameldin/simplestepcounter
MainActivity.java
package com.example.oessa_000.simplestepcounter;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
ToggleButton countToggle;
TextView stepView;
private int stepCount = 0;
boolean toggle = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
stepView = (TextView) findViewById(R.id.stepView);
countToggle = (ToggleButton) findViewById(R.id.countToggle);
;
countToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle = !toggle ;
if(toggle){
startListening();
}
else{
stopListening();
}
}
});
}
protected void startListening() {
mSensorManager.registerListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void stopListening() {
mSensorManager.unregisterListener(this, mStepCounterSensor);
}
public void onResume() {
super.onResume();
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
switch(sensor.getType()) {
case Sensor.TYPE_STEP_COUNTER:
if (toggle){
stepCount++;
stepView.setText("Step Count: " + stepCount);
}
break;
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.oessa_000.simplestepcounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Step Count: 0"
android:textSize="15dp"
android:id="#+id/stepView"
/>
<ToggleButton
android:layout_width="200dp"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
android:id="#+id/countToggle"
android:layout_margin="20dp"
android:textOff="Not Walking"
android:textOn="Walking"
android:layout_below="#+id/stepView"
/>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.oessa_000.simplestepcounter">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<uses-feature android:name="android.hardware.sensor.stepcounter" />
</activity>
</application>
</manifest>
Edited: Added code snippets
I realized that using the predefined stepCounter sensor for small number of steps, like what i wanted, isn't the best option and implementing a counter using accelerometer would be a lot better; however it won't be recommended for building fitness apps or any app that require constant step counting for a long time because the delay in the stepcounting sensor is to neglect the false positives.
so this is my implementation of the stepcounter using accelerometer
MainActivity.java
package com.example.oessa_000.testcompass;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements SensorEventListener{
// Gravity for accelerometer data
private float[] gravity = new float[3];
// smoothed values
private float[] smoothed = new float[3];
// sensor manager
private SensorManager sensorManager;
// sensor gravity
private Sensor sensorGravity;
private double bearing = 0;
private TextView acc;
private TextView stepView;
private TextView thresholdView;
private SeekBar seek;
private ToggleButton countToggle;
private int stepCount;
private boolean toggle;
private double prevY;
private double threshold;
private boolean ignore;
private int countdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acc = (TextView) findViewById((R.id.accelerometer));
thresholdView = (TextView) findViewById((R.id.thresholdView));
stepView = (TextView) findViewById((R.id.stepView));
countToggle = (ToggleButton) findViewById(R.id.countToggle);
seek = (SeekBar) findViewById(R.id.seek);
seek.setProgress(0);
seek.incrementProgressBy(1);
seek.setMax(40);
// keep screen light on (wake lock light)
implementListeners();
}
protected float[] lowPassFilter( float[] input, float[] output ) {
if ( output == null ) return input;
for ( int i=0; i<input.length; i++ ) {
output[i] = output[i] + 1.0f * (input[i] - output[i]);
}
return output;
}
#Override
protected void onStart() {
super.onStart();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorGravity = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// listen to these sensors
sensorManager.registerListener(this, sensorGravity,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
super.onStop();
// remove listeners
sensorManager.unregisterListener(this, sensorGravity);
}
#Override
public void onSensorChanged(SensorEvent event) {
// get accelerometer data
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// we need to use a low pass filter to make data smoothed
smoothed = lowPassFilter(event.values, gravity);
gravity[0] = smoothed[0];
gravity[1] = smoothed[1];
gravity[2] = smoothed[2];
acc.setText("x: "+gravity[0] + " y: " + gravity[1] + " z: " + gravity[2]+ "ignore: "+ ignore + "countdown: "+ countdown);
if(ignore) {
countdown--;
ignore = (countdown < 0)? false : ignore;
}
else
countdown = 22;
if(toggle && (Math.abs(prevY - gravity[1]) > threshold) && !ignore){
stepCount++;
stepView.setText("Step Count: " + stepCount);
ignore = true;
}
prevY = gravity[1];
}
}
public void implementListeners(){
seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
threshold = ((double)seek.getProgress()) * 0.02;
thresholdView.setText("Threshold: "+ threshold);
}
});
countToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle = !toggle ;
if(toggle){
stepCount = 0;
countdown = 5;
ignore = true;
stepView.setText("Step Count: " + stepCount);
}
}
});
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.oessa_000.testcompass.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_below="#+id/degree"
android:id="#+id/accelerometer"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Step Count: 0"
android:textSize="24dp"
android:layout_centerHorizontal="true"
android:id="#+id/stepView"
android:layout_below="#+id/accelerometer"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_marginBottom="0dp"
android:layout_below="#+id/stepView"
android:id="#+id/thresholdView"
/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/seek"
android:layout_marginTop="0dp"
android:layout_below="#+id/thresholdView"
/>
<ToggleButton
android:layout_width="200dp"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
android:id="#+id/countToggle"
android:layout_margin="20dp"
android:textOff="Not Walking"
android:textOn="Walking"
android:layout_below="#+id/seek"
/>
</RelativeLayout>
Adjusting the threshold sets the sensitivity of the sensor :)
Reference: http://nebomusic.net/androidlessons/Pedometer_Project.pdf
I am using Android Studio
I'm wanting to change the color of my button, with each click.
To cycle it through around 10 colors and start over again in a continuous loop.
For example I'm using setBackgroundResource(#drawable/oval)
oval = blue circle button
oval2 = red circle button
oval3 = green circle button and so on.
So far I have it that button1 starts as oval(blue) and onClick turns into oval2(red)
So my question is, how to add another click to change it to oval3(green) and then cycle it back to the start oval(blue)?
MainActivity.java
package com.example.shadowz.buttononclick;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.view.TintableBackgroundView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
private Button colorChangeButton;
private TextView basicText;
private RelativeLayout background;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Drawable oval1;
Drawable oval2;
Drawable oval3;
Drawable oval4;
Drawable oval5;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
background = (RelativeLayout) findViewById(R.id.backgroundLayout);
basicText = (TextView) findViewById(R.id.button1);
colorChangeButton = (Button) findViewById(R.id.button1);
// Code Break
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
// Code Break
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button1) {
button1.setBackgroundResource(R.drawable.oval2);
}
}
});
// Code Break
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button2) {
button2.setBackgroundResource(R.drawable.oval3);
}
}
});
// Code Break
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button3) {
button3.setBackgroundResource(R.drawable.oval4);
}
}
});
// Code Break
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button4) {
button4.setBackgroundResource(R.drawable.oval5);
}
}
});
// Code Break
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button5) {
button5.setBackgroundResource(R.drawable.oval6);
}
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.shadowz.buttononclick.MainActivity"
android:id="#+id/backgroundLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="#+id/button1"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button1"
android:background="#drawable/oval"
android:padding="#dimen/abc_action_bar_content_inset_material"
android:layout_below="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/button2"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button2"
android:background="#drawable/oval"
android:layout_alignTop="#+id/button1"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/button3"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button3"
android:background="#drawable/oval"
android:singleLine="false"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/button4"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button4"
android:background="#drawable/oval"
android:padding="#dimen/abc_action_bar_content_inset_material"
android:layout_above="#+id/button2"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/button2" />
<Button
android:id="#+id/button5"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button5"
android:background="#drawable/oval"
android:padding="#dimen/abc_action_bar_content_inset_material"
android:layout_alignBottom="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="78dp" />
</RelativeLayout>
You can do this by following:
Create integer-array in resources:
<integer-array name="backgrounds">
<item>#drawable/oval1</item>
<item>#drawable/oval2</item>
<item>#drawable/oval3</item>
<item>#drawable/oval4</item>
<item>#drawable/oval5</item>
</integer-array>
Then create special OnClickListener class inside your class code
private static class MyClickListener implements View.OnClickListener {
private int mBackgroundIndex = 0;
private final TypedArray mBackgrounds;
public MyClickListener(Context context) {
mBackgrounds = context.getResources().obtainTypedArray(R.array.backgrounds);
}
#Override
public void onClick(View v) {
mBackgroundIndex++;
if (mBackgroundIndex >= mBackgrounds.length()) {
mBackgroundIndex = 0;
}
v.setBackgroundResource(mBackgrounds.getResourceId(mBackgroundIndex, 0));
}
#Override
protected void finalize() throws Throwable {
mBackgrounds.recycle();
super.finalize();
}
}
And then set that listener to each button:
button1.setOnClickListener(new MyClickListener(this));
button2.setOnClickListener(new MyClickListener(this));
button3.setOnClickListener(new MyClickListener(this));
button4.setOnClickListener(new MyClickListener(this));
button5.setOnClickListener(new MyClickListener(this));
This should result in the following MainActivity code:
package com.example.shadowz.buttononclick;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.view.TintableBackgroundView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button colorChangeButton;
private TextView basicText;
private RelativeLayout background;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Drawable oval1;
Drawable oval2;
Drawable oval3;
Drawable oval4;
Drawable oval5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
background = (RelativeLayout) findViewById(R.id.backgroundLayout);
basicText = (TextView) findViewById(R.id.button1);
colorChangeButton = (Button) findViewById(R.id.button1);
// Code Break
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button1.setOnClickListener(new MyClickListener(this));
button2.setOnClickListener(new MyClickListener(this));
button3.setOnClickListener(new MyClickListener(this));
button4.setOnClickListener(new MyClickListener(this));
button5.setOnClickListener(new MyClickListener(this));
}
private static class MyClickListener implements View.OnClickListener {
private int mBackgroundIndex = 0;
private final TypedArray mBackgrounds;
public MyClickListener(Context context) {
mBackgrounds = context.getResources().obtainTypedArray(R.array.backgrounds);
}
#Override
public void onClick(View v) {
mBackgroundIndex++;
if (mBackgroundIndex >= mBackgrounds.length()) {
mBackgroundIndex = 0;
}
v.setBackgroundResource(mBackgrounds.getResourceId(mBackgroundIndex, 0));
}
#Override
protected void finalize() throws Throwable {
mBackgrounds.recycle();
super.finalize();
}
}
}
How to create an android mobile application that will do a counting in miliseconds (start from 0), and ask user to type"I Like to eat" in EditText and click submit. After user click submit, counting will stop and a dialog box will appear and show the counting result.
package com.example.labex4;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView textView1,textView2,textView3,textView4,displayValue;
EditText nameTxt;
Button button1;
int count = 0;
Timer T;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
displayValue.setText("count="+count);
count++;
}
});
}
}, 0, 1);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
textView4 = (TextView)findViewById(R.id.textView4);
displayValue = (TextView)findViewById(R.id.displayValue);
nameTxt = (EditText)findViewById(R.id.nameTxt);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
T.cancel();
dialog.editext.setText(""+count);
}
}
***Here is The 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"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="(Type Faster)"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="25dp"
android:text="Miliseconds: " />
<TextView
android:id="#+id/displayValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:text="displayvalue" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="Type this words: " />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Frankie Jones Anak Saing"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView4"
android:layout_marginTop="38dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/nameTxt"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:text="Check" />
</RelativeLayout>
Global Variable
int count = 0;
Timer T;
Put the below code in onCreate after setContentView
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
//myTextView.setText("count="+count);
count++;
}
});
}
}, 0, 1);
At Button OnCLick
UPDATE
T.cancel();
//Open popup or dialog or alert as per your choice and print the count value
//dialog.editext.setText(""+count);
AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
alertDialog.setTitle("You total time count");
alertDialog.setMessage(String.valueof(count));
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
alertDialog.dismiss();
}
});
alertDialog.show(); //<-- See This!
}
As Per Your Requirement I am pasting the whole class
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity implements OnClickListener {
TextView textView1,textView2,textView3,textView4,displayValue;
EditText nameTxt;
Button button1;
int count = 0;
Timer T;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
displayValue.setText("count="+count);
count++;
}
});
}
}, 0, 1);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
textView4 = (TextView)findViewById(R.id.textView4);
displayValue = (TextView)findViewById(R.id.displayValue);
nameTxt = (EditText)findViewById(R.id.nameTxt);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
T.cancel();
//Open popup or dialog or alert as per your choice and print the count value
//dialog.editext.setText(""+count);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_popup);
dialog.setTitle("Typing Result!");
// set the custom dialog components - text, image and button
TextView titletext = (TextView) dialog.findViewById(R.id.titletext);
//titletext.setText("Typing Result!");
titletext.setVisibility(View.GONE);
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Frankie Jones Igat, Your Typing Speed "+String.valueOf(count)+" miliseconds");
Button dialogButtonOK = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButtonOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
And Custom pop up layout in layout folder custom_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#999999"
android:layout_marginTop="10dp">
<TextView
android:id="#+id/titletext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="title"
android:textSize="18sp"
android:textColor="#android:color/black"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titletext"
android:layout_marginTop="5dp"
android:textSize="16sp"
android:text="titlekiefsjisejefsjeaij"
android:textColor="#android:color/black"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/dialogButtonOK"
android:layout_width="80dp"
android:layout_height="40dp"
android:text=" Ok "
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/text"
android:textSize="18sp"
android:textColor="#android:color/black"
android:layout_centerHorizontal="true"
android:gravity="center"
android:background="#FF0000"
android:layout_marginBottom="10dp"
/>
</RelativeLayout>
User in my app may choose some dates in activity B and the last five choises should be saving.
The problem is that each user can have a different story calculations! In fact my app calculations of last user is remembering but even for new users who should have empty fields for dates.
Its my first activity:
package com.example.dnitygodnia;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Ekran1 extends Activity {
EditText editText;
Button dalej;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekran1);
preferences = getSharedPreferences("Dni Tygodnia", Activity.MODE_PRIVATE);
editText = (EditText) findViewById(R.id.editTextUserName);
String LastUser = preferences.getString("LastUser", "");
editText.setText(LastUser);
//set listeners
editText.addTextChangedListener(textWatcher);
//run once to disable if empty
checkFieldsForEmptyValues();
}
protected TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3)
{
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
checkFieldsForEmptyValues();
}
#Override
public void afterTextChanged(Editable editable) {
}
};
protected void checkFieldsForEmptyValues() {
dalej = (Button) findViewById(R.id.btnDalej);
String s = editText.getText().toString();
if (s.equals(""))
{
dalej.setEnabled(false);
}
else if (s.matches("[A-Za-z\\d]*")){
dalej.setEnabled(true);
}
else
dalej.setEnabled(false);
}
public void onClick (View v){
SharedPreferences.Editor preferencesEditor = preferences.edit();
String wyslij = editText.getText().toString();
Intent intent = new Intent (this, TestowyEkran.class);
intent.putExtra("Nazwa Uzytkownika", wyslij);
preferencesEditor.putString("LastUser", wyslij);
preferencesEditor.commit();
startActivity (intent);
}
}
This is the second activity:
package com.example.dnitygodnia;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class TestowyEkran extends Activity implements OnClickListener , TextWatcher {
String userName;
TextView txt;
TextView[] calData;
Button button;
Button backButton;
DatePicker picker;
Boolean backPressed = false;
SharedPreferences preferences;
Queue<String> strings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testowy_ekran);
preferences = getSharedPreferences("Dni Tygodnia", Activity.MODE_PRIVATE);
userName = getIntent().getExtras().getString("LOGIN");
txt = (TextView) findViewById(R.id.textViewLogin1);
backButton = (Button) findViewById(R.id.buttonBack);
button = (Button) findViewById(R.id.buttonDayOfTheWeek);
button.setOnClickListener(this);
picker = (DatePicker) findViewById(R.id.datePicker1);
// Bundle b = getIntent().getExtras();
// String odbior = b.getString("Nazwa Uzytkownika");
// txt.setText(odbior);
String LastUser = preferences.getString("LastUser", "");
txt.setText(LastUser);
backButton.setOnClickListener(this);
strings = new LinkedList<String>();
calData = new TextView[5];
calData[0] = (TextView) findViewById(R.id.textView1);
calData[1] = (TextView) findViewById(R.id.textView2);
calData[2] = (TextView) findViewById(R.id.textView3);
calData[3] = (TextView) findViewById(R.id.textView4);
calData[4] = (TextView) findViewById(R.id.textView5);
if ( strings != null )
updateFields();
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View arg0) {
if ( arg0.getId() == R.id.buttonBack )
{
backPressed = true;
finish();
}
else
{
SimpleDateFormat simpledateformat = new SimpleDateFormat("EEEE");
Date date = new Date(picker.getYear(),picker.getMonth(), picker.getDayOfMonth()-1);
String a = Integer.toString(picker.getYear());
String b = Integer.toString(picker.getMonth());
String c = Integer.toString(picker.getDayOfMonth());
String dayOfWeek = simpledateformat.format(date);
String fin = String.format("%s-%s-%s : %s" , a,b,c,dayOfWeek);
if ( strings.peek() != null && strings.peek().equals(fin) )
return;
strings.add(fin);
updateFields();
}
}
#Override
public void onBackPressed() {
}
private void updateFields()
{
if ( strings == null || strings.size() == 0 )
return;
if ( strings.size() == 6 )
{
strings.remove();
}
int i = 0;
for ( String s : strings)
{
calData[i].setText(s);
i++;
}
for ( TextView v : calData )
v.setTextColor(-16777216);
calData[i-1].setTextColor(-16711936);
}
#SuppressLint("NewApi")
#Override
protected void onPause() {
super.onPause();
SharedPreferences pref = getSharedPreferences("shared",0);
SharedPreferences.Editor ed = pref.edit();
ed.putStringSet(userName, new HashSet<String>(strings));
if ( !backPressed )
ed.putBoolean("secondscreen", true);
ed.putString("user", userName);
ed.commit();
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
SharedPreferences pref = getSharedPreferences("shared",0);
Set<String> hash = pref.getStringSet(userName, null);
if ( hash != null && hash.size() > 0 )
{
strings = new LinkedList<String>(hash);
updateFields();
}
super.onResume();
}
#SuppressLint("NewApi")
#Override
protected void onSaveInstanceState(Bundle outState) {
//outState.putStringArray(userName, (String[])strings.toArray());
super.onSaveInstanceState(outState);
}
#SuppressLint("NewApi")
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
String[] arr = savedInstanceState.getStringArray(userName);
if ( arr != null && arr.length > 0 )
{
strings = new LinkedList<String>(Arrays.asList(arr));
updateFields();
}
super.onRestoreInstanceState(savedInstanceState);
}
}
This is xml for activity 1:
<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=".Ekran1" >
<Button
android:id="#+id/btnDalej"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="102dp"
android:layout_marginRight="123dp"
android:text="#string/dalej"
android:onClick="onClick"/>
<TextView
android:id="#+id/textViewUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editTextUserName"
android:layout_alignParentTop="true"
android:text="#string/wpisz_nazw_u_ytkownika"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editTextUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textViewUserName"
android:layout_marginLeft="47dp"
android:layout_marginTop="52dp"
android:layout_toLeftOf="#+id/btnDalej"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
</RelativeLayout>
and this is a xml of activity 2:
<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=".TestowyEkran" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="174dp"
android:text="TextView1" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/textView1"
android:layout_marginTop="17dp"
android:text="TextView2" />
<Button
android:id="#+id/buttonDayOfTheWeek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="46dp"
android:text="Day of the week" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:text="TextView3" />
<Button
android:id="#+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="34dp"
android:layout_marginRight="18dp"
android:text="back" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:text="TextView4" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_below="#+id/textView4"
android:text="TextView5" />
<DatePicker
android:id="#+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/buttonDayOfTheWeek"
android:layout_marginTop="51dp"
android:calendarViewShown="false" />
<TextView
android:id="#+id/textViewLogin1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp"
android:text="TextView" />
</RelativeLayout>
replace
getSharedPreferences("Dni Tygodnia", Activity.MODE_PRIVATE);
with
getSharedPreferences("Dni Tygodnia", MODE_PRIVATE);
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();
}
}