I built a small progress bar. When you press a button, the progress bar starts counting, from 1 to 100.
I changed the button text to "Running" when it runs. But when I tried to change the text to "Again?" after it reached 100 (after the while loop finished), the application has suddenly stopped - every time.
Any help? Thank you in advance.
package com.myfirstapplication.owner.myfirstapplication;
import android.os.Handler;
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.TextClock;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ProgressBar pg;
Button bt;
int progressStatus = 0;
TextView tv;
Handler handler = new Handler();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pg = (ProgressBar) findViewById(R.id.progressBar);
bt = (Button) findViewById(R.id.btn);
tv = (TextView) findViewById(R.id.textID);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bt.setText("Running.");
progressStatus = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
progressStatus++;
handler.post(new Runnable() {
#Override
public void run() {
pg.setProgress(progressStatus);
tv.setText("Progress: " + progressStatus + "/" + pg.getMax());
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
bt.setText("Again?");
}
}).start();
}
});
}
}
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bt.setText("Running.");
progressStatus = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
progressStatus++;
handler.post(new Runnable() {
#Override
public void run() {
pg.setProgress(progressStatus);
tv.setText("Progress: " + progressStatus + "/" + pg.getMax());
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
handler.post(new Runnable() {
#Override
public void run() {
bt.setText("Again?");
}
});
}
}).start();
}
});
Related
So I have this main activity:
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private volatile boolean stopTask = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
public boolean getStopTask() {
return stopTask;
}
public void startMyTask(View view) {
stopTask = false;
TextView textView = findViewById(R.id.text_view);
MyTask myTask = new MyTask(10, textView);
new Thread(myTask).start();
}
public void stopMyTask(View view) {
stopTask = true;
}
}
I was told that I could access getStopTask() from MyTask by getting an instance of MainActivity and accessing that function directly.
I tried that, but I get an error: "Can't create handler inside thread Thread[Thread-6,5,main] that has not called Looper.prepare()".
Here's MyTask:
import android.widget.TextView;
public class MyTask implements Runnable {
int seconds;
TextView textView;
MyTask(int seconds, TextView textView) {
this.seconds = seconds;
this.textView = textView;
}
#Override
public void run() {
MainActivity mainActivity = new MainActivity();
for (int x = 0; x < seconds; x++) {
boolean stopTask = mainActivity.getStopTask();
if (stopTask)
break;
textView.setText(String.format("x: %s", x));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The error happens right after the app hits:
MainActivity mainActivity = new MainActivity();
How can I get the value of stopTask from MyTask?
I would turn boolean stopTask to static and use it instead of getStopTask() this way:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static boolean stopTask = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
/*
public boolean getStopTask() {
return stopTask;
}*/
public void startMyTask(View view) {
stopTask = false;
TextView textView = findViewById(R.id.text_view);
MyTask myTask = new MyTask(10, textView);
new Thread(myTask).start();
}
public void stopMyTask(View view) {
stopTask = true;
}
}
MyTask.java:
public class MyTask implements Runnable {
int seconds;
TextView textView;
MyTask(int seconds, TextView textView) {
this.seconds = seconds;
this.textView = textView;
}
#Override
public void run() {
//MainActivity mainActivity = new MainActivity();
for (int x = 0; x < seconds; x++) {
boolean stopTask = MainActivity.stopTask;
if (stopTask)
break;
textView.setText(String.format("x: %s", x));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I have problem with Runnable. It don't want to works, and i don't know what is the problem, because it is works in my other app... Can somebody help me?
Just example, there are "healt" with deafult value=5, for the test i made a button, when i click button, healt value -1... and i want start Runnable when health<5... and add +1 to health.... for the test i setted the Runnable 1 secunds
Here is the code:
MainActivity.java
package com.mygame.test;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import static com.mygame.test.variables.coin;
import static com.mygame.test.variables.health;
public class Main2Activity extends AppCompatActivity {
public static final String PREFS_NAME_MAIN = "mainpref";
TextView coinText, healthText, textView;
Button button3;
private final Context app = this;
private final Handler update = new Handler();
private final Runnable updateHealth = new Runnable()
{
public void run()
{
if (variables.run)
{
healthText.setText(""+health);
update.postDelayed(updateHealth, 500);
}
else if (!variables.run) update.removeCallbacksAndMessages(null);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
coinText = findViewById(R.id.coinText);
healthText = findViewById(R.id.healthText);
healthText.setText(String.valueOf(health));
button3 = findViewById(R.id.button3);
textView = findViewById(R.id.textView);
Button closeButton = findViewById(R.id.closeButton);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, ExitActivity.class));
}
});
Button coinsplusButton = findViewById(R.id.coinsplusButton);
coinsplusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, StoreActivity.class));
}
});
Button level1Button = findViewById(R.id.level1Button);
level1Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, Level1Activity.class));
}
});
}
public void buttontest(View button3)
{
if (health > 0) {
health = health-1;
healthText.setText(""+health);
}
variables.run = true;
Intent activeClick = new Intent(this, ClickService.class);
this.startService(activeClick);
update.post(updateHealth);
save();
}
#Override
protected void onStart()
{
super.onStart();
load();
textupgrade();
if (!variables.run)
{
variables.run = true;
Intent activeClick = new Intent(this, ClickService.class);
this.startService(activeClick);
}
}
protected void onResume()
{
super.onResume();
load();
textupgrade();
update.post(updateHealth);
}
private void load()
{
SharedPreferences varReader = app.getSharedPreferences(PREFS_NAME_MAIN, MODE_PRIVATE);
variables.run = varReader.getBoolean("run", false);
coin = varReader.getInt("coin", 0);
health = varReader.getInt("health", 5);
}
private void save()
{
SharedPreferences.Editor varReader = app.getSharedPreferences(PREFS_NAME_MAIN, 0).edit();
varReader.putBoolean("run", variables.run);
varReader.putInt("coin", coin);
varReader.putInt("health", health);
varReader.apply();
}
private void textupgrade(){
coinText.setText(""+coin);
healthText.setText(""+health);
}
}
ClickService.java
package com.mygame.test;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
public class ClickService extends IntentService
{
private final Handler handler = new Handler();
private final Runnable addHealth = new Runnable()
{
public void run()
{
variables.health++;
if (!variables.run) handler.removeCallbacksAndMessages(null);
else if (variables.run) handler.postDelayed(addHealth, 1000);
}
};
public ClickService()
{
super("ClickService");
}
#Override
protected void onHandleIntent(Intent activeClick)
{
handler.postDelayed(addHealth, 500);
}
}
variables.java
package com.mygame.test;
public class variables {
static int coin;
static int health;
static boolean run;
}
Oh, i fixed it :D ClickService was not registered in AndroidManifest
<service
android:name=".ClickService"
android:exported="false" />
**Down here I am trying to build a music app in android studio,my app is working fine displaying all my SD card songs and play too ,all button works but when I click on next button it works normally but don't know why app sometimes gets stopped working and shows runtime exception ->>please open the image of run log of the application.
package com.example.ramandeepsingh.tunes;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.jar.Manifest;
public class PlayerActivity extends AppCompatActivity{
static MediaPlayer mp;//assigning memory loc once or else multiple songs will play at once
int position;
SeekBar sb;
ArrayList<File> mySongs;
Thread updateSeekBar;
Button pause,forward,reverse,next,previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
pause = (Button)findViewById(R.id.pause);
forward = (Button)findViewById(R.id.forward);
previous = (Button)findViewById(R.id.previous);
next = (Button)findViewById(R.id.next);
reverse = (Button)findViewById(R.id.reverse);
sb=(SeekBar)findViewById(R.id.seekBar);
updateSeekBar=new Thread(){
#Override
public void run(){
int totalDuration = mp.getDuration();
int currentPosition = 0;
// sb.setMax(totalDuration);
while(currentPosition < totalDuration){
try{
sleep(500);
currentPosition=mp.getCurrentPosition();
}
catch (InterruptedException e){
e.printStackTrace();
System.out.println(e);
}
sb.setProgress(currentPosition);
}
}
};
if(mp != null){
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songs");
position = b.getInt("pos",0);
Uri u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
if(mp.isPlaying()){
pause.setText(">");
mp.pause();
}
else {
pause.setText("||");
mp.start();
}
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
mp.seekTo(mp.getCurrentPosition()+5000);
}
});
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
mp.seekTo(mp.getCurrentPosition()-5000);
}
});
next.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.reset();
position=((position+1)%mySongs.size());
Uri u = Uri.parse(mySongs.get( position).toString());
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.release();
position=((position-1)<0)?(mySongs.size()-1):(position-1);
Uri u = Uri.parse(mySongs.get( position).toString());//%mysongs so that it do not go to invalid position
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
}
});
}}
I have radio app which streams online radio. But it don't work on background i.e when i press home button phone automatically shut it down. how do i make it run on background.
package com.radioawaz.simerpreetjassal.radioawaz;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import java.io.IOException;
public class MainActivity extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
Log.e("ready!","ready");
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://streaming.shoutcast.com/Radioawazca?lang=en-ca");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
All above is my main Activity. please look and give suggestion.Thanks in advance.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
My problem:
I actually want to set the visibility of my ImageView on random basis. I mean each Image View will be Visible randomly after few milliseconds but my my app unexpectedly crashes all the time. Though, I'm new to android development but good at Java J2SE. Please tell me what I'm doing is it a blunder or a mistake by chance? please! thanks in advance!
package com.example.app;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button b;
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1=new ImageView(this);
I1=(ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2=new ImageView(this);
I2=(ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3=new ImageView(this);
I3=(ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4=new ImageView(this);
I4=(ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T=(TextView)findViewById(R.id.time);
s=(TextView)findViewById(R.id.score);
Thread t=new Thread(new MyThread());
t.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyThread implements Runnable{
Random randomGenerator = new Random();
int n;
public void run(){
while(true){
n=randomGenerator.nextInt(8);
if(n==1){
I1.setVisibility(View.VISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
}
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.getStackTrace();
}
}
}
}
}
THE EDITED CODE:
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
Random randomGenerator = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1=new ImageView(this);
I1=(ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2=new ImageView(this);
I2=(ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3=new ImageView(this);
I3=(ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4=new ImageView(this);
I4=(ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T=(TextView)findViewById(R.id.time);
s=(TextView)findViewById(R.id.score);
runOnUiThread(new Runnable() //run on ui thread
{
int n;
public void run(){
while(true){
n=randomGenerator.nextInt(4)+1;
if(n==1){
I1.setVisibility(View.VISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
You must be getting an exception as above. You need to update ui on the UI thread. You are updating UI in the thread. Hence the exception and crash.
Inside your thread use runOnUiThread to update UI
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
while(true){
n=randomGenerator.nextInt(8);
if(n==1){
I1.setVisibility(View.VISIBLE);
}
....
}
}
});
Also remove this I1=new ImageView(this); since you are initializing as I1=(ImageView) findViewById(R.id.imag1);
Edit:
I would recommend using a Handler for this purpose
int n;
Handler m_handler;
Runnable m_handlerTask ;
Random r;
Declare the above as class variables;
Inside the activity onCrate() use a handler as below
r= new Random();
m_handler= new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
n=r.nextInt(4)+1;
if(n==1){
I1.setVisibility(View.VISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
}
m_handler.postDelayed(m_handlerTask, 50);
// 50 milli seconds. set this to desired number
}
};
m_handlerTask.run();
And remember to stop the handler when not required
m_handler.removeCallbacks(m_handlerTask);
I think you want full code. You can use timer. see the following code.
public class MainActivity extends Activity {
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
int n;
Timer t;
TimerTask task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1 = (ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2 = (ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3 = (ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4 = (ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T = (TextView) findViewById(R.id.time);
s = (TextView) findViewById(R.id.score);
startTimer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void startTimer() {
//Random randomGenerator = new Random();
//n=randomGenerator.nextInt(8);
final Random randomGenerator = new Random();
t = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//n++;
n=randomGenerator.nextInt(8);
if (n == 1) {
I1.setVisibility(View.VISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 2) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.VISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 3) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.VISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 4) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.VISIBLE);
}
}
});
}
};
t.scheduleAtFixedRate(task, 0, 1000);
}
}
This will work perfectly. I hope this will help you.
It is perfect ! 100%
package com.example.abc;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
public Button B;
public Button B1;
public TextView S;
int count=0;
Random randomGenerator = new Random();
int n;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
B=new Button(this);
B=(Button)findViewById(R.id.button1);
B.setVisibility(View.INVISIBLE);
B1=new Button(this);
B1=(Button)findViewById(R.id.button2);
B1.setVisibility(View.INVISIBLE);
S=(TextView)findViewById(R.id.score);
B.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
count+=1;
S.setText(Integer.toString(count));
}
});
B.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
count+=1;
S.setText(Integer.toString(count));
}
});
runThread();
}
private void runThread() {
new Thread() {
public void run() {
while ( i++ < 1200) {
if(i==1200){
startActivity(new Intent(Test.this,Game.class));
break;
}
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
n = randomGenerator.nextInt(4)+1;
if(n==2){
B.setVisibility(View.VISIBLE);
B1.setVisibility(View.INVISIBLE);
}
if(n==4){
B.setVisibility(View.INVISIBLE);
B1.setVisibility(View.VISIBLE);
}
}
});
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}