Change TextView value every second (Android) - android

i am creating a sample app in which i want to change a TextVeiw value every second.
TextView value should change continue every second.
to perform this task i tried this below code:
but this code is not changing text values continue, it only change on app start or screen rotate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Boolean b = true;
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "2345u8", "9654", "987650", };
Random generator = new Random();
final int random = generator.nextInt(str.length);
Thread t = new Thread() {
#Override
public void run() {
try {
while (b != false) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// update TextView here!
tv.setText(str[random]);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
}
and i also tried this code:
but this code crash application
private Timer timer = new Timer();
private TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "2345u8", "9654", "987650", };
Random generator = new Random();
final int random = generator.nextInt(str.length);
timerTask = new TimerTask() {
#Override
public void run() {
// refresh your textview
tv.setText(str[random]);
}
};
timer.schedule(timerTask, 0, 1000);
}

Try the following code snippet
final Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
long millis =(long)currentTime();
dateAndTime.setText(getDate(millis, "dd/MM/yyyy hh:mm:ss.SSS"));
h.postDelayed(this, 1000);
}
});

final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "23458", "9654", "987650", };
// //
final Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
Random generator = new Random();
final int random = generator.nextInt(str.length);
tv.setText(str[random]);
h.postDelayed(this, 1000);
}
});
// //

Related

Not updating TextView value with thread,Why?

TextView output;
int i;
Random random=new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output=findViewById(R.id.textView);
new Thread(new mythread()).start();
}
class mythread implements Runnable{
#Override
public void run() {
try {
while(true) {
i = random.nextInt(100);
output.setText(i + "");
Thread.sleep(500);
}
}catch (Exception e){}
}
}
}
it just showing one number in text view
but requirement is ,it should generate random number and keep updating textview after 500ms
Thank You!
The main problem, in your code, is that you can update UI only in the main thread and you are using a custom thread.
The second problem is that you are using Thread.sleep that is a very bad practise.
I suggest you to use Handler
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
Log.d("Handler", "Running Handler");
handler.postDelayed(this, 500);
}
}
handler.postDelayed(runnable, 0);
and here the kotlin version
var handler = Handler()
var runnable = object : Runnable {
override fun run() {
Log.d("Handler", "Running Handler");
handler.postDelayed(this, 500)
}
}
handler.postDelayed(runnable, 500)
Try this, I think it will solved your problem.
public class MainActivity extends AppCompatActivity {
private Random random;
private Handler handler;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.tv_number);
displayRandomNumber();
}
/**
* Display random number in text view
*/
private void displayRandomNumber()
{
random = new Random();
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
int value = random.nextInt();
textView.setText(String.valueOf(value));
handler.postDelayed(this,2000);
}
}, 2000);
}
}

How to keep changing the background image non stop?

I wrote code which can change the background every 3 second, but unfortunately it only change 1 time, I try using the count but it wont work, where did it went wrong?
public class MainActivity extends AppCompatActivity {
public static int count=0;
int images[] = new int[] {R.drawable.main, R.drawable.main2, R.drawable.main3, R.drawable.main4};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
public void run() {
if (count < images.length) {
RelativeLayout background = (RelativeLayout) findViewById(R.id.activity_main);
Random rand = new Random();
int index = rand.nextInt(images.length);
background.setBackgroundResource(images[index]);
count++;
}
else{
count = 0;
}
}
}, 3000);
}
};
Just call handler.postDelayed inside run() method to start it again, and modify your code like this:
public class MainActivity extends AppCompatActivity {
int images[] = new int[] {R.drawable.main, R.drawable.main2, R.drawable.main3, R.drawable.main4};
final Handler animHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout background = (RelativeLayout) findViewById(R.id.activity_main);
animHandler.post(new Runnable() {
#Override
public void run() {
Random rand = new Random();
int index = rand.nextInt(images.length);
background.setBackgroundResource(images[index]);
animHandler.postDelayed(this, 3000);
}
});
}
};
}

How to update TextView dynamically (periodically)?

I am developing a simple android activity with a scrollable TextView. I am displaying numbers from 1-100 in my TextView with a time delay. However my desired output is not what I'm getting.
Current Output: 1 replaced by 2 replaced by 3....till 100.
Desired Output:
1
2
3
4
.
.
100
Here is my Activity code:
public class MainActivity extends ActionBarActivity {
private static int i = 0;
TextView textView;
Handler handler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
textView = (TextView) findViewById(R.id.text_area);
new PrimeCalculation().execute();
handler = new Handler();
handler.post(updateView);
}
private Runnable updateView = new Runnable() {
#Override
public void run() {
if(i <= 100) {
textView.setText(Integer.toString(i));
i++;
handler.postDelayed(this, 1000);
}
}
};
}
How about this:
textView.setText(textView.getText() + "\n" + i);
Create a new String Array. Set the text view to the array.toString(); Every time that your timer runs out insert the most recent number into the array and repeat. The most recent number should be an int that increases when the timer runs out. Hope this helps!
Try this
private Handler mHandler = new Handler();
private int nCounter = 0;
View.OnClickListener mButtonStartListener = new OnClickListener() {
public void onClick(View v) {
try {
mHandler.removeCallbacks(hMyTimeTask);
// Parameters
// r The Runnable that will be executed.
// delayMillis The delay (in milliseconds) until the Runnable will be executed.
mHandler.postDelayed(hMyTimeTask, 1000); // delay 1 second
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Runnable hMyTimeTask = new Runnable() {
nCounter++;
hTextView.append("\n"+nCounter);
}
public void run() {
};
Hope this will help you
You can use following code......
public class MainActivity extends ActionBarActivity {
private static int i = 0;
TextView textView;
Handler handler;
String textViewText="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_area);
handler = new Handler();
handler.post(updateView);
}
private Runnable updateView = new Runnable() {
#Override
public void run() {
if(i <= 100) {
//
textViewText=textViewText+Integer.toString(i)+" ";
textView.setText(textViewText);
// textViewText=textViewText+textView.getText().toString();
i++;
handler.postDelayed(this, 1000);
}
}
};}
I hope it will help you....

Android Textview not Updating

everyone.
I'm trying to make a basic tycoon game for Android
and I'm trying to increment the value of text-views every 5 seconds with a timer,
But the textview doesn't update.
Here's my code so far:
public class Town extends Activity implements OnClickListener {
Timer timer;
TimerTask task;
TextView goldTV;
TextView woodTV;
TextView foodTV;
TextView stoneTV;
TextView cashTV;
int gold = 20;
int wood = 20;
int food = 20;
int stone = 20;
int cash = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_town);
goldTV = (TextView) findViewById(R.id.textView1);
woodTV = (TextView) findViewById(R.id.TextView01);
foodTV = (TextView) findViewById(R.id.TextView02);
stoneTV = (TextView) findViewById(R.id.TextView03);
cashTV = (TextView) findViewById(R.id.TextView04);
timer = new Timer();
task = new TimerTask() {
#Override
public void run() {
gold++;
goldTV.setText(gold);
try {
this.wait(2000);
}
catch (InterruptedException e){
}
}
};
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
In your run() method
#Override
public void run() {
gold++;
goldTV.setText(gold);
try {
this.wait(2000);
}
catch (InterruptedException e){
}
}
You're calling setText(int resId) instead of setText(CharSequence c);
To display the actual integer gold, convert it from int to String
String goldStr = String.valueOf(gold);
goldTV.setText(goldStr);
Your problem is that you are changing the text on something other than the UI thread. Better is to run it on the UI thread. Plus you should convert your number into a string, or else Android will think you are looking for a resource id. Put them both together, and...
task = new TimerTask() {
#Override
public void run() {
gold++;
runOnUiThread(new Runnable(){
public void run(){
goldTV.setText(""+gold);
}
});
try {
this.wait(5000);
}
catch (InterruptedException e){
}
}
};
Or even better, you could use a handler, like this:
Handler handler = new Handler();
Runnable task=new Runnable(){
public void run(){
handler.postDelayed(this,5000);
goldTV.setText(""+gold);
}
});
handler.postDelayed(task,5000);
a TimerTask should be used with a Timer object. in your code you never run the task.
edit:
try this instead:
goldTV.postDelayed(new Runnable() {
#Override
public void run() {
gold++;
goldTV.setText(gold+"");
goldTV.postDelayed(this,2000);
}
}, 2000);

How to stop a timer after certain number of times

Trying to use a Timer to do run this 4 times with intervals of 10 seconds each.
I have tried stopping it with a loop, but it keeps crashing. Have tried using the schedule() with three parameters, but I didn't know where to implement a counter variable. Any ideas?
final Handler handler = new Handler();
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "test",
Toast.LENGTH_SHORT).show();
}
});
}
};
int DELAY = 10000;
for (int i = 0; i != 2 ;i++) {
timer2.schedule(testing, DELAY);
timer2.cancel();
timer2.purge();
}
private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
private int counter = 0;
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
});
if(++counter == 4) {
timer.cancel();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer.schedule(task, DELAY, DELAY);
}
Why not use an AsyncTask and just have it Thread.sleep(10000) and the publishProgress in a while loop? Here is what it would look like:
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
int i = 0;
while(i < 4) {
Thread.sleep(10000);
//Publish because onProgressUpdate runs on the UIThread
publishProgress();
i++;
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
//This is run on the UIThread and will actually Toast... Or update a View if you need it to!
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
}.execute();
Also as a side note, for longer term repetitive tasks, consider using AlarmManager...
for(int i = 0 ;i<4 ; i++){
Runnable runnableforadd ;
Handler handlerforadd ;
handlerforadd = new Handler();
runnableforadd = new Runnable() {
#Override
public void run() {
//Your Code Here
handlerforadd.postDelayed(runnableforadd, 10000); }
};
handlerforadd.postDelayed(runnableforadd, i);
}

Categories

Resources