Fatal Exception: Timer-0? - java

Im creating a game which calculates reaction times. I am using a timer to get the time it takes for a user to press a button. For some reason I am getting a Timer-0 Exception when I try run the app.
LOGCAT
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.example.abz.layouts, PID: 16015
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6556)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:942)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:5081)
at android.view.View.invalidateInternal(View.java:12713)
at android.view.View.invalidate(View.java:12649)
at android.view.View.invalidateDrawable(View.java:16788)
at android.widget.TextView.invalidateDrawable(TextView.java:5408)
at android.graphics.drawable.Drawable.invalidateSelf(Drawable.java:385)
at android.graphics.drawable.RippleDrawable.invalidateSelf(RippleDrawable.java:705)
at android.graphics.drawable.RippleDrawable.invalidateSelf(RippleDrawable.java:701)
at android.graphics.drawable.LayerDrawable.invalidateDrawable(LayerDrawable.java:896)
at android.graphics.drawable.DrawableWrapper.invalidateDrawable(DrawableWrapper.java:153)
at android.graphics.drawable.Drawable.invalidateSelf(Drawable.java:385)
at android.graphics.drawable.GradientDrawable.setColorFilter(GradientDrawable.java:837)
at android.graphics.drawable.DrawableWrapper.setColorFilter(DrawableWrapper.java:243)
at android.graphics.drawable.LayerDrawable.setColorFilter(LayerDrawable.java:1285)
at android.graphics.drawable.Drawable.clearColorFilter(Drawable.java:600)
at com.example.abz.layouts.HighLight.run(HighLight.java:33)
at java.util.Timer$TimerImpl.run(Timer.java:284)
D/EGL_emulation: eglMakeCurrent: 0xae424780: ver 3 0 (tinfo 0xae412ba0)
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaaac9820
Application terminated.
Here are my java classes
MainActivty.java
package com.example.abz.layouts;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private long start_time;
private long end_time;
private Button finalButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
// Create list of buttons
ArrayList<Button> buttons = createButtonsArrayList();
// Generates sequence of 5 random buttons
RandomSequence randomSequence = new RandomSequence(buttons, 5, 9);
// Add OnClickListener for last button
finalButton = randomSequence.sequence.get(randomSequence.sequence.size() - 1);
finalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalButtonClicked();
}
});
// Start Game
start_time = System.nanoTime();
randomSequence.startSequence();
}
private void finalButtonClicked() {
end_time = System.nanoTime();
double diffInMillis = (end_time - start_time) / 1e6;
finalButton.getBackground().clearColorFilter();
Toast toast = Toast.makeText(this, "Reaction time: " + diffInMillis + " milliseconds.", Toast.LENGTH_LONG);
toast.show();
}
private ArrayList<Button> createButtonsArrayList() {
ArrayList<Button> buttons = new ArrayList<>();
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button)findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
final Button button4 = (Button) findViewById(R.id.button4);
final Button button5 = (Button) findViewById(R.id.button5);
final Button button6 = (Button) findViewById(R.id.button6);
final Button button7 = (Button) findViewById(R.id.button7);
final Button button8 = (Button) findViewById(R.id.button8);
final Button button9 = (Button) findViewById(R.id.button9);
buttons.add(button1);
buttons.add(button2);
buttons.add(button3);
buttons.add(button4);
buttons.add(button5);
buttons.add(button6);
buttons.add(button7);
buttons.add(button8);
buttons.add(button9);
return buttons;
}
}
HighLight.java
package com.example.abz.layouts;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.widget.Button;
import java.util.ArrayList;
import java.util.TimerTask;
public class HighLight extends TimerTask {
private ArrayList<Button> sequence;
private int sequencePosition;
public HighLight(ArrayList<Button> sequence) {
this.sequence = sequence;
sequencePosition = 0;
}
public void run() {
Button activeButton = sequence.get(sequencePosition);
if (sequencePosition == 0) {
activeButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
} else if (sequencePosition == sequence.size() - 1) {
Button previousActiveButton = sequence.get(sequencePosition - 1);
previousActiveButton.getBackground().clearColorFilter();
activeButton.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
// TODO: PLAY SOUND FOR FINAL BUTTON
this.cancel();
} else {
Button previousActiveButton = sequence.get(sequencePosition - 1);
previousActiveButton.getBackground().clearColorFilter();
activeButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
}
sequencePosition++;
}
}
RandomSequence.java
package com.example.abz.layouts;
import android.os.Looper;
import android.widget.Button;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.logging.Handler;
public class RandomSequence {
public ArrayList<Button> sequence;
private ArrayList<Button> buttons;
private int length;
public RandomSequence(ArrayList<Button> buttons, int low, int high) {
this.buttons = buttons;
length = newRandomNumber(low, high);
sequence = generateRandomSequence();
}
public void startSequence() {
Timer timer = new Timer();
timer.schedule(new HighLight(sequence), 0, 1500);
}
private ArrayList<Button> generateRandomSequence() {
ArrayList<Button> randomSequence = new ArrayList<>();
for (int i = 1; i <= length; i++) {
int random = newRandomNumber(0, buttons.size());
Button button = buttons.get(random);
// Ensure not same number in a row
while (randomSequence.size() > 0 && button.getId() == randomSequence.get(randomSequence.size() - 1).getId()) {
random = newRandomNumber(0, buttons.size());
button = buttons.get(random);
}
randomSequence.add(buttons.get(random));
}
return randomSequence;
}
private int newRandomNumber(int low, int high) {
Random r = new Random();
return r.nextInt(high - low) + low;
}
}
I have tried looking for solutions but was not successful.

The key line in your logcat is this:
Only the original thread that created a view hierarchy can touch its views
You're trying to make changes to UI elements outside the main thread, in this case with calls to previousActiveButton.getBackground().clearColorFilter() within HighLight.run().
You can either post your run() method on a Handler created on the main thread, or wrap UI-related calls within runOnUiThread(). Because you're using a self-contained class that extends TimerTask, I recommend the former:
public void run() {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Button activeButton = sequence.get(sequencePosition);
if (sequencePosition == 0) {
activeButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
} else if (sequencePosition == sequence.size() - 1) {
Button previousActiveButton = sequence.get(sequencePosition - 1);
previousActiveButton.getBackground().clearColorFilter();
activeButton.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
// TODO: PLAY SOUND FOR FINAL BUTTON
HighLight.this.cancel();
} else {
Button previousActiveButton = sequence.get(sequencePosition - 1);
previousActiveButton.getBackground().clearColorFilter();
activeButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
}
}
});
sequencePosition++;
}
Though personally I'd look into using a recursive Handler::postDelayed() rather than a Timer

Related

CountDownTimer for quiz can't be accessed how I need it to be

I am writing a small math's quiz with 10 questions per level. I'm trying to write a 10 second timer which has the following functions:
Moves to the next question when it runs out and restarts the timer
Restarts when a question is entered
My issue is that regardless of how I write this code, I cannot access the timer from both the "onFinish()" function as well as the rest of the program. such as "onCorrect()" I need to be able to cancel and restart an existing timer initialised in "onCreate()" however I can't then access that timer through a MyCountDownTimer class or function (I've tried using both to no avail.)
My code is below with comments to show where I need the timers to work.
package com.example.myapplication;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class Level2 extends AppCompatActivity {
int score = 0;
int q = 1;
TextView value;
TextView q_num;
TextView timer_label = findViewById(R.id.Timer);
/*public class MyCountDownTimer extends CountDownTimer {
TextView timer_label = findViewById(R.id.Timer);
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
onDone();
}
#Override
public void onTick(long millisUntilFinished) {
int temp = (int)millisUntilFinished/1000;
//do what ever You want
timer_label.setText(String.format(getResources().getString(R.string.timer_string),String.valueOf(temp)));
}
}
#Override
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level2);
q = 1;
//MyCountDownTimer t = new MyCountDownTimer(11000,1000);
Button b1 = findViewById(R.id.option1);
Button b2 = findViewById(R.id.option2);
Button b3 = findViewById(R.id.option3);
Button b4 = findViewById(R.id.option4);
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
//
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //bellow setSupportActionBar(toolbar);
getSupportActionBar().setCustomView(R.layout.action_layout);
//Gives action bar style
value = findViewById(R.id.score_value);
q_num = findViewById(R.id.question_number);
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b1.getText();
onCheck(ans,score);
}
});
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b2.getText();
onCheck(ans,score);
}
});
b3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b3.getText();
onCheck(ans,score);
}
});
b4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b4.getText();
onCheck(ans,score);
}
});
}
public void onCheck(String ans, int score) {
TextView ans_data = findViewById(R.id.answer_data);
String correct = (String) ans_data.getText();
if (ans.contains(correct)) {
onCorrect(score);
}
else{
onWrong();
}
}
public void onCorrect(int temp){
//t.cancel()
//t.start()
temp++;
score = temp;
q++;
if(q >= 11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
value.setText(String.valueOf(score));
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
public void onDone(){
//t.start()
q++;
if(q>=11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
else{
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
}
public void onWrong(){
//t.cancel()
//t.start
q++;
if(q>=11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
else{
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
For reference;
onCheck() checks if the answer is right
onCorrect() is right
onWrong() is wrong
onDone() is when the timer runs out
The root of my issue is that I cannot put t into onDone as it's called by the MyCountDownTimer class which doesn't have access to the t called in onCreate.
Declare MyCountDownTimer t outside of onCreate() as a global variable.

How to loop a function and wait a second between every loop in google maps project in android studio?

I want to create a program that mark a place on the google map and every second from when I push the "Start" button the marker would jump a km to a random direction until I push the "Stop" button.
I want the marker to jump, wait a second, jump, wait a second and so on... Until I push the "Stop" button.
When I am using the "while" loop the program stuck even before the showing of the "Stop" button.
But if I don't use the loop it's working good. Can you help me please?
This is my code:
import androidx.annotation.DrawableRes;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.Random;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private double currLat = 32.671677;
private double currLng = 35.195678;
private Marker _marker;
private boolean _stopBWasNotPressed = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
// Setting the icon instead of the default marker.
private BitmapDescriptor bitmapDescriptorFromVector(Context context, #DrawableRes int vectorDrawableResourceId) {
Drawable background = ContextCompat.getDrawable(context, R.drawable.car_icon);
background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
background.draw(canvas);
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Hide the Stop button.
Button stopB = (Button) findViewById(R.id.stopB);
stopB.setVisibility(View.GONE);
// Hide the Reset button.
Button resetB = (Button) findViewById(R.id.resetB);
resetB.setVisibility(View.GONE);
// Add a marker in my home and move the camera.
LatLng home = new LatLng(currLat, currLng);
_marker = mMap.addMarker(new MarkerOptions().position(home).icon(bitmapDescriptorFromVector(this, R.drawable.car_icon)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(home));
// Show the Start button.
Button startB = (Button) findViewById(R.id.startB);
startB.setVisibility(View.VISIBLE);
startB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Hide the Start button.
Button startB = (Button) findViewById(R.id.startB);
startB.setVisibility(View.GONE);
// Show the Stop button.
final Button stopB = (Button) findViewById(R.id.stopB);
stopB.setVisibility(View.VISIBLE);
while (_stopBWasNotPressed) {
// Making the program wait a second until it moving the marker again.
new Handler().postDelayed(new Runnable() {
public void run() {
startMoving();
}
}, 1000); // 1 second.
}
}
});
}
// This func generates a random number to use as a direction.
public int generateRandomDirection(){
final int min = 1;
final int max = 4;
final int random = new Random().nextInt((max - min) + 1) + min;
return random;
}
// This func makes the new location and sends it to the animateMarker func.
public void startMoving(){
int directionNumber = generateRandomDirection();
final LatLng toPos;
switch(directionNumber) {
case 1:
toPos = new LatLng((currLat + 0.01), currLng); // North.
_marker.setPosition(toPos);
break;
case 2:
toPos = new LatLng((currLat - 0.01), currLng); // South.
_marker.setPosition(toPos);
break;
case 3:
toPos = new LatLng(currLat, (currLng + 0.01)); // East.
_marker.setPosition(toPos);
break;
default:
toPos = new LatLng(currLat, (currLng - 0.01)); // West.
_marker.setPosition(toPos);
break;
}
}
public void stopButtonClick(View view) {
_stopBWasNotPressed = false; // Stops the while loop.
// Hide the Stop button.
Button stopB = (Button) findViewById(R.id.stopB);
stopB.setVisibility(View.GONE);
// Show the Reset button.
final Button resetB = (Button) findViewById(R.id.resetB);
resetB.setVisibility(View.VISIBLE);
resetB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
_marker.setVisible(false);
currLat = 32.671677;
currLng = 35.195678;
onMapReady(mMap);
}
});
}
}
I searched a bit and I found that I can't use the while loop and the delay function together so I changed it to this:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
while (_stopBWasNotPressed) {
try {
Thread.sleep(1000); // Making the program wait a second until it continues.
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
startMoving();
}
});
}
}
};
Thread myThread = new Thread(runnable); // Creating a thread for the marker movement.
myThread.start();

How do I add button to another activity in android studio using java code rather than xml code

I want to add a button from 1 activity - "pop_accompaniments.xml" to another activity - "pop_cart.xml", using java code. For this I created an instance of the class "pop_cart.java" in "pop_accompaniments.java", to call the func - "cart_button_creator" which is in "pop_cart.java".
But my app just crashes as soon as I open it.
pop_accompaniments.java
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class pop_accompaniments extends AppCompatActivity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pop_accompaniments);
Button assorted_condiments = findViewById(R.id.assorted_condiments);
}
#Override
public void onClick(View v) {
setContentView(R.layout.pop_cart);
pop_cart main = new pop_cart();
int id;
String name;
Button myButton;
switch (v.getId()) {
case R.id.assorted_condiments:
myButton = new Button(this);
name = "Assorted Condiments";
id = generateButtonId();
main.cart_content_keeper(id, name, myButton);
}
}
}
pop_cart.java
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
public class pop_cart extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.pop_cart);
}
public void cart_button_creator(String name, int id, Button myButton) {
//setContentView(R.layout.pop_cart);
LinearLayout ll = findViewById(R.id.cart_items);
myButton.setText(name);
myButton.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
myButton.setId(id);
ll.addView(myButton);
}
public void cart_content_keeper(int id, String name, final Button myButton) {
int n = 0;
int[] id_arr = {};
String[] name_arr = {};
//int price = 0;
name_arr = add_item(n, name_arr, name);
id_arr = add_id(n, id_arr, id);
n = n + 1;
Button refresh = findViewById(R.id.refresh);
final int finalN = n;
final String[] finalName_arr = name_arr;
final int[] finalId_arr = id_arr;
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.refresh) {
for (int i = 0; i < finalN; i++) {
cart_button_creator(finalName_arr[i], finalId_arr[i], myButton);
}
}
}
});
}
public static String[] add_item(int n, String[] arr, String x)
{
int i;
String[] newarr = new String[n + 1];
for (i = 0; i < n; i++)
newarr[i] = arr[i];
newarr[n] = x;
return newarr;
}
public static int[] add_id(int n, int[] arr, int x)
{
int i;
int[] newarr = new int[n + 1];
for (i = 0; i < n; i++)
newarr[i] = arr[i];
newarr[n] = x;
return newarr;
}
}
Sorry for such a long code but I have tried almost all the possible ways of calling a func from an instance of another class, passing the variables in a different manner, trying to call the whole variable generator as a function and only passing the view v as an argument in pop_accompaniments.java but the app keeps in crashing either when I click on the button "ASSORTED CONDIMENTS" at the very first step or if I just start the app it crashes.
Also, the buttons are created just fine if I am creating them in the same activity that is "pop_accompaniments.xml" while calling the button_creator method from "pop_accompaniments.java".
But I want them to show in the CART activity not the ACCOMPANIMENTS activity.
I am guessing you need the button to be created when the activity pop_cart.java is in the foreground.
In that case why don't you directly execute the button code in the onCreate() of pop_cart.java?
You can pass a boolean from pop_accompaniments.java to pop_cart.java via an intent if you want something in pop_accompaniments.java to decide whether the button will be created or not!
In pop_accompaniments.java:
Intent intent = new Intent(this, pop_cart.class);
intent.putExtra("someBool", true);
In pop_cart.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
Boolean bool = getIntent().getExtras().getBoolean("someBool");
//Now you can check if the bool is true or false
if(bool){
//Execute button code here
}
}

Android Java : Error while running countdown timer

I need your help to find an error in my "test" android application.
Until I create the second function "setProgessBar" the app runs without error, but now the error occur everytime. To comment the function call out has no effect.
Here is the code:
package my.timer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Timer1 extends AppCompatActivity {
private int arrayPosition = 0;
private long timeValue = 0;
private boolean indicator = false;
private double progress;
private final String[] actions = {"Phase1" , "Phase2" , "Phase3" , "Phase4"};
private final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer1);
final Button startButton = (Button) findViewById(R.id.startButton);
final TextView text1 = (TextView) findViewById(R.id.textView3);
final TextView text2 = (TextView) findViewById(R.id.actionParameter);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text2.setText(actions[arrayPosition]);
text1.setText("" + timeValue + "");
new CountDownTimer(240000, 100) {
public void onTick(long millisUntilFinished) {
timeValue = (millisUntilFinished / 1000) % 4;
text1.setText("" + timeValue + "");
if (timeValue == 3 && indicator){
if (arrayPosition < 3){
arrayPosition++;
} else {
arrayPosition = 0;
}
indicator = false;
setProgressBar(arrayPosition);
text2.setText(actions[arrayPosition]);
}
if (timeValue == 1){
indicator = true;
}
}
public void onFinish() {
text1.setText("Geschafft :)");
}
}.start();
}
});
}
private void setProgressBar(int progressStatus) {
switch (progressStatus){
case 0:
progress = progress + 0.25;
break;
case 2:
progress = progress - 0.25;
break;
}
progressBar.setProgress((int)progress);
}
}
Many thanks in advance
Tim

How can random string look like slot machine

In my program, I have only 1 button. And first press the program will output a random string. If the user presses it again to stop, my program will slow random (delay) the same slot machine. How can I do it?
my code
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Randomsentence extends Activity {
boolean showRandom = false;
TextView txt;
int time = 30;
int random;
public String[] myString;
Button bt1;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
Medaiplayer mp = new Medaiplayer();
Mediaplayer mp2 = new Mediaplayer();
mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showRandom = !showRandom;
t = new Thread() {
public void run() {
try {
while (showRandom) {
mp.start();
mp2.reset();
mp2.prepare();
sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
mp.reset();
mp.prepare();
mp2.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
});
}
// our handler
Handler handler = new Handler() {
public void handleMessage(Message msg) {//display each item in a single line
{
Random rgenerator = new Random();
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
txt.setText(q);
}
}
};
}
Ignoring the MediaPlayer part, I think it should be this way:
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Randomsentence.R;
public class Randomsentence extends Activity {
TextView txt;
int random;
public String[] myStrings;
Button bt1;
private static final int MESSAGE_RANDOM = 1;
private static final long MIN_INTERVAL = 500;
private static final long MAX_INTERVAL = 1500;
private static final long STEP = 60;
private long mInterval = 0;
private boolean mStarted = false;
private Random mRandom = new Random();
private Handler mHandler = new Handler() {
#Override
public void handleMessage (Message msg) {
if(msg.what == MESSAGE_RANDOM) {
showRandomString();
if(mStarted) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
} else {
if(mInterval <= MAX_INTERVAL) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
mInterval += STEP;
} else {
this.removeMessages(MESSAGE_RANDOM);
Toast.makeText(Randomsentence.this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(mBt1OnClick);
myStrings = getResources().getStringArray(R.array.myArray);
}
private void showRandomString() {
final int index = mRandom.nextInt(myStrings.length - 1);
txt.setText(myStrings[index]);
}
private OnClickListener mBt1OnClick = new OnClickListener() {
#Override
public void onClick(View v) {
if(!mStarted) {
// Start
Toast.makeText(Randomsentence.this, "Started!", Toast.LENGTH_SHORT).show();
mStarted = true;
mInterval = MIN_INTERVAL;
mHandler.removeMessages(MESSAGE_RANDOM);
mHandler.sendEmptyMessage(MESSAGE_RANDOM);
} else {
// Stop
mStarted = false;
Toast.makeText(Randomsentence.this, "Stoping...", Toast.LENGTH_SHORT).show();
}
}
};
}

Categories