I am making one simple bank transfer Android application with Google voice input. So, basically, in my app I have created one method layoutclicked() for number of clicks on the layout. I have initialized numberOfclicks as 0 initially, so when user taps on the screen it increments. It will start voice input as well.
public void layoutClicked(View view)
{
if(IsInitialVoiceFinshed) {
numberOfClicks++;
listen();
}
}
I have created switch case statement for filling the input field, so like when case is 1, i.e user tap on the screen one time, then it will start voice input and user tell the details. It will set that text to that input field. And, again, in case 2 it will do another task.
If the user does not say anything in the first case, the field will be empty. And in case 2, they will go to another field. I want to fill that first input field. Can we achieve this by using for loop?
Here is my complete Java code
package org.tensorflow.lite.examples.detection;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
public class Banktransfer extends AppCompatActivity {
private TextToSpeech tts;
private TextView status;
private TextView To;
private TextView Subject;
private TextView To1;
private int numberOfClicks;
static String to;
float x1,x2;
private boolean IsInitialVoiceFinshed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bank_transfer);
IsInitialVoiceFinshed = false ;
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
tts.speak("Welcome to Bank transfer. tap on the screen , Tell me the IFSC code of bank",TextToSpeech.QUEUE_FLUSH,null);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
IsInitialVoiceFinshed=true;
}
}, 8500);
} else {
Log.e("TTS", "Initilization Failed!");
}
}
});
status = (TextView)findViewById(R.id.status);
To = (TextView) findViewById(R.id.to);
Subject = findViewById(R.id.subject);
To1 = (TextView) findViewById(R.id.to1);
numberOfClicks = 0;
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void layoutClicked(View view)
{
if(IsInitialVoiceFinshed) {
numberOfClicks++;
listen();
}
}
private void listen(){
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something");
try {
startActivityForResult(i, 100);
} catch (ActivityNotFoundException a) {
Toast.makeText(Banktransfer.this, "Your device doesn't support Speech Recognition", Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("SetTextI18n")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100&& IsInitialVoiceFinshed){
IsInitialVoiceFinshed = false;
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(result.get(0).contains("cancel"))
{
tts.speak("Transaction Cancelled!",TextToSpeech.QUEUE_FLUSH,null);
}
else {
switch (numberOfClicks) {
case 1:
To1.setText("");
String ifsc;
ifsc = result.get(0).replace(" ","");
char[] str=ifsc.toCharArray();
for(int i=0;i< str.length;i++){
To1.append(str[i]+"");
Toast.makeText(getApplicationContext(), To1.getText().toString(), Toast.LENGTH_SHORT).show();
}
if(!To1.getText().toString().isEmpty()) {
tts.speak("tap on the screen & say, account number to whom you want to transfer money? ",TextToSpeech.QUEUE_FLUSH,null);
}
break;
case 2:
to = result.get(0).replaceAll("[^\\d.]", "");
To.setText(to);
if(!to.isEmpty()) {
tts.speak("tap on the screen & say, how much money you want to transfer",TextToSpeech.QUEUE_FLUSH,null);
}
break;
case 3:
String amount;
amount = result.get(0).replaceAll("[^\\d.]", "");
Subject.setText(amount);
status.setText("confirm");
if(!amount.isEmpty()) {
tts.speak("Please Confirm the details , IFSC code is "+To1.getText().toString()+",Account number is: " + Arrays.toString(To.getText().toString().split("(?!^)")) + ". And Money that you want to transfer is ,: " + Subject.getText().toString() +"rupees"+ ",Tap on the screen and Speak Yes to confirm",TextToSpeech.QUEUE_FLUSH,null);
tts.speak(",swipe left to listen again, or say Yes to confirm or no to cancel the transaction",TextToSpeech.QUEUE_ADD,null);
}
break;
default:
if(result.get(0).equals("yes")) {
if (To.getText().toString().equals("")) {
if (Subject.getText().toString().equals("")) {
tts.speak("Details may be incorrect or incomplete, canceling the transaction",TextToSpeech.QUEUE_FLUSH,null);
final Handler h = new Handler(Looper.getMainLooper());
h.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Banktransfer.this,MainActivity.class);
startActivity(i);
}
},8000);
}
} else {
status.setText("transferring money ");
tts.speak("transferring money please wait",TextToSpeech.QUEUE_FLUSH,null);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
status.setText("Amount transferred successfully.");
tts.speak("Amount transferred successfully.",TextToSpeech.QUEUE_FLUSH,null);
}
}, 6000);
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
finish();
Intent intent = new Intent(Banktransfer.this, MainActivity.class);
startActivity(intent);
tts.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
}, 9000);
}
}
else if(result.get(0).contains("no")){
tts.speak("transaction cancelled",TextToSpeech.QUEUE_FLUSH,null);
To.setText("");
Subject.setText("");
IsInitialVoiceFinshed=true;
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
finish();
Intent intent = new Intent(Banktransfer.this,MainActivity.class);
startActivity(intent);
}
},3000);
}
}
}
}
else {
switch (numberOfClicks) {
case 1:
break;
case 2:
break;
default:
tts.speak("say yes to proceed the transaction or no to cancel the transaction",TextToSpeech.QUEUE_FLUSH,null);
break;
}
numberOfClicks--;
}
}
IsInitialVoiceFinshed=true;
}
public boolean onTouchEvent(MotionEvent touchEvent) {
switch (touchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
if (x1 < x2) {
tts.speak("Please Confirm the details , IFSC code is "+To1.getText().toString()+"Account number is: " + Arrays.toString(To.getText().toString().split("(?!^)")) + ". And Money that you want to transfer is ,: " + Subject.getText().toString() +"rupees"+ ",Tap on the screen and Speak Yes to confirm",TextToSpeech.QUEUE_FLUSH,null);
tts.speak("swipe left to listen again, and say Yes to confirm or no to cancel the transaction",TextToSpeech.QUEUE_ADD,null);
break;
}
if (x1 > x2) {
break;
}
break;
}
return false;
}
public void onPause() {
if (tts != null) {
tts.stop();
}
super.onPause();
}
}
bank_transfer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#faa519"
android:orientation="vertical"
android:onClick = "layoutClicked"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="48dp"
android:background="#e8e8e7"
android:orientation="horizontal">
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginLeft="25dp"
android:text="Bank transfer"
android:textColor="#2582C5"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="30dp"
android:orientation="vertical">
<ImageView
android:layout_width="161dp"
android:layout_height="77dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:src="#drawable/bank" />
<TextView
android:id="#+id/to1"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginTop="70dp"
android:background="#f3f3f3"
android:paddingLeft="7dp"
android:paddingTop="7dp"
android:text="IFSC Code"
android:textColor="#4C4D4F" />
<TextView
android:id="#+id/to"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginTop="80dp"
android:background="#f3f3f3"
android:paddingLeft="7dp"
android:paddingTop="7dp"
android:text="Acc. no"
android:textColor="#4C4D4F" />
<TextView
android:id="#+id/subject"
android:layout_width="fill_parent"
android:layout_height="95dp"
android:layout_marginTop="95dp"
android:background="#f3f3f3"
android:text="Transfer money:- "
android:textColor="#4C4D4F" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Instead of using switch statement You can use the codes below:
if(//){
}else if(//){
}else if(//){
}else if(//){
}else{
//
}
but switch statement, it's simpler and readable than the if and else if
Related
I have a problem with my setOnClickListener method for one of the buttons in my code. What basically happens is that I call a typeFinder inside the setOnClickListener method, but the first time I press the button the values do not get updated. I have used the debugger and from my understanding what happens is that even though the function is called, the program does not actually go through the function until after setOnClickListener, which means when I press the button the second time it has the right values to show from the previous button press. I have tried using TypesTask as well (as seen in commented part at the bottom of the page), but doing so resulted in the same outcome.
Here is the code for the class:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private DatabaseReference myRef;
private ArrayList<String> recipesList = new ArrayList<String>();
private String[] types = {"pizza", "ice cream", "sandwich", "salad", "steak"};
private void typeFinder(String type) {
myRef.orderByChild("type").equalTo(type).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String word = "";
boolean wordAdded = false;
String value = dataSnapshot.getValue().toString();
for (int i = 0; i < value.length(); i++) {
if (wordAdded == false) {
if (value.charAt(i) == '=') {
recipesList.add(word);
wordAdded = true;
word = "";
} else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
if (word.length() == 0 && value.charAt(i) == ' ') {
} else {
word = word + value.charAt(i);
}
}
}
if (value.charAt(i) == '}')
if (i + 2 == value.length()) {
wordAdded = false;
break;
} else
wordAdded = false;
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
myRef = FirebaseDatabase.getInstance().getReference();
Button saladsB = (Button) findViewById(R.id.saladButton);
Button pizzaB = (Button) findViewById(R.id.pizzaButton);
Button iceCreamB = (Button) findViewById(R.id.iceCreamButton);
Button steakB = (Button) findViewById(R.id.steakButton);
Button sandwichB = (Button) findViewById(R.id.sandwichButton);
final TextView testTextView = (TextView) findViewById(R.id.test_text_view);
testTextView.setText(Integer.toString(recipesList.size()));
super.onCreate(savedInstanceState);
saladsB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// recipesList.clear();
// t.typeFinder("salad")
typeFinder("salad");
// new TypesTask().execute("salad");
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
testTextView.setText(recipes);
// Intent intent = new Intent(MainActivity.this, ListviewActivity.class);
// intent.putStringArrayListExtra("FOOD_LIST", recipesList);
// startActivity(intent);
}
});
}
/*
public class TypesTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
myRef = FirebaseDatabase.getInstance().getReference();
}
#Override
protected Void doInBackground(String... params) {
typeFinder(params[0]);
return null;
}
}
*/
}
Here is the xml for the page
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.thevash.recipes.MainActivity">
<LinearLayout
android:layout_width="0dp"
android:layout_height="810dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="458dp"
android:orientation="horizontal"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1">
<TextView
android:id="#+id/test_text_view"
android:layout_width="585dp"
android:layout_height="248dp"
android:layout_weight="1"
android:text="TextView"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="-377dp" />
</LinearLayout>
<Button
android:id="#+id/saladButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Salads"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="5dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/pizzaButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Pizzas"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="52dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/iceCreamButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="ice cream"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/pizzaButton"
app:layout_constraintTop_toBottomOf="#+id/pizzaButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/pizzaButton" />
<Button
android:id="#+id/steakButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="steaks"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/iceCreamButton"
app:layout_constraintTop_toBottomOf="#+id/iceCreamButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/iceCreamButton" />
<Button
android:id="#+id/sandwichButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="sandwiches"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/steakButton"
app:layout_constraintTop_toBottomOf="#+id/steakButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/steakButton" />
</android.support.constraint.ConstraintLayout>
you can do this using TypesTask but you need to modify TypesTask class like below
public class TypesTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
myRef = FirebaseDatabase.getInstance().getReference();
}
#Override
protected Void doInBackground(String... params) {
typeFinder(params[0]);
return null;
}
#Override
onPostExecute(Void result){
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
testTextView.setText(recipes);
}
}
and your onClick should be like this
saladsB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TypesTask().execute("salad");
}
});
As mentioned in the comments both of the answers provided work. I either had to add the UI update to the typeFinder function itself, or use AsyncTask to update the UI inside onPostExecute method. For the latter I had to put the program to sleep for one second after the line typeFinder(params[0]) to give it enough time to update the variables.
Your method in which you are building the reciepeList is an asynchronous call. You need to update the changes to Ui after the OnSuccess() call of EventListener. Relocate the Ui updation code to OnDataChange See the code below :
private void typeFinder(String type) {
myRef.orderByChild("type").equalTo(type).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String word = "";
boolean wordAdded = false;
String value = dataSnapshot.getValue().toString();
for (int i = 0; i < value.length(); i++) {
if (wordAdded == false) {
if (value.charAt(i) == '=') {
recipesList.add(word);
wordAdded = true;
word = "";
} else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
if (word.length() == 0 && value.charAt(i) == ' ') {
} else {
word = word + value.charAt(i);
}
}
}
if (value.charAt(i) == '}')
if (i + 2 == value.length()) {
wordAdded = false;
break;
} else
wordAdded = false;
}
// Update the Ui Here
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
this.testTextView.setText(recipes);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
I'm working on a small project where a user is shown his result after he tries to login and he already taken the quiz on my app.
So i'm using a page like this to display result.
But i cannot display my score. This page also has an option to share your score which is working fine and displaying score.Share option containing result.
I'm attaching my XML and Java Code kindly please help me solve the issue that'll be great help.
Thanks & Regards
BugAdder
XML Code:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center|top">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="20dp"
android:textAlignment="center"
android:textSize="25sp"
android:textStyle="bold"
android:text="#string/login_score_title"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="20dp"
android:textSize="25sp"
android:textStyle="bold"
android:text="#string/score_result"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textStyle="bold"
android:id="#+id/login_score_text"/>
<Button
android:padding="20dp"
android:layout_marginTop="75dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/login_share_button"
android:text="#string/share_button"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="#string/exit_button"
android:drawableEnd="#drawable/arrow_right"
android:drawableRight="#drawable/arrow_right"
android:id="#+id/login_exit_button"/>
</LinearLayout>
</ScrollView>
Java Code:
public class QuizLoginScore extends AppCompatActivity {
private List<ScoreItem> mScoreItems = new ArrayList<>();
private ProgressDialog mProgressDialog;
private String mScore;
private TextView mScoreTextView;
private Button mShareButton;
private Button mExitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_login_quiz);
mScoreTextView = (TextView)findViewById(R.id.login_score_text);
mShareButton = (Button)findViewById(R.id.login_share_button);
mExitButton = (Button)findViewById(R.id.login_exit_button);
new FetchScoresTask().execute();
mScoreTextView.setText(mScore);
mExitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= 21){
finishAndRemoveTask();
}else{
finishAffinity();
System.exit(0);
}
}
});
mShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,getScoreShareReport(mScore));
i.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.score_report_subject));
i = Intent.createChooser(i,getString(R.string.send_report));
startActivity(i);
}
});
}
public String getScoreShareReport(String score){
String result;
StringBuilder sb = new StringBuilder();
sb.append("QuizApp!").
append("\n\n").
append("I Just Scored").
append(" \' ").
append(score).
append(" \' ").
append("marks out of \' 100 \' in Latest Quiz on QuizApp!\nWhats your Score Huh?");
result = sb.toString();
return result;
}
private class FetchScoresTask extends AsyncTask<Void, Void, List<ScoreItem>> {
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(QuizLoginScore.this);
mProgressDialog.setTitle("Downloading Score");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMessage("Please wait while the score is being downloaded!");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected List<ScoreItem> doInBackground(Void... params) {
return new ScoreFetcher().fetchScoreItems();
}
#Override
protected void onPostExecute(List<ScoreItem> scoreItems) {
mScoreItems = scoreItems;
for(int i = 0; i < mScoreItems.size(); i++){
if(mScoreItems.get(i).getUserId().equals(QuizLogin.mUserIdString)){
mScore = String.valueOf(mScoreItems.get(i).getScore());
break;
}
}
mProgressDialog.dismiss();
}
}
}
mScore is set in a async task. so you must set text in onPostExecute. try following code:
public class QuizLoginScore extends AppCompatActivity {
private List<ScoreItem> mScoreItems = new ArrayList<>();
private ProgressDialog mProgressDialog;
private String mScore;
private TextView mScoreTextView;
private Button mShareButton;
private Button mExitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_login_quiz);
mScoreTextView = (TextView)findViewById(R.id.login_score_text);
mShareButton = (Button)findViewById(R.id.login_share_button);
mExitButton = (Button)findViewById(R.id.login_exit_button);
new FetchScoresTask().execute();
mScoreTextView.setText(mScore);
mExitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= 21){
finishAndRemoveTask();
}else{
finishAffinity();
System.exit(0);
}
}
});
mShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,getScoreShareReport(mScore));
i.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.score_report_subject));
i = Intent.createChooser(i,getString(R.string.send_report));
startActivity(i);
}
});
}
public String getScoreShareReport(String score){
String result;
StringBuilder sb = new StringBuilder();
sb.append("QuizApp!").
append("\n\n").
append("I Just Scored").
append(" \' ").
append(score).
append(" \' ").
append("marks out of \' 100 \' in Latest Quiz on QuizApp!\nWhats your Score Huh?");
result = sb.toString();
return result;
}
private class FetchScoresTask extends AsyncTask<Void, Void, List<ScoreItem>> {
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(QuizLoginScore.this);
mProgressDialog.setTitle("Downloading Score");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMessage("Please wait while the score is being downloaded!");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected List<ScoreItem> doInBackground(Void... params) {
return new ScoreFetcher().fetchScoreItems();
}
#Override
protected void onPostExecute(List<ScoreItem> scoreItems) {
mScoreItems = scoreItems;
for(int i = 0; i < mScoreItems.size(); i++){
if(mScoreItems.get(i).getUserId().equals(QuizLogin.mUserIdString)){
mScore = String.valueOf(mScoreItems.get(i).getScore());
mScoreTextView.setText(mScore);
break;
}
}
mProgressDialog.dismiss();
}
}
}
Put your mScore string in log to see if you are getting the data in logcat. Also try changing the color of your textview. Also put your textview.settext() in onpostexecute(); method
Set text from onPostExecute():
#Override
protected void onPostExecute(List<ScoreItem> scoreItems) {
mScoreItems = scoreItems;
for(int i = 0; i < mScoreItems.size(); i++){
if(mScoreItems.get(i).getUserId().equals(QuizLogin.mUserIdString)){
mScore = String.valueOf(mScoreItems.get(i).getScore());
mScoreTextView.setText(mScore);
break;
}
}
mProgressDialog.dismiss();
}
#Update
When i create new project everything its fine. But i don't know what is wrong. I just refactor all names with e-mail to login, change type of textview e-mail to normal.
I have problem with simple app. I made default loading activity. And change e-mail to login. So there will be login and password.
But app stop on device. There is error EGL_BAD_MATCH
Android monitor error
01-03 18:43:35.591 4738-4757/com.example.rachel.safemessenger E/EGL_emulation: tid 4757: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
01-03 18:43:35.591 4738-4757/com.example.rachel.safemessenger W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x923a4660, error=EGL_BAD_MATCH
Please help.
LoginActivity.java
package com.example.rachel.safemessenger;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor>
{
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo#example.com:hello", "bar#example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mLoginView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mLoginView = (AutoCompleteTextView) findViewById(R.id.activityLogin_login);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.activityLogin_password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent)
{
if (id == R.id.login || id == EditorInfo.IME_NULL)
{
attemptLogin();
return true;
}
return false;
}
});
Button mLoginSignInButton = (Button) findViewById(R.id.activityLogin_name_sign_in_button);
mLoginSignInButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.activityLogin_login_form);
mProgressView = findViewById(R.id.activityLogin_login_progress);
}
private void populateAutoComplete()
{
if (!mayRequestContacts())
{
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts()
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
{
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
{
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS))
{
Snackbar.make(mLoginView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener()
{
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v)
{
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else
{
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults)
{
if (requestCode == REQUEST_READ_CONTACTS)
{
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin()
{
if (mAuthTask != null)
{
return;
}
// Reset errors.
mLoginView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String login = mLoginView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
{
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid login address.
if (TextUtils.isEmpty(login))
{
mLoginView.setError(getString(R.string.error_field_required));
focusView = mLoginView;
cancel = true;
} else if (!isLoginValid(login))
{
mLoginView.setError(getString(R.string.error_invalid_login));
focusView = mLoginView;
cancel = true;
}
if (cancel)
{
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else
{
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(login, password);
mAuthTask.execute((Void) null);
}
}
private boolean isLoginValid(String login)
{
//TODO: Replace this with your own logic
return login.contains("#");
}
private boolean isPasswordValid(String password)
{
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show)
{
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
{
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter()
{
#Override
public void onAnimationEnd(Animator animation)
{
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter()
{
#Override
public void onAnimationEnd(Animator animation)
{
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else
{
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle)
{
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor)
{
List<String> logins = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
logins.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addLoginsToAutoComplete(logins);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader)
{
}
private void addLoginsToAutoComplete(List<String> loginAddressCollection)
{
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, loginAddressCollection);
mLoginView.setAdapter(adapter);
}
private interface ProfileQuery
{
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean>
{
private final String mLogin;
private final String mPassword;
UserLoginTask(String login, String password)
{
mLogin = login;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params)
{
// TODO: attempt authentication against a network service.
try
{
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e)
{
return false;
}
for (String credential : DUMMY_CREDENTIALS)
{
String[] pieces = credential.split(":");
if (pieces[0].equals(mLogin))
{
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
#Override
protected void onPostExecute(final Boolean success)
{
mAuthTask = null;
showProgress(false);
if (success)
{
finish();
} else
{
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled()
{
mAuthTask = null;
showProgress(false);
}
}
}
activity_login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
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.rachel.safemessenger.LoginActivity">
<!-- Login progress -->
<ProgressBar
android:id="#+id/activityLogin_login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/activityLogin_login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/activityLogin_name_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/activityLogin_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_email"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/activityLogin_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/activityLogin_name_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/action_sign_in"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
strings.xml
<resources>
<string name="app_name">SafeMessenger</string>
<!-- Strings related to login -->
<string name="prompt_email">Nick</string>
<string name="prompt_password">Password </string>
<string name="action_sign_in">Sign in or register</string>
<string name="action_sign_in_short">Sign in</string>
<string name="error_invalid_login">This login is invalid</string>
<string name="error_invalid_password">This password is too short</string>
<string name="error_incorrect_password">This password is incorrect</string>
<string name="error_field_required">This field is required</string>
<string name="permission_rationale">"Contacts permissions are needed for providing email
completions."
</string>
</resources>
ok, now it works. I think somehow to correct without my participation.
I update android devices and reset computer and now it works.
I am trying to use a thread to count down the seconds to answer a question.
This is updating the seconds left to a TextView on the screen
I want to restart the timer after a question is answered.
How do I stop/start or restart the timer thread.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_thread_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ebookfrenzy.threadexample.ThreadExampleActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/myTextView"
app:layout_constraintBottom_toBottomOf="#+id/activity_thread_example"
app:layout_constraintRight_toRightOf="#+id/activity_thread_example"
app:layout_constraintLeft_toLeftOf="#+id/activity_thread_example"
app:layout_constraintTop_toTopOf="#+id/activity_thread_example" />
<Button
android:text="#string/press_me"
android:layout_width="wrap_content"
android:layout_height="51dp"
android:id="#+id/button"
app:layout_constraintRight_toRightOf="#+id/myTextView"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="#+id/myTextView"
app:layout_constraintLeft_toLeftOf="#+id/myTextView"
android:onClick="buttonClick" />
</android.support.constraint.ConstraintLayout>
package com.enceladussoftware.threadexample;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.util.Objects;
public class ThreadExampleActivity extends AppCompatActivity {
private static String TAG = "Thread";
Handler mhandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
String string = bundle.getString("myKey");
TextView myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText(string);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread_example);
Log.i(TAG, "oncreate()");
}
public void buttonClick(View v) {
int threadNumber = 1;
final Thread myThread = new Thread("myThread" + threadNumber) {
public void run() {
Looper.prepare();
Log.i(TAG, "Start run()");
int i = 10;
while (i>=0) {
Log.i(TAG, ( "Remaining: " + i + " seconds. "));
Message msg = mhandler.obtainMessage();
Bundle bundle = new Bundle();
String dateString = String.valueOf(i);
bundle.putString("myKey", dateString);
msg.setData(bundle);
mhandler.sendMessage(msg);
try {
i--;
Thread.sleep(1000L); // 1000L = 1000ms = 1 second
} catch (InterruptedException e) {
//I don't think you need to do anything for your particular problem
}
}
Log.i(TAG, "End runabble()");
Looper.loop();
}
};
myThread.start();
}
}
CountDownTimer counter = new CountDownTimer(30000, 1000){
public void onTick(long millisUntilDone){
Log.d("counter_label", "Counter text should be changed");
tv.setText("You have " + millisUntilDone + "ms");
}
public void onFinish() {
tv.setText("DONE!");
}
};
counter.start();
counter.cancel(); // cancel
counter.start(); // then restart
if the thread has terminated,you cant restart it.what you can do is to create a new Thread instance.
refer to this answer
Define your thread object outside buttonClick as class variable
To stop your thread you could call it
if(mThread.isAlive())
mThread.interrupt();
And Start again as a new instance when you will need for counting of another question by calling
mThread.start();
I am learning how to make an android app, as my first project I'm trying to build a stupid game haha.
when I get to my second activity, The game runs as it has to (picture down)
http://i.imgur.com/BBllAJU.png?1
Than nothing changes, the score, the numbers, but all the toasts still coming.
package com.example.moshik.whatisbigger;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.DynamicLayout;
import android.text.Layout;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class NormalModeActivity1 extends AppCompatActivity {
int Score = 0;
boolean AnswerBig = false;
boolean AnswerEqual = false;
boolean AnswerSmall = false;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_mode1);
Random rnd = new Random();
while (counter < 5) {
int Number1 = rnd.nextInt(99) + 1;
TextView X = (TextView) findViewById(R.id.XNumber);
String Xstring = String.valueOf(Number1);
X.setText(Xstring);
int Number2 = rnd.nextInt(99) + 1;
TextView Y = (TextView) findViewById(R.id.YNumber);
String Ystring = String.valueOf(Number2);
Y.setText(Ystring);
if (Number1 > Number2) {
AnswerBig = true;
}
if (Number1 == Number2) {
AnswerEqual = true;
}
if (Number1 < Number2) {
AnswerSmall = true;
}
findViewById(R.id.Bigger).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerBig) {
Toast.makeText(NormalModeActivity1.this, "(BIG)You are RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerBig = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(BIG)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.Equal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerEqual) {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerEqual = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.Smaller).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerSmall)
{
Toast.makeText(NormalModeActivity1.this, "(Small)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerSmall = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Small)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
TextView score = (TextView) findViewById(R.id.ScoreDisplay);
String ScoreShow;
ScoreShow = String.valueOf(Score);
score.setText("Your Score Is: " + ScoreShow);
counter++;
if (counter > 5)
{
score.setText("ItsOver!!!");
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.moshik.whatisbigger.NormalModeActivity1">
<include layout="#layout/content_normal_mode1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:id="#+id/ScoreDisplay"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/XNumber"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/ScoreDisplay"
android:layout_toStartOf="#+id/ScoreDisplay"
android:textSize="20sp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/YNumber"
android:layout_alignTop="#+id/XNumber"
android:layout_toRightOf="#+id/ScoreDisplay"
android:layout_toEndOf="#+id/ScoreDisplay"
android:textSize="20sp">
</TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Bigger"
android:layout_marginTop="121dp"
android:hint="#string/BIG"
android:layout_below="#+id/XNumber"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Equal"
android:layout_alignTop="#+id/Bigger"
android:layout_centerHorizontal="true"
android:hint="#string/EQUAL">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Smaller"
android:hint="#string/SMALL"
android:layout_alignTop="#+id/Equal"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</Button>
Here is the layout and the activity itself.
Can you find what the problem here or what I miss?, thank you very much :)
You are never updating your score TextView. Change it to a class field first so it is easier to access in your callbacks.
private TextView score;
and then in your onCreate method:
score = (TextView) findViewById(R.id.ScoreDisplay);
Then update the text in each callback click listener after incrementing Score:
Score++;
score.setText("Your Score Is: " + Score);
Also, I would update your variable names to be more different as using Score for an int and score for a TextView is confusing.
Update Showing class field:
public class NormalModeActivity1 extends AppCompatActivity {
int Score = 0;
boolean AnswerBig = false;
boolean AnswerEqual = false;
boolean AnswerSmall = false;
int counter = 0;
TextView X;
TextView Y;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_mode1);
// set class fields
X = (TextView) findViewById(R.id.XNumber);
Y = (TextView) findViewById(R.id.YNumber);
score = (TextView) findViewById(R.id.ScoreDisplay);
Random rnd = new Random();
int Number1 = rnd.nextInt(99) + 1;
String Xstring = String.valueOf(Number1);
X.setText(Xstring);
int Number2 = rnd.nextInt(99) + 1;
String Ystring = String.valueOf(Number2);
Y.setText(Ystring);
if (Number1 > Number2) {
AnswerBig = true;
}
if (Number1 == Number2) {
AnswerEqual = true;
}
if (Number1 < Number2) {
AnswerSmall = true;
}
findViewById(R.id.Bigger).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerBig) {
Toast.makeText(NormalModeActivity1.this, "(BIG)You are RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerBig = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(BIG)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
findViewById(R.id.Equal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerEqual) {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerEqual = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
findViewById(R.id.Smaller).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerSmall)
{
Toast.makeText(NormalModeActivity1.this, "(Small)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerSmall = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Small)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
String ScoreShow;
ScoreShow = String.valueOf(Score);
score.setText("Your Score Is: " + ScoreShow);
}
private void incrementAndCheckCounter() {
counter++;
if (counter > 5)
{
score.setText("ItsOver!!!");
}
}
}