I made two applications that use the bluetooth in the same way. When I click on the "Connect" button I get the message "complete action using..." with the choice of my two applications. How do I delete it and launch only the activity of the application that I am using?
Thanks.
public class MainActivity extends Activity implements View.OnClickListener{
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (Bluetooth.connectedThread != null) {
Bluetooth.connectedThread.write(" ");}//Stop streaming
super.onBackPressed();
}
//toggle Button
static boolean Lock;//whether lock the x-axis to 0-5
static boolean AutoScrollX;//auto scroll to the last x value
static boolean Stream;//Start or stop streaming
boolean dark = true;
//Button init
Button bXminus;
Button bXplus;
Button bYminus;
Button bYplus;
ToggleButton tbScroll;
ToggleButton tbStream;
RadioButton ch1,ch2,ch3,ch4;
//GraphView init
static LinearLayout GraphView, GraphView1;
//graph value
private static double graph2LastXValue = 0;
private static int Xview=10;
Button bConnect, bDisconnect;
Button cambia;
Button bBackground;
int switches = 0;
int range = 1;
int counter = 0;
byte prova = (byte) 187; //188 e 168
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
case Bluetooth.SUCCESS_CONNECT:
Bluetooth.connectedThread = new Bluetooth.ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "Connected!", 0).show();
String s = "successfully connected";
Bluetooth.connectedThread.start();
Bluetooth.connectedThread.write(new byte[]{(byte) prova});
break;
case Bluetooth.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
int valore_a_16 = ((readBuf[1] & 0xFF) << 8) | (readBuf[0] & 0xFF);
int valore_a_16_2 = ((readBuf[3] & 0xFF) << 8) | (readBuf[2] & 0xFF);
int valore_a_16_3 = ((readBuf[5] & 0xFF) << 8) | (readBuf[4] & 0xFF);
int valore_a_16_4 = ((readBuf[7] & 0xFF) << 8) | (readBuf[6] & 0xFF);
String strIncom = new String(readBuf); // create string from bytes array
String str = String.valueOf(valore_a_16);
String str2 = String.valueOf(valore_a_16_2);
String str3 = String.valueOf(valore_a_16_3);
String str4 = String.valueOf(valore_a_16_4);
Log.d("SHORT", str);
Log.d("strIncom", strIncom);
Log.d("SHORT CH 2", str2);
Log.d("SHORT CH 3", str3);
Log.d("SHORT CH 4", str4);
char c = strIncom.charAt(0);
long foo = Integer.parseInt(str);
long foo2 = Integer.parseInt(str2);
long foo3 = Integer.parseInt(str3);
long foo4 = Integer.parseInt(str4);
//String provola = Integer.toString(foo);
//Log.d("AAAAAAAAAAAAAA", provola);
// int decVal = (int) c;
long risultato = (long) (foo * 5000000)/(65535*150);
long risultato2 = (long) (foo2 * 5000000)/(65535*150);
long risultato3 = (long) (foo3 * 5000000)/(65535*150);
long risultato4 = (long) (foo4 * 5000000)/(65535*150);
String prova = Float.toString(risultato);
String prova2 = Float.toString(risultato2);
String prova3 = Float.toString(risultato3);
String prova4 = Float.toString(risultato4);
Log.d("prova", prova);
// Log.d("testing2", String.valueOf(decVal));
break;
}
}
public boolean isFloatNumber(String num){
//Log.d("checkfloatNum", num);
try{
Double.parseDouble(num);
} catch(NumberFormatException nfe) {
return false;
}
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);//Hide title
this.getWindow().setFlags(WindowManager.LayoutParams.
FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//Hide Status bar
setContentView(R.layout.activity_main);
//set background color
LinearLayout background = (LinearLayout)findViewById(R.id.bg);
background.setBackgroundColor(Color.BLACK);
init();
ButtonInit();
}
void init(){
Bluetooth.gethandler(mHandler);
}
void ButtonInit(){
bConnect = (Button)findViewById(R.id.bConnect);
bConnect.setOnClickListener(this);
bDisconnect = (Button)findViewById(R.id.bDisconnect);
bDisconnect.setOnClickListener(this);
//X-axis control button
bXminus = (Button)findViewById(R.id.bXminus);
bXminus.setOnClickListener(this);
bXplus = (Button)findViewById(R.id.bXplus);
bXplus.setOnClickListener(this);
bYminus = (Button)findViewById(R.id.bYminus);
bYminus.setOnClickListener(this);
bYplus = (Button)findViewById(R.id.bYplus);
bYplus.setOnClickListener(this);
//
tbScroll = (ToggleButton)findViewById(R.id.tbScroll);
tbScroll.setOnClickListener(this);
tbStream = (ToggleButton)findViewById(R.id.tbStream);
tbStream.setOnClickListener(this);
tbStream.setEnabled(false);
bBackground = (Button)findViewById(R.id.button1);
bBackground.setOnClickListener(this);
//init toggleButton
ch1 = (RadioButton)findViewById(R.id.radioButton1);
ch1.setOnClickListener(this);
ch1.setChecked(true);
ch2 = (RadioButton)findViewById(R.id.radioButton2);
ch2.setOnClickListener(this);
ch3 = (RadioButton)findViewById(R.id.radioButton3);
ch3.setOnClickListener(this);
ch4 = (RadioButton)findViewById(R.id.radioButton4);
ch4.setOnClickListener(this);
Lock=false;
AutoScrollX=true;
Stream=true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bConnect:
startActivity(new Intent("android.intent.action.BT1"));
break;
case R.id.bDisconnect:
Intent myIntent = new Intent(MainActivity.this, RacerGameActivity.class);
MainActivity.this.startActivity(myIntent);
break;
case R.id.bXminus:
if (Xview>1) Xview=Xview/10;
break;
case R.id.bXplus:
if (Xview<100) Xview=Xview*10;
break;
case R.id.bYminus:
if (range==1)
{
range=0;
}
else if (range==0)
{
range=0;
}
else if(range==2)
{
range=1;
}
else if(range==3)
{
range=2;
}
else if(range==4)
{
range=3;
}
break;
case R.id.bYplus:
if (range==1)
{
range=2;
}
else if (range==0)
{
range=1;
}
else if(range==2)
{
range=3;
}
else if(range==3)
{
range=4;
}
else if(range==4)
{
range=4;
}
break;
case R.id.tbScroll:
if (tbScroll.isChecked()){
AutoScrollX = true;
}else{
AutoScrollX = false;
}
break;
case R.id.radioButton1:
ch1.setChecked(true);
ch2.setChecked(false);
ch3.setChecked(false);
ch4.setChecked(false);
switches=0;
break;
case R.id.radioButton2:
ch1.setChecked(false);
ch2.setChecked(true);
ch3.setChecked(false);
ch4.setChecked(false);
switches=1;
break;
case R.id.radioButton3:
ch1.setChecked(false);
ch2.setChecked(false);
ch3.setChecked(true);
ch4.setChecked(false);
switches=2;
break;
case R.id.radioButton4:
ch1.setChecked(false);
ch2.setChecked(false);
ch3.setChecked(false);
ch4.setChecked(true);
switches=3;
break;
/* case R.id.tbStream:
if (tbStream.isChecked()){
if (Bluetooth.connectedThread != null)
Bluetooth.connectedThread.write("E");
}else{
if (Bluetooth.connectedThread != null)
Bluetooth.connectedThread.write("Q");
}
break;
// case R.id.button1:
// GraphView.setBackgroundColor(Color.WHITE);
// break;
case R.id.button1:
switches=1;
break;*/
}
}
}
Related
I have a quiz app which has a timer for the whole game-activity where in you should answer as 20 questions and every qustion have 10 sec ..
after the assigned 20 is over, it will take you to the results activity which shows your score. even after calling score activity toast from main activty will show and score activity will open agian and again.
int score = 0;
int unanswer = 0;
int questionasked = 1;
int maxquestion = 20;
TextView first, operator, second, timeview;
Button A, B, C, D;
int ans = 0;
String t;
DecimalFormat df;
CountDownTimer mCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeview = findViewById(R.id.time);
A = findViewById(R.id.A);
A.setOnClickListener(this);
B = findViewById(R.id.B);
B.setOnClickListener(this);
C = findViewById(R.id.C);
C.setOnClickListener(this);
D = findViewById(R.id.D);
D.setOnClickListener(this);
first = findViewById(R.id.first);
second = findViewById(R.id.second);
operator = findViewById(R.id.operator);
df = new DecimalFormat("###.##");
starTimer();
fillValue();
}
main activity code
private void fillValue() {
if (questionasked > maxquestion)
showscore();
questionasked++;
int a = (int) (Math.random() * 50 + 1);
int b = (int) (Math.random() * 50 + 1);
int op = (int) (Math.random() * 4 + 1);
int buttonoption = (int) (Math.random() * 4 + 1);
char operatorcharter = '+';
switch (op) {
case 1:
ans = a + b;
operatorcharter = '+';
break;
case 2:
ans = a - b;
operatorcharter = '-';
break;
case 3:
ans = a * b;
operatorcharter = 'X';
break;
case 4:
ans = (a) / b;
operatorcharter = '/';
break;
//default:
//Toast.makeText(this,op+"",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(this,a+" "+operatorcharter+" "+b+" "+ans+" "+buttonoption,Toast.LENGTH_LONG).show();
operator.setText(operatorcharter + "");
first.setText(a + "");
second.setText(b + "");
t = df.format(ans);
int temp = 0;
switch (buttonoption) {
case 1:
A.setText(t);
break;
case 2:
B.setText(t);
break;
case 3:
C.setText(t);
break;
case 4:
D.setText(t);
break;
//default:
// Toast.makeText(this,buttonoption+" butt",Toast.LENGTH_SHORT).show();
}
for (int i = 1; i <= 4; i++) {
if (i == buttonoption)
continue;
temp = (int) (Math.random() * ans + 1);
if (temp == ans) ;
temp += 5;
String temp1 = df.format(temp);
if (i == 1)
A.setText(temp1 + "");
else if (i == 2)
B.setText(temp1 + "");
else if (i == 3)
C.setText(temp1 + "");
else if (i == 4)
D.setText(temp1 + "");
}
mCountDownTimer.start();
}
private void showscore() {
Intent i = new Intent(this, final_activity.class);
i.putExtra(Contact.maxquestion, maxquestion);
i.putExtra(Contact.score, score);
i.putExtra(Contact.unanswer, unanswer);
mCountDownTimer.cancel();
Toast.makeText(this, "new activity open", Toast.LENGTH_LONG).show();
startActivity(i);
this.finish();
}
#Override
public void onClick(View v) {
Button b = (Button) v;
String clickbuttonvalue = (String) b.getText();
if (clickbuttonvalue.equals(t))
score++;
//Toast.makeText(this,score+" "+clickbuttonvalue ,Toast.LENGTH_LONG).show();
mCountDownTimer.cancel();
fillValue();
}
public void starTimer() {
mCountDownTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
timeview.setText("seconds remaining: " + millisUntilFinished / 1000);
Toast.makeText(MainActivity.this, "new" + millisUntilFinished / 1000, Toast.LENGTH_LONG).show();
}
public void onFinish() {
unanswer++;
fillValue();
}
}.start();
}
}
this is my code even after opening new activity and open new activity check method showscore()
plz, help!
You need to override the onDestroy method which will be triggered when the activity is finished(don't forget to add finish() after the startActivty()).
#Override
public void onDestroy() {
super.onDestroy();
mCountDownTimer.cancel();
}
This is the code for a calculator app for Android I'm making:
package com.example.calculator;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.view.View;
import android.view.View.OnClickListener;
public class main extends Activity {
GridView mKeypadGrid;
TextView userInputText;
TextView memoryStatText;
Stack<String> mInputStack;
Stack<String> mOperationStack;
KeypadAdapter mKeypadAdapter;
TextView mStackText;
boolean resetInput = false;
boolean hasFinalResult = false;
String mDecimalSeperator;
double memoryValue = Double.NaN;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat
.getInstance();
char decimalSeperator = currencyFormatter.getDecimalFormatSymbols()
.getDecimalSeparator();
mDecimalSeperator = Character.toString(decimalSeperator);
setContentView(R.layout.main);
// Create the stack
mInputStack = new Stack<String>();
mOperationStack = new Stack<String>();
// Get reference to the keypad button GridView
mKeypadGrid = (GridView) findViewById(R.id.grdButtons);
// Get reference to the user input TextView
userInputText = (TextView) findViewById(R.id.txtInput);
userInputText.setText("0");
memoryStatText = (TextView) findViewById(R.id.txtMemory);
memoryStatText.setText("");
mStackText = (TextView) findViewById(R.id.txtStack);
// Create Keypad Adapter
mKeypadAdapter = new KeypadAdapter(this);
// Set adapter of the keypad grid
mKeypadGrid.setAdapter(mKeypadAdapter);
// Set button click listener of the keypad adapter
mKeypadAdapter.setOnButtonClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button) v;
// Get the KeypadButton value which is used to identify the
// keypad button from the Button's tag
KeypadButton keypadButton = (KeypadButton) btn.getTag();
// Process keypad button
ProcessKeypadInput(keypadButton);
}
});
mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
private void ProcessKeypadInput(KeypadButton keypadButton) {
//Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show();
String text = keypadButton.getText().toString();
String currentInput = userInputText.getText().toString();
int currentInputLen = currentInput.length();
String evalResult = null;
double userInputValue = Double.NaN;
switch (keypadButton) {
case BACKSPACE: // Handle backspace
// If has operand skip backspace
if (resetInput)
return;
int endIndex = currentInputLen - 1;
// There is one character at input so reset input to 0
if (endIndex < 1) {
userInputText.setText("0");
}
// Trim last character of the input text
else {
userInputText.setText(currentInput.subSequence(0, endIndex));
}
break;
case SIGN: // Handle -/+ sign
// input has text and is different than initial value 0
if (currentInputLen > 0 && currentInput != "0") {
// Already has (-) sign. Remove that sign
if (currentInput.charAt(0) == '-') {
userInputText.setText(currentInput.subSequence(1,
currentInputLen));
}
// Prepend (-) sign
else {
userInputText.setText("-" + currentInput.toString());
}
}
break;
case CE: // Handle clear input
userInputText.setText("0");
break;
case INVERT:
if (currentInput != "0") {
userInputText.setText("1/" + currentInput);
}
break;
case C: // Handle clear input and stack
userInputText.setText("0");
clearStacks();
break;
case DECIMAL_SEP: // Handle decimal separator
if (hasFinalResult || resetInput) {
userInputText.setText("0" + mDecimalSeperator);
hasFinalResult = false;
resetInput = false;
} else if (currentInput.contains("."))
return;
else
userInputText.append(mDecimalSeperator);
break;
case DIV:
case PLUS:
case MINUS:
case MULTIPLY:
if (resetInput) {
mInputStack.pop();
mOperationStack.pop();
} else {
if (currentInput.charAt(0) == '-') {
mInputStack.add("(" + currentInput + ")");
} else {
mInputStack.add(currentInput);
}
mOperationStack.add(currentInput);
}
mInputStack.add(text);
mOperationStack.add(text);
dumpInputStack();
evalResult = evaluateResult(false);
if (evalResult != null)
userInputText.setText(evalResult);
resetInput = true;
break;
case CALCULATE:
if (mOperationStack.size() == 0)
break;
mOperationStack.add(currentInput);
evalResult = evaluateResult(true);
if (evalResult != null) {
clearStacks();
userInputText.setText(evalResult);
resetInput = false;
hasFinalResult = true;
}
break;
case M_ADD: // Add user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue += userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case M_REMOVE: // Subtract user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue -= userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case MC: // Reset memory buffer to 0
memoryValue = Double.NaN;
displayMemoryStat();
break;
case MR: // Read memoryBuffer value
if (Double.isNaN(memoryValue))
return;
userInputText.setText(doubleToString(memoryValue));
displayMemoryStat();
break;
case MS: // Set memoryBuffer value to user input
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
memoryValue = userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
default:
if (Character.isDigit(text.charAt(0))) {
if (currentInput.equals("0") || resetInput || hasFinalResult) {
userInputText.setText(text);
resetInput = false;
hasFinalResult = false;
} else {
userInputText.append(text);
resetInput = false;
}
}
break;
}
}
private void clearStacks() {
mInputStack.clear();
mOperationStack.clear();
mStackText.setText("");
}
private void dumpInputStack() {
Iterator<String> it = mInputStack.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
CharSequence iValue = it.next();
sb.append(iValue);
}
mStackText.setText(sb.toString());
}
private String evaluateResult(boolean requestedByUser) {
if ((!requestedByUser && mOperationStack.size() != 4)
|| (requestedByUser && mOperationStack.size() != 3))
return null;
String left = mOperationStack.get(0);
String operator = mOperationStack.get(1);
String right = mOperationStack.get(2);
String tmp = null;
if (!requestedByUser)
tmp = mOperationStack.get(3);
double leftVal = Double.parseDouble(left.toString());
double rightVal = Double.parseDouble(right.toString());
double result = Double.NaN;
if (operator.equals(KeypadButton.DIV.getText())) {
result = leftVal / rightVal;
} else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
result = leftVal * rightVal;
} else if (operator.equals(KeypadButton.PLUS.getText())) {
result = leftVal + rightVal;
} else if (operator.equals(KeypadButton.MINUS.getText())) {
result = leftVal - rightVal;
}
String resultStr = doubleToString(result);
if (resultStr == null)
return null;
mOperationStack.clear();
if (!requestedByUser) {
mOperationStack.add(resultStr);
mOperationStack.add(tmp);
}
return resultStr;
}
private String doubleToString(double value) {
if (Double.isNaN(value))
return null;
long longVal = (long) value;
if (longVal == value)
return Long.toString(longVal);
else
return Double.toString(value);
}
private double tryParseUserInput() {
String inputStr = userInputText.getText().toString();
double result = Double.NaN;
try {
result = Double.parseDouble(inputStr);
} catch (NumberFormatException nfe) {
}
return result;
}
private void displayMemoryStat() {
if (Double.isNaN(memoryValue)) {
memoryStatText.setText("");
} else {
memoryStatText.setText("M = " + doubleToString(memoryValue));
}
}
}
To find the reciprocal of an inputted number, I use the following code:
case INVERT:
if (currentInput != "0") {
userInputText.setText("1/" + currentInput);
}
break;
But instead of displaying the output of the reciprocal, like I wanted, it simply displays "1/inputted number". Why is this, and can someone help me fix it? Thanks in advance.
You are returning it as text and so that is how it is displayed. You need to do the math then convert it to a string:
float input = Float.valueOf(currentInput);
if( input == 0) // Check if 0 to avoid divide by 0 error
userInputText.setText("NaN");
else
userInputText.setText(Float.toString(1/input));
double inputVal = Double.valueOf(currentInput);
userInputText.setText(inputVal != 0 ? String.valueOf(1/inputVal) : "NaN");
I am making an app to search a database and i have a part where i type in a search detail and the name of the possible results are displayed on buttons in a new activity. It works fine first time round but if i press back from that activity then try to search for something different then the last button results but the old results are still there with the new ones.
public class search_page extends Activity implements OnClickListener {
static int number;
static int[] numberArray = new int[8];
static int looped;
static int typeFound = 0;
TextView editText1;
Button search_button, search_button2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_page);
editText1 = (EditText) findViewById(R.id.editText1);
search_button = (Button) findViewById(R.id.search_button);
search_button2 = (Button) findViewById(R.id.search_button2);
search_button.setOnClickListener(this);
search_button2.setOnClickListener(this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.search_button:
sqlStuff search1 = new sqlStuff(search_page.this);
boolean found = false;
String Systname = editText1.getText().toString();
search1.open();
String[] IDSysNames = search1.getIDSysName();
search1.close();
for(int i = 0; i < IDSysNames.length; i++) {
if(Systname.equalsIgnoreCase(IDSysNames[i].toString())) {
found = true;
number = i;
}
}
if(found==true) {
Intent search = new Intent("com.MC.ChemPal.RESULT");
startActivity(search);
}
else {
Dialog d = new Dialog(this);
d.setTitle("result not found");
TextView tv = new TextView(this);
d.setContentView(tv);
d.show();
}
break;
case R.id.search_button2:
boolean found2 = false;
boolean found3 = false;
sqlStuff search2 = new sqlStuff(search_page.this);
search2.open();
String entry = editText1.getText().toString();
String[] IDSysNames2 = search2.getIDSysName();
String[] IDGroup = search2.getIDGroup();
String[] IDMP = search2.getIDMP();
String[] IDBP = search2.getIDBP();
String[] IDComname = search2.getIDComname();
String[] IDElement = search2.getIDElement();
String[] IDMolarmass = search2.getIDMOLARMASS();
search2.close();
for(int i = 0; i < IDSysNames2.length; i++) {
if(entry.equalsIgnoreCase(IDSysNames2[i].toString())) {
found2 = true;
found3 = true;
typeFound = 1;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDGroup[i].toString())) {
found2 = true;
found3 = true;
typeFound = 2;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDMP[i].toString())) {
found2 = true;
found3 = true;
typeFound = 3;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDBP[i].toString())) {
found2 = true;
found3 = true;
typeFound = 4;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDComname[i].toString())) {
found2 = true;
found3 = true;
typeFound = 5;
numberArray[looped] = i;
}
if(IDElement[i].toString().contains(entry)) {
found2 = true;
found3 = true;
typeFound = 6;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDMolarmass[i].toString())) {
found2 = true;
found3 = true;
typeFound = 7;
numberArray[looped] = i;
}
if(found2 == true) {
looped++;
}
found2 = false;
}
if (found3==true) {
Intent searching2 = new Intent("com.MC.ChemPal.SEARCHLIST");
startActivity(searching2);
}
else {
Dialog d = new Dialog(this);
d.setTitle("result not found");
TextView tv = new TextView(this);
d.setContentView(tv);
d.show();
}
break;
}
}
public static int returnNum() {
return number;
}
public static int[] returnNumArray() {
return numberArray;
}
public static int returnlooped() {
return looped;
}
}
That activity then links to this one.
public class searchlist extends Activity implements OnClickListener {
static int buttonPress = 0;
int loops = 0;
public void onCreate(Bundle savedinstance){
super.onCreate(savedinstance);
setContentView(R.layout.searchlist);
Button[] mybuttons = new Button[10];
mybuttons[0] = (Button) findViewById(R.id.search1);
mybuttons[1] = (Button) findViewById(R.id.search2);
mybuttons[2] = (Button) findViewById(R.id.search3);
mybuttons[3] = (Button) findViewById(R.id.search4);
mybuttons[4] = (Button) findViewById(R.id.search5);
mybuttons[5] = (Button) findViewById(R.id.search6);
mybuttons[6] = (Button) findViewById(R.id.search7);
mybuttons[7] = (Button) findViewById(R.id.search8);
mybuttons[8] = (Button) findViewById(R.id.search9);
mybuttons[9] = (Button) findViewById(R.id.search10);
int i = 0;
if(!mybuttons[0].getText().equals("-"))
{
mybuttons[0].setText("-");
mybuttons[0].setVisibility(View.INVISIBLE);
}
if(!mybuttons[1].getText().equals("-"))
{
mybuttons[1].setText("-");
mybuttons[1].setVisibility(View.INVISIBLE);
}
if(!mybuttons[2].getText().equals("-"))
{
mybuttons[2].setText("-");
mybuttons[2].setVisibility(View.INVISIBLE);
}
if(!mybuttons[3].getText().equals("-"))
{
mybuttons[3].setText("-");
mybuttons[3].setVisibility(View.INVISIBLE);
}
if(!mybuttons[4].getText().equals("-"))
{
mybuttons[4].setText("-");
mybuttons[4].setVisibility(View.INVISIBLE);
}
if(!mybuttons[5].getText().equals("-"))
{
mybuttons[5].setText("-");
mybuttons[5].setVisibility(View.INVISIBLE);
}
if(!mybuttons[6].getText().equals("-"))
{
mybuttons[6].setText("-");
mybuttons[6].setVisibility(View.INVISIBLE);
}
if(!mybuttons[7].getText().equals("-"))
{
mybuttons[7].setText("-");
mybuttons[7].setVisibility(View.INVISIBLE);
}
if(!mybuttons[8].getText().equals("-"))
{
mybuttons[8].setText("-");
mybuttons[8].setVisibility(View.INVISIBLE);
}
if(!mybuttons[9].getText().equals("-"))
{
mybuttons[9].setText("-");
mybuttons[9].setVisibility(View.INVISIBLE);
}
sqlStuff searching = new sqlStuff(searchlist.this);
searching.open();
String[] IDSysNames = searching.getIDSysName();
loops = search_page.returnlooped();
int[] teacup = search_page.returnNumArray();
searching.close();
for(i=0; i < loops; i++ )
{
if(IDSysNames[teacup[i]] != null)
{
mybuttons[i].setText(IDSysNames[teacup[i]]);
}
}
if(!mybuttons[0].getText().equals("-"))
{
mybuttons[0].setOnClickListener(this);
mybuttons[0].setVisibility(View.VISIBLE);
}
if(!mybuttons[1].getText().equals("-"))
{
mybuttons[1].setOnClickListener(this);
mybuttons[1].setVisibility(View.VISIBLE);
}
if(!mybuttons[2].getText().equals("-"))
{
mybuttons[2].setOnClickListener(this);
mybuttons[2].setVisibility(View.VISIBLE);
}
if(!mybuttons[3].getText().equals("-"))
{
mybuttons[3].setOnClickListener(this);
mybuttons[0].setVisibility(View.VISIBLE);
}
if(!mybuttons[4].getText().equals("-"))
{
mybuttons[4].setOnClickListener(this);
mybuttons[4].setVisibility(View.VISIBLE);
}
if(!mybuttons[5].getText().equals("-"))
{
mybuttons[5].setOnClickListener(this);
mybuttons[5].setVisibility(View.VISIBLE);
}
if(!mybuttons[6].getText().equals("-"))
{
mybuttons[6].setOnClickListener(this);
mybuttons[6].setVisibility(View.VISIBLE);
}
if(!mybuttons[7].getText().equals("-"))
{
mybuttons[7].setOnClickListener(this);
mybuttons[7].setVisibility(View.VISIBLE);
}
if(!mybuttons[8].getText().equals("-"))
{
mybuttons[8].setOnClickListener(this);
mybuttons[8].setVisibility(View.VISIBLE);
}
if(!mybuttons[9].getText().equals("-"))
{
mybuttons[9].setOnClickListener(this);
mybuttons[9].setVisibility(View.VISIBLE);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case
R.id.search1:
buttonPress = 0;
Intent search = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search);
break;
case
R.id.search2:
buttonPress = 1;
Intent search2 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search2);
break;
case
R.id.search3:
buttonPress = 2;
Intent search3 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search3);
break;
case
R.id.search4:
buttonPress=3;
Intent search4 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search4);
break;
case
R.id.search5:
buttonPress=4;
Intent search5 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search5);
break;
case
R.id.search6:
buttonPress=5;
Intent search6 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search6);
break;
case
R.id.search7:
buttonPress=6;
Intent search7 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search7);
break;
case
R.id.search8:
buttonPress=7;
Intent search8 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search8);
break;
case
R.id.search9:
buttonPress=8;
Intent search9 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search9);
break;
case
R.id.search10:
buttonPress=9;
Intent search10 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search10);
break;
}
}
public static int getButtonPress() {
return buttonPress;
}
public void onResume(){
super.onResume();
setContentView(R.layout.searchlist);
Button[] mybuttons = new Button[10];
onResume();
mybuttons[0] = (Button) findViewById(R.id.search1);
mybuttons[1] = (Button) findViewById(R.id.search2);
mybuttons[2] = (Button) findViewById(R.id.search3);
mybuttons[3] = (Button) findViewById(R.id.search4);
mybuttons[4] = (Button) findViewById(R.id.search5);
mybuttons[5] = (Button) findViewById(R.id.search6);
mybuttons[6] = (Button) findViewById(R.id.search7);
mybuttons[7] = (Button) findViewById(R.id.search8);
mybuttons[8] = (Button) findViewById(R.id.search9);
mybuttons[9] = (Button) findViewById(R.id.search10);
int i = 0;
if(!mybuttons[0].getText().equals("-"))
{
mybuttons[0].setText("-");
mybuttons[0].setVisibility(View.INVISIBLE);
}
if(!mybuttons[1].getText().equals("-"))
{
mybuttons[1].setText("-");
mybuttons[1].setVisibility(View.INVISIBLE);
}
if(!mybuttons[2].getText().equals("-"))
{
mybuttons[2].setText("-");
mybuttons[2].setVisibility(View.INVISIBLE);
}
if(!mybuttons[3].getText().equals("-"))
{
mybuttons[3].setText("-");
mybuttons[3].setVisibility(View.INVISIBLE);
}
if(!mybuttons[4].getText().equals("-"))
{
mybuttons[4].setText("-");
mybuttons[4].setVisibility(View.INVISIBLE);
}
if(!mybuttons[5].getText().equals("-"))
{
mybuttons[5].setText("-");
mybuttons[5].setVisibility(View.INVISIBLE);
}
if(!mybuttons[6].getText().equals("-"))
{
mybuttons[6].setText("-");
mybuttons[6].setVisibility(View.INVISIBLE);
}
if(!mybuttons[7].getText().equals("-"))
{
mybuttons[7].setText("-");
mybuttons[7].setVisibility(View.INVISIBLE);
}
if(!mybuttons[8].getText().equals("-"))
{
mybuttons[8].setText("-");
mybuttons[8].setVisibility(View.INVISIBLE);
}
if(!mybuttons[9].getText().equals("-"))
{
mybuttons[9].setText("-");
mybuttons[9].setVisibility(View.INVISIBLE);
}
sqlStuff searching = new sqlStuff(searchlist.this);
searching.open();
String[] IDSysNames = searching.getIDSysName();
loops = search_page.returnlooped();
int[] teacup = search_page.returnNumArray();
searching.close();
for(i=0; i < loops; i++ )
{
if(IDSysNames[teacup[i]] != null)
{
mybuttons[i].setText(IDSysNames[teacup[i]]);
}
}
if(!mybuttons[0].getText().equals("-"))
{
mybuttons[0].setOnClickListener(this);
mybuttons[0].setVisibility(View.VISIBLE);
}
if(!mybuttons[1].getText().equals("-"))
{
mybuttons[1].setOnClickListener(this);
mybuttons[1].setVisibility(View.VISIBLE);
}
if(!mybuttons[2].getText().equals("-"))
{
mybuttons[2].setOnClickListener(this);
mybuttons[2].setVisibility(View.VISIBLE);
}
if(!mybuttons[3].getText().equals("-"))
{
mybuttons[3].setOnClickListener(this);
mybuttons[0].setVisibility(View.VISIBLE);
}
if(!mybuttons[4].getText().equals("-"))
{
mybuttons[4].setOnClickListener(this);
mybuttons[4].setVisibility(View.VISIBLE);
}
if(!mybuttons[5].getText().equals("-"))
{
mybuttons[5].setOnClickListener(this);
mybuttons[5].setVisibility(View.VISIBLE);
}
if(!mybuttons[6].getText().equals("-"))
{
mybuttons[6].setOnClickListener(this);
mybuttons[6].setVisibility(View.VISIBLE);
}
if(!mybuttons[7].getText().equals("-"))
{
mybuttons[7].setOnClickListener(this);
mybuttons[7].setVisibility(View.VISIBLE);
}
if(!mybuttons[8].getText().equals("-"))
{
mybuttons[8].setOnClickListener(this);
mybuttons[8].setVisibility(View.VISIBLE);
}
if(!mybuttons[9].getText().equals("-"))
{
mybuttons[9].setOnClickListener(this);
mybuttons[9].setVisibility(View.VISIBLE);
}
}
}
You changed the state of the buttons within the view. Moving to another activity and back won't reset the view. It maintains the states within your app, which would make not knowing the state far more of a problem.
Where you're setting the states programatically, I would suggest an override on onResume to set the states of your buttons to where you want them. This will be called when your activity is initially started, if it is restarted, and each time your activity is brought to the foreground.
Refer to: Android life cycle activities
Additional information:
You posted 2 activities (search_page and searchlist) where search_page clearly calls searchlist. You mentioned that your problem is hitting the back button. The problem isn't actually hitting the back -- that's obviously working, it is what the activity does when it resumes.
From your last comment it looks to me like you're making the buttons visible if they have text in them, so the problem isn't making them visible -- that's working, the problem is that the wrong buttons have text.
When should you clear them? When you return to search_page? If so, make your onResume in your search_page clear the text in all buttons.
i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}
I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}
You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()