I am new to Android development and currently learning to design for a basic calculator app. I have already self designed the layout, but sourced Main Activity codes from different websites for the operations for 0 to 9, +, -, *, / and after incorporation, they work fine.
However, I do want to further modify the MainActivity with decimal point function.
While integer can be shown properly to the screen using "current = current * 10 + number", eg 53 = 5*10+3;
I am thinking applying the same approach for decimal point with a loop function, the idea like this:
1. current = current + remaining if dot button is pressed
2. create an integer i, i increases by 1 once any numerial button is clicked
3. so that when e.g. input 5.3, i =1, it will = 5 + 3/(10^i) = 5.3
4. 5.3 loop to here, then when e.g. input as 5.39, now i=2, it will = 5.3 + 9/(10^i) = 5.39
QUESTION >>
*Yet...really...I am so fresh that I do not know how to design the coding for the decimal button, would there be anyone can suggest the code?* first ignore the following addons where errors to be detected (such as delete the second dot if the dot is input twice or more, adding 0 in front of . if say, .5 is input)
The button id is as follows, and once clicked to refer to DecimalClickEvent
Button b_decimal = (Button) findViewById(R.id.decimal);
b_decimal.setOnClickListener(new DecimalClickEvent(???));}
Many many thanks in advance!! The codes are attached below for reference and your comments:
=========================MainActivity.java=====================================
package com.trial.newcalculator;
import java.io.Serializable;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
#SuppressLint("ParserError")
public class MainActivity extends Activity {
State s;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s = new State();
int[] opNumbers = new int[] {
R.id.zero,
R.id.one,
R.id.two,
R.id.three,
R.id.four,
R.id.five,
R.id.six,
R.id.seven,
R.id.eight,
R.id.nine,
};
final TextView textView = (TextView) findViewById(R.id.ansEditText);
for (int i = 0; i < 10;i++){
final Button button = (Button) findViewById(opNumbers[i]);
button.setOnClickListener(new NumberClickEvent(textView,s,i));
}
int[] opButtons = new int[] { R.id.add, R.id.subtract, R.id.multiply, R.id.divide };
State.Operation[] states = new State.Operation[] {
State.Operation.PLUS,
State.Operation.MINUS,
State.Operation.MULTIPLY,
State.Operation.DIVIDE};
for(int i = 0; i < opButtons.length;i++){
Button b_op = (Button) findViewById(opButtons[i]);
b_op.setOnClickListener(new OperationClickEvent(textView, s, states[i]));
}
// Memory functions
int[] memButtons = new int[] { R.id.MC, R.id.MR, R.id.Mdeduct, R.id.Mplus};
State.Operation[] mstates = new State.Operation[] {
State.Operation.MEMORYCLEAR,
State.Operation.MEMORYCALL,
State.Operation.MEMORYMINUS,
State.Operation.MEMORYPLUS};
for(int i = 0; i < memButtons.length;i++){
Button b_mem = (Button) findViewById(memButtons[i]);
b_mem.setOnClickListener(new OperationClickEvent(textView, s, states[i]));
}
// Memory functions
//decimal
// Button b_decimal = (Button) findViewById(R.id.decimal);
// b_decimal.setOnClickListener(new DecimalClickEvent(textView, s, "."));
//decimal
Button b_eq = (Button) findViewById(R.id.equal);
b_eq.setOnClickListener(new EqualClickEvent(textView, s));
Button b_op = (Button) findViewById(R.id.ac);
b_op.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
s.clear();
textView.setText(s.getDisplay());
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable("STATE", s);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Serializable serializable = savedInstanceState.getSerializable("STATE");
if(serializable!= null){
s = (State) serializable;
}
}
public void onPause(){
super.onPause();
}
}
===============================State.java==================================
package com.trial.newcalculator;
import java.io.Serializable;
import android.text.Editable;
import android.widget.TextView;
public class State implements Serializable {
private static final long serialVersionUID = -1231231231231233L;
public TextView output;
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
MEMORYPLUS,
MEMORYMINUS,
MEMORYCALL,
MEMORYCLEAR,
}
public enum IOState{
INPUTTING,
DISPLAY_RESULT,
}
private Double accu = null;
private double current = 0;
private double memory = 0;
private Operation currentOp = null;
private IOState currentState = IOState.INPUTTING;
public Operation getCurrentOp() {
return currentOp;
}
public void setCurrentOp(Operation currentOp) {
if (currentState == IOState.INPUTTING){
if (accu != null && this.currentOp != null ){calculateResult();
}
else{accu = Double.valueOf(current);current = 0;
}
}
this.currentOp = currentOp;
if (currentState == IOState.INPUTTING){
currentState = IOState.DISPLAY_RESULT;
}
}
private void calculateResult() {
double res = accu.doubleValue();
switch (currentOp) {
case PLUS:
res += current;
break;
case MINUS:
res -= current;
break;
case MULTIPLY:
res *= current;
break;
case DIVIDE:
res /= current;
break;
case MEMORYPLUS:
memory += current;
break;
case MEMORYMINUS:
memory -= current;
break;
case MEMORYCLEAR:
memory = 0;
break;
case MEMORYCALL:
current = memory;
break;
}
accu = Double.valueOf(res);
current = 0;
}
public void number(int number) {
if (currentState == IOState.INPUTTING){
current = current *10 + number;
}
else if(currentState == IOState.DISPLAY_RESULT){
currentState = IOState.INPUTTING;
current = number;
}
}
public String getDisplay() {
String res;
Double d = getCurrentDisplayValue();
double doubleValue = d.doubleValue();
int intVal = (int)doubleValue;
if (intVal == doubleValue){
res = Integer.toString(intVal);
}
else{
res = d.toString();
}
return res;
}
private Double getCurrentDisplayValue() {
Double d = accu;
if (currentState == IOState.INPUTTING){
d = Double.valueOf(current);
}
return d;
}
public void clear() {
accu = null;
currentState = IOState.INPUTTING;
currentOp = null;
current = 0;
}
public void equal() {
if (accu == null || currentOp == null){
return;
}
calculateResult();
currentState = IOState.DISPLAY_RESULT;
currentOp = null;
current = getCurrentDisplayValue();
}
}
====================OperationClickEvent.java===============================
package com.trial.newcalculator;
import com.trial.newcalculator.State.Operation;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class OperationClickEvent implements OnClickListener {
private State s;
private TextView textView;
private Operation op;
public OperationClickEvent(TextView textView, State s, State.Operation op) {
super();
this.op = op;
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.setCurrentOp(op);
textView.setText(s.getDisplay());
}
}
=================EqualClickEvent.java=======================================
package com.trial.newcalculator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class EqualClickEvent implements OnClickListener {
private State s;
private TextView textView;
public EqualClickEvent(TextView textView, State s) {
super();
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.equal();
textView.setText(s.getDisplay());
}
}
======================NumberClickEvent.java==================================
package com.trial.newcalculator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class NumberClickEvent implements OnClickListener {
private int number;
private State s;
private TextView textView;
public NumberClickEvent(TextView textView, State s, int number) {
super();
this.number = number;
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.number(number);
textView.setText(s.getDisplay());
}
}
Instead of creating new classes for negative click event and doublezeroclickevent, i suggest you to get their id's and do the proper functionality when the particular button is clicked .
Each OnClickListener can be a default anonymous class, that will be triggered only by one button.
So no need to name them "NegativeClickEvent", "DoublezeroClickEvent", etc.
You can keep a boolean variable if the "." was pressed, and accept another one only if not.
If you want a usable calculator, you need a "backspace" button as well. So note that the dot may be deleted. (need to keep track of its placement).
For the leading 0, you can use a simple "if dot was pressed first, insert 0.".
There are many ways to implement what you want, but to keep it simple, just handle the cases you need to handle.
Other ways to implement this may include Double.parseDouble(s) with catch (NumberFormatException e) on each key pressed, or using a double as your buffer, and using the buttons to perform mathematical operations on it directly (such as multiply by 10 and adding the new digit on each button press) - this will ensure input validity without the need to parse String, but it's more complicated to implement.
Related
My app is a timed math game. Answer as many questions as you can before the timer runs out. When the time runs out, The GameOverActivity is now the current activity. I've realized that if I give no answer, the app will crash. If I give at least 1 answer, the app doesn't crash and everything is normal. I'm not sure where the flaw in my code exista.
This is the Main Activity
package stormy.incremental.randomtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class FastMathActivity extends AppCompatActivity {
int rand1, rand2, randDecider, correctAnswer, falseAnswer, problemsSolved;
String response,sumStr;
MyCountDownTimer myCountDownTimer;
int score;
Random r;
TextView randTV1, randTV2, scoreTV, sumTV, problemsSolvedTV, timerTV;
Button choice1, choice2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_test);
problemsSolved =0;
falseAnswer = 1;
//Initializing TextViews
timerTV = ((TextView) findViewById(R.id.timer));
randTV1 = ((TextView) findViewById(R.id.rand1));
randTV2 = ((TextView) findViewById(R.id.rand2));
sumTV = ((TextView) findViewById(R.id.sum));
scoreTV = ((TextView) findViewById(R.id.score));
problemsSolvedTV = ((TextView) findViewById(R.id.problemsSolved));
choice1 = ((Button) findViewById(R.id.choice1));
choice2 = ((Button) findViewById(R.id.choice2));
//Initializing a Random
r = new Random();
//Set the first question
setRandomProblem();
//Starting the timer
myCountDownTimer = new MyCountDownTimer(timerTV, 5000, 1000);
myCountDownTimer.start();
// Button Listeners
choice1.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
setRandomProblem();
}
});
choice2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
setRandomProblem();
}
});
}
public void checkResponse(Button v) {
//Convert the response and correctAnswer to String in order to compare values
response = v.getText().toString();
sumStr = Integer.toString(correctAnswer);
//If the user clicks the correct answer, increment score
if ((response.equals(sumStr))) {
score++;
scoreTV.setText(score+"");
}
//Increment the total amount of problems solved
problemsSolved++;
problemsSolvedTV.setText(problemsSolved+"");
//Keep track of the score within the timer
myCountDownTimer.recordScore(score,problemsSolved);
}
private void setRandomProblem() {
//Assigning random values to ints
rand1 = r.nextInt(5 - 1) + 1;
rand2 = r.nextInt(5 - 1) + 1;
randDecider = r.nextInt(2) + 1;
//The correctAnswer of the randoms
correctAnswer = rand1 + rand2;
//Setting the texts of the random values
randTV1.setText(rand1 + "");
randTV2.setText(rand2 + "");
//If the random deciding number is 1, set answer on choice1
if (randDecider == 1) {
choice1.setText(correctAnswer + "");
choice2.setText(correctAnswer + falseAnswer + "");
}
//If the random deciding number is 2, set answer on choice2
else {
choice1.setText(correctAnswer + falseAnswer + "");
choice2.setText(correctAnswer + "");
}
}
#Override
public void onStop(){
super.onStop();
//Stop the timer
myCountDownTimer.cancel();
}
}
This is the GameOverActivity
package stormy.incremental.randomtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
/**
* Created by kamalu on 12/25/2017.
*/
public class GameOverActivity extends AppCompatActivity {
TextView scoreTV, problemsSolvedTV, percentageTV;
int score, problemsSolved, percentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
//Initializing TextViews
scoreTV = ((TextView)findViewById(R.id.score));
problemsSolvedTV = ((TextView)findViewById(R.id.problemsSolved));
percentageTV = ((TextView)findViewById(R.id.percentage));
//Opening Bundle and assigning values
Bundle extras = getIntent().getExtras();
score = extras.getInt("score");
problemsSolved = extras.getInt("problemsSolved");
//calculating the accuracy
percentage = (score/problemsSolved)*100;
//Displaying the score
percentageTV.setText(percentage+"");
scoreTV.setText(score+"");
problemsSolvedTV.setText(problemsSolved+"");
}
//Start the game over
public void retry(View v){
Intent retryIntent = new Intent(GameOverActivity.this, FastMathActivity.class);
startActivity(retryIntent);
}
public void onBackPressed()
{
}
}
This is the Timer. I believe it to be important to note that the onFinish() method in this class starts the GameOverActivity.
package stormy.incremental.randomtest;
import android.content.Intent;
import android.os.CountDownTimer;
import android.widget.TextView;
public class MyCountDownTimer extends CountDownTimer {
TextView textCounter;
int score,problemsSolved;
public MyCountDownTimer(TextView textCounter, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.textCounter = textCounter;
}
#Override
public void onTick (long millisUntilFinished){
textCounter.setText(String.valueOf(millisUntilFinished / 1000));
}
#Override
public void onFinish () {
Intent gameOverIntent = new Intent(textCounter.getContext(), GameOverActivity.class);
gameOverIntent.putExtra("score", score);
gameOverIntent.putExtra("problemsSolved", problemsSolved);
textCounter.getContext().startActivity(gameOverIntent);
}
//Keep track of the scores
public void recordScore(int score,int problemsSolved){
this.problemsSolved = problemsSolved;
this.score = score;
}
}
You should check:
//calculating the accuracy
percentage = (score/problemsSolved)*100;
if problemsSolved = 0, your app will crash with exeptions: java.lang.ArithmeticException
You can refer:
if (problemSolved != 0){
//calculating the accuracy
percentage = (score/problemsSolved)*100;
} else {
// handle with problemSolved = 0;
}
I hope it can help your problem!
I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}
Hey guys I know there are many java programs for the factorial of a number...but I am facing problem with android. Following is my code....Thanks
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
long factorial = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
calcFactorial();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private void calcFactorial() {
if (number.getText().toString().equals("")) number.setText("0");
int num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
#Override
public void onClick(View v) {
calcFactorial();
answer.setText("Factorial of " + number.getText().toString() + " is : " + factorial);
}
}
This is my code and I need to know a way around for setting the hint instead of 0, but if I remove if (number.getText().toString().equals("")) number.setText("0");
then getting NullPointerException...
Also on the first go its calculating correctly but If I calculate again then getting wrong answer. I think some loop issue because I am directly using the value of factorial.
Please help thanks
Forget all that equal stuff, cover all basis and do it like this:
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
number.setHint("Enter number to be factorialized :P")
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private long calcFactorial() {
long factorial = 1;
try {
factorial = Long.parseLong(number.getText().toString());
for(int i=factorial-1; i>0; i--){
factorial = i * factorial;
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Incorrect Input", Toast.LENGTH_LONG).show();
} finally {}
return factorial;
}
#Override
public void onClick(View v) {
answer.setText("Factorial of " + number.getText().toString() + " is : " + calcFactorial());
}
Do something like.
private void calcFactorial() {
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
Rather than using
(number.getText().toString().equals("")) number.setText("0");
Use
(number.getText().length==0) number.setText("0");
** first go its calculating correctly but If I calculate again then getting wrong answer**
try like this
private void calcFactorial() {
factorial = 1;///Check out the line..
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
You need to make sure variable factorial is reinitialise to 1 .. for getting factorial for next number..
private void fact_isClicked(View view) {
if(textField.length()>0){
int ifac = Integer.parseInt(textField.getText().toString());
int fact = factorial(ifac);
tvsec.setText(String.valueOf(fact));
textField.setText(ifac+"!");
}}
i want to set a "0" in each "empyt" TextBoxes if the user clicks one button, to avoid an error in the app, any help? i dont know what to do
package com.doko.most;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class doko extends Activity {
private EditText bx1;
private EditText bx2;
private TextView txt3;
private Button btncalcular;
private Button btnreset;
private double variable1 = 0;
private double variable2 = 0;
private double variable3 = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
bx1 = (EditText)findViewById(R.id.bx1);
bx2 = (EditText)findViewById(R.id.bx2);
txt3 = (TextView)findViewById(R.id.txt3);
btncalcular = (Button)findViewById(R.id.btncalcular);
btnreset = (Button)findViewById(R.id.btnreset);
btncalcular.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calcular(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
}
private void calcular()
{
variable1 = Double.parseDouble(bx1.getText().toString());
variable2 = Double.parseDouble(bx2.getText().toString());
variable3 = Math.sqrt(1*2/3600);
txt3.setText(Double.toString(variable3));
}
private void reset(){
bx1.setText("");
bx2.setText("");
}
}
try something like this, quick and dirty:
private void calcular() {
try {
variable1 = Double.parseDouble(bx1.getText().toString());
}
catch(NumberFormatException e) {
bx1.setText("0");
}
try {
variable2 = Double.parseDouble(bx2.getText().toString());
}
catch(NumberFormatException e) {
bx2.setText("0");
}
variable3 = Math.sqrt(1*2/3600);
txt3.setText(Double.toString(3));
}
set up Hint property at your EditText
Ex.
and check it when you getText()
use str.isEmpty() and str.length to check user's inpupt
another way :
set up inputType for the EditText to number and setup Input filter
ex.
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(4);
input.setFilters(FilterArray);
Me Doing "edu.sju.BlackJack" Is not causing updates that are later called to occur.
I reference the layout correctly and the calls that are supposed to update it are correct, so what do I put in for the package name?
I should add that my package name according to the manifest is the above.
This is the code I have now which currently doesn't update the screen (or i'm guessing change the value correctly).
RemoteViews name = new RemoteViews("edu.sju.BlackJack", R.layout.play_screen);
If that's not it.. would it then be this code?
name.setTextViewText(R.id.Dealer_Total, "0");
Dealer_Total is the id for the TextView that I want to change.. however again the Change is not occurring.
Thanks in advance for any and all assistance.
Here is the whole of my code that i'm talking about, first Playscreen.java
package edu.sju.BlackJack;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.*;
public class PlayScreen extends Activity implements OnClickListener {
/** Called when the activity is first created. */
GameEngine Engine = new GameEngine();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_screen);
TextView TextDealer = (TextView)findViewById(R.id.Dealer_Total);
Engine.setView(TextDealer);
//Set up click listeners for all the buttons
View hitButton = findViewById(R.id.hit_button);
hitButton.setOnClickListener(this);
View standButton = findViewById(R.id.stand_button);
standButton.setOnClickListener(this);
//new preplay button (ML 10/24/10)
View prePlayButton = findViewById(R.id.prePlay_button);
prePlayButton.setOnClickListener(this);
Thread thread = new Thread(Engine);
thread.start();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.prePlay_button:
v.setVisibility(View.GONE);
System.out.println("Working?");
Engine.setGameStart(1);
break;
case R.id.hit_button:
Engine.gameHit(1);
break;
case R.id.stand_button:
Engine.gameStand(1);
break;
}
// More buttons go here (if any) ...
}
}
Now here's the GameEngine Thread
Not the Whole of it, just enough so you get the idea
package edu.sju.BlackJack;
import java.util.Random;
import android.widget.RemoteViews;
import android.widget.TextView;
public class GameEngine implements Runnable {
static int playerCount = 0; //keep record of which cards to change for player when hit is selected
static int dealerCount = 0; //keep record of which cards to change for dealer when dealer hits
static int win = 0; //keeps record of wins (JV 10/01/10)
static int lose = 0; //keeps record of loss (JV 10/01/10)
static int hit = 0; //let's engine know if hit button was selected (0 means it has not)
static int stand = 0; //let's engine know if stand button was selected (0 means it has not)
static int playerTotal = 0; //tells player's total (JV 10/01/10)
static int dealerTotal = 0; //tells dealer's total (JV 10/01/10)
static int playerTurn = 0; //activates buttons so that they do actions when clicked (as it's players turn)
static int startGame = 0; //starts the game when the start game button is pressed
TextView TextDealer;
RemoteViews name = new RemoteViews("edu.sju.BlackJack", R.layout.play_screen);
public void run() {
name.setTextViewText(R.id.Dealer_Total, "0");
//main();
}
public void setView(TextView a)
{
TextDealer = a;
}
public void setGameStart(int i)
{
startGame = i;
}
public void gameHit(int i)
{
if(playerTurn == 1)
hit = 1;
}
public void gameStand(int i)
{
if(playerTurn == 1)
stand = 1;
}
public void main()
{//Start Game
Deck mainDeck = new Deck();
fillDeck(mainDeck);
//TextView TextPlayer = (TextView)findViewById(R.id.Player_Total);
//TextDealer.setText("" + dealerTotal);
//TextPlayer.setText("" + playerTotal);
while(true)
{
if(startGame == 1)
{
if(mainDeck.getList().size() < 15){
mainDeck = emptyDeck();
fillDeck(mainDeck);
}
//RESET CARD VIEWS TO DEFAULT
//RESET DEALERCARD AND PLAYERCARD TOTALS TO 0
dealerTotal = 0;
playerTotal = 0;
playerCount = 0;
dealerCount = 0;
//playHand(mainDeck);
}
}
}
Whatever your problem is, I don't think it is what you think it is. If your layout is appearing in the app widget, then the package name is being handled properly. If the update (your setTextViewText() call) is not having an effect, then either R.layout.play_screen does not have R.id.Dealer_Total or you are not sending over a RemoteViews that contains the setTextViewText() instructions.