How to update TextView dynamically (periodically)? - android

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....

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);
}
}

Update TextView every second in Android [duplicate]

This question already has answers here:
Update TextView Every Second
(11 answers)
Closed 4 years ago.
i want to update my textview every second.
on button click i am calling one method,
loopMethod(milli); //suppose milli= 50000 i.e 50 sec.
so my loopMethod(int m) is as follows:
public void loopMethod(int m){
timer=(TextView) findViewById(R.id.timerText);
if(m>=1000){
try {
timer.setText(""+m);//timer is a textview
System.out.println(m);
m=m-1000;
Thread.sleep(1000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
loopMethod(m);
}
}
so what i am expecting is, my timer textview should print the value of m every second.
but i am getting only console output i.e system.out.println(m)...
printing value on console working fine...
but its not updating my textview at all
You can use following code:
Runnable updater;
void updateTime(final String timeString) {
timer=(TextView) findViewById(R.id.timerText);
final Handler timerHandler = new Handler();
updater = new Runnable() {
#Override
public void run() {
timer.setText(timeString);
timerHandler.postDelayed(updater,1000);
}
};
timerHandler.post(updater);
}
In this line:
timerHandler.post(updater);
time will set for the first time. i.e, updater will execute. After first execution it will be posted after every 1 second time interval. It will update your TextView every one second.
You need to remove it when the activity destroys, else it will leak memory.
#Override
protected void onDestroy() {
super.onDestroy();
timerHandler.removeCallbacks(updater);
}
Hope it will help you.
You should use RxJava library to do so:
Subscription s =
Observable.interval(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v -> {
// update your ui here
}, e -> {
});
// call when you no longer need an update:
if (s != null && !s.isUnsubscribed()){
s.unsubscribe();
s = null;
}
That's it. Do NOT use .postDelay(), Timer because it is error prone.
You might want to consider using the Chronometer class: https://developer.android.com/reference/android/widget/Chronometer.html
just use timer.start(); on the button click
Using handler can be used like this
TextView timer;
int m =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer=(TextView) findViewById(R.id.timerText);
Handler handler = new UpdateHandler();
m = 10;
handler.sendEmptyMessageDelayed(1, 1000);//start after 1000
}
class UpdateHandler extends Handler{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
timer=(TextView) findViewById(R.id.timerText);
timer.setText("Text :" +m);
m = m-1000;
sendEmptyMessageDelayed(1, 1000); //seng again after 1000
//add some stop logic
break;
default:
break;
}
}
}
Try this code Initialize textview in
onCreate
timer=(TextView) findViewById(R.id.timerText);
public void loopMethod(int m){
if(m>=1000){
try {
System.out.println(m);
m=m-1000;
final ScheduledThreadPoolExecutor c = new ScheduledThreadPoolExecutor(1);
c.schedule(new Runnable() {
#Override
public void run() {
timer.setText(""+m);//timer is a textview
c.shutdownNow();
}
}, 1, TimeUnit.SECONDS);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
loopMethod(m);
}
}
I've added some logics to stop the Timer. If you have any qyestion, ask freely
private int m = 0;
private int milliseconds = 1000;
public void loopMethod(int m){
timer=(TextView) findViewById(R.id.timerText);
Timer t = new Timer();
//schedule a timer
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
timer.setText(String.valueOf(m));//avoid using composite string in the setText
System.out.println(String.valueOf(m));
//remove from the total the amount of millisecond passed
m=m-milliseconds;
if(m <= milliseconds) { //or <= what you want
//stop the timer repeatitions
t.cancel();
}
}
});
}
//"0" is the amount of time to wait for the timer to start
//"milliseconds" is the duration
},0,milliseconds);
}
Add
For a correct analysis you should add more infos in your question. the problem of not-updating textview might be caused by the setText("" + int) because it's always better to avoid the setText with an int. I edited it with String.valueOf, but if it's not working you should add the xml and the onCreate
Hope this helped
I have created timer for seconds.
public class TimerForSeconds extends AppCompatActivity {
private int seconds = 60;
private TextView tvTimer;
private Handler mHandler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
if(seconds == 0){
mHandler.removeCallbacks(runnable);
}
else{
tvTimer.setText(seconds + "");
seconds--;
mHandler.postDelayed(runnable,1000);
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
tvTimer = (TextView) findViewById(R.id.tv_timer);
mHandler = new Handler();
mHandler.postDelayed(runnable,1000);
}
}
//and also removCallback onDestroy too.

Android dev't using thread with textview: why this is crashing?

My goal is when the user tap start button, letters "o" "n" "o" "m" and so forth will appear at the center of the screen. "o" will appear first then after a few seconds will be replaced by "n" then "o" and so forth.
note: for brevity, i just make the guessword = onomatopoeia, first. In reality, guessword will changes every time i tap the start bottom.
this is the code:
private String guessword = "onomatopoeia";
private TextView showchar;
private int n = guessword.length();
private char letArray[]= guessword.toCharArray();;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
addStartListener();
}
public void addStartListener(){
Button start = (Button) findViewById(R.id.start);
showchar = (TextView) findViewById (R.id.charView);
start.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread thread = new Thread()
{
#Override
public void run() {
try {
for(int i = 0 ; i < n ; i++) {
sleep(1000);
showchar.setText(letArray[i]);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
}
thanks for the help
I decided to implement runonuithread but still it crashes:
this is the updated version:
private String guessword = "onomatopoeia";
private TextView showchar;
private int n = guessword.length();
private char letArray[]= guessword.toCharArray();
private Handler handler;
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
handler = new Handler();
showchar = (TextView) findViewById (R.id.charView);
}
public void startGame(View view){
new Thread() {
public void run() {
while(i++ < n) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
showchar.setText(letArray[i]);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
use this code for setting the text in your textview
runOnUiThread(new Runnable() {
#Override
public void run() {
showchar.setText(letArray[i]);
}
});
You are updating ui from a thread which is not possible.
showchar.setText(letArray[i]);
UI must be updated ui thread.
All you are doing is repeatedly setting value to TextView you can use Handler with a delay for this purpose.
You could use runOnUiThread also but i don't see the need for a thread for what you are doing.
Use a Handler. You can find an example #
Android Thread for a timer

Updating a textview that shows current time every second or minute

Hi Iam trying to update 3 textviews every second. I have written this piece of code. the thread starts normally but the textviews they do not get updated. I am passing a function inside the text parameters of the texts views that gets the current system time (using Calendar) in digits but then converts it to letters. example: for 3.45 THREE FORTYFIVE. any help would be appreciated. thanks
public class MainActivity extends Activity {
TextView currentv;
GetDate gd;
TextView currentmin;
TextView currentmins;
private Handler mHandler;
private boolean Running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentv = (TextView) this.findViewById(R.id.tvtimehour);
currentmin = (TextView) findViewById(R.id.tvtimemin);
currentmins = (TextView) findViewById(R.id.tvtimesecond);
gd = new GetDate();
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
mHandler = new Handler();
Runnable runb = new Runnable(){
#Override
public void run(){
while(Running == true){
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
mHandler.post(new Runnable(){
#Override
public void run(){
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
}
});
}
}
};
new Thread(runb).start();
}
Try this,
private MyTimerTask mytask;
private Timer timer;
mytask = new MyTimerTask();
timer = new Timer();
timer.schedule(mytask, 0,60000);
Timer class:
class MyTimerTask extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// Do your stuff here it will work
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
}
});
}
}
Use Timer for this, I think because Thread can not update your UI.

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);

Categories

Resources