TextView Update Content Every Second Via Sleep Thread - android

in this app the Content of the TextView should change/update every second with a sleep thread.
The whole process starts when the button is clicked.
Firstable here is the normal code without the threads:
public class MainActivity extends ActionBarActivity {
Button btn;
TextView tw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
tw = (TextView) findViewById(R.id.tw);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText("1"); //This is the TextView Content, it should update every second with a sleep thread
tw.setText("2");
tw.setText("3");
}
});
}
}
This is the code added ( not working ) sleep threads:
public class MainActivity extends ActionBarActivity {
Button btn;
TextView tw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
tw = (TextView) findViewById(R.id.tw);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText("1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tw.setText("2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tw.setText("3");
}
});
}
}
Thank´s

The problem is that you are block the main UI(sleep) thread thus giving you unexpected result.
You need to use handler for this if you want to update this each second
sample:
public class MainActivity extends ActionBarActivity {
Button btn;
TextView tw;
int incre = 1;
Handler handler;
Runnable run;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
tw = (TextView) findViewById(R.id.tw);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText(incre++ + "");
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
tw.setText(incre++ + ""); //set the textview text HERE every 1 second
if(incre != 3) //checks if it is not already 3 second
handler.postDelayed(run, 1000); //run the method again
else
incre -= 2;
}
};
handler.postDelayed(run, 1000); //will call the runnable every 1 second
}
});
}
}

Related

Android - simple Thread loop doesn't work

I want a thread loop that changes String each time. (e.g. d -> dd -> ddd -> dddd...) I expected it to update the view as well as the Thread is excuted , but the screen stops at the first run() excution (which is "dd"). What is wrong? Thanks!
package com.example.name.app;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
thread t1 = new thread();
t1.start();
}
});
}
private class thread extends Thread {
TextView textView = (TextView) findViewById(R.id.tv);
#Override
public synchronized void run() {
String text = "d";
while (true) {
try {
text += "d";
textView.setText(text);
sleep(5000);
} catch (Exception e) {
return;
}
}
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv);
final Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
thread t1 = new thread();
t1.start();
}
});
}
private class thread extends Thread {
String text = "d";
#Override
public synchronized void run() {
while (true) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(text);
}
});
sleep(5000);
text += "d";
} catch (Exception e) {
return;
}
}
}
}
}
activity_main.xml
<?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="digitdemo.com.myapplication.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Count"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Output:
Hope this helps you.
All the ui elements are handled on main thread. Hence to update any ui element you must do it from the main thread (UI Thread). you can use runOnUiThread to switch to UI thread:
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
thread t1 = new thread();
t1.start();
}
});
}
private class thread extends Thread {
#Override
public synchronized void run() {
String text = "d";
while (true) {
try {
text += "d";
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(text);
}
});
sleep(5000);
} catch (Exception e) {
return;
}
}
}
}
Try this..it will give same output as you want.
public class TestActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
textView = (TextView) findViewById(R.id.tv);
final Button button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
thread t1 = new thread();
t1.start();
}
});
}
private class thread extends Thread {
String text = "d";
#Override
public synchronized void run() {
while (true) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(text);
}
});
sleep(5000);
text += "d";
} catch (Exception e) {
return;
}
}
}
}
Instead of extending the thread class for simple task of incrementing and updating UI use handler.Handler runs in the same main thread with different execution environment.
create a simple handler and update main thread if you want.
TextView textView = (TextView) findViewById(R.id.tv);
String text = "d";
Runnable runnable=null;
Handler newHandler=null;
private void runTask() {
newHandler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
try {
//update UI
text += "d";
textView.setText(text);
newHandler.post(runnable);
} catch (Exception e) {
e.printStackTrace();
}
}
};
newHandler.post(runnable);
}
}
and to stop the handler use
newHandler.removeCallbacks(runnable);

Android code about timer

I have change code to below and my purpose is to set a button
when I click the timer run,how to change the code below? thanks
new code below
I have change code to below and my purpose is to set a button
when I click the timer run,how to change the code below? thanks
new code below
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Handler aHandler;
TextView aTextView;
Button aButton;
EditText aEditText;
Handler aHandler01;
TextView aTextView01;
Button aButton01;
EditText aEditText01;
Boolean checker=false;
int count = 11;
int count01 = 11;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
aEditText = (EditText)findViewById(R.id.editText01);
aTextView = (TextView)findViewById(R.id.TextView01);
aEditText01 = (EditText)findViewById(R.id.editText02);
aTextView01 = (TextView)findViewById(R.id.TextView02);
aButton=(Button)findViewById(R.id.button01);
aButton01=(Button)findViewById(R.id.button02);
//第一個計時器
aButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v){ if(!aEditText.getText().toString().equalsIgnoreCase(""))
{count=Integer.parseInt(aEditText.getText().toString());}
aHandler = new Handler();
if(checker==false){
aHandler.post(runnable);
checker=true;
}
}
});
//第二個計時器
aButton01.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (!aEditText01.getText().toString().equalsIgnoreCase("")) {
count01 = Integer.parseInt(aEditText01.getText().toString());
}
aHandler01 = new Handler();
aHandler01.post(runnable01);
}
});
}
//第一個計時器
final Runnable runnable = new Runnable() {
public void run() { // TODO Auto-generated method stub
if (count> 0) {
aTextView.setText(Integer.toString(count-1));
count--;
aHandler.postDelayed(runnable, 1000);
}else{
aTextView.setText("boom");
}
}
};
//第二個計時器
final Runnable runnable01 = new Runnable() {
public void run() { // TODO Auto-generated method stub
if (count01> 0) {
aTextView01.setText(Integer.toString(count01-1));
count01--;
aHandler01.postDelayed(runnable01, 1000);
}else{
aTextView01.setText("boom");
}
}
};
#Override
protected void onPause() { // TODO Auto-generated method stub
super.onPause();
if (aHandler != null) {
aHandler.removeCallbacks(runnable);
}
}
}
try this
private Handler handler = new Handler();
Boolean checker=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
aEditText = (EditText)findViewById(R.id.editText01);
aTextView = (TextView)findViewById(R.id.TextView01);
aButton=(Button)findViewById(R.id.button01);
aButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v){ if(!aEditText.getText().toString().equalsIgnoreCase(""))
{count=Integer.parseInt(aEditText.getText().toString());}
if(!checker){
checker=true;
handler.post(runnable);//to start timer
}
}
});
}
final Runnable runnable = new Runnable() {
public void run() {
// TODO Auto-generated method stub
if(checker)
{
checker=false;
return;
}
if (count> 0) {
aTextView.setText(""+Integer.toString(count-1));
count--;
aHandler.postDelayed(runnable, 1000);
}else{
aTextView.setText("boom");
}
}
};
as you are assigning the value to 'count' variable in OnCreate from editText when editText is empty, it is returning null string which then you are parsing for int value which returns NumberFormatException
try to do it as follows
if (!aEditText.getText().toString().equalsIgnoreCase(""))
{
count = Integer.parseInt(aEditText.getText().toString());
}
OR you can assign a value to 'count' from editText on any button's click or using TextChangedListener(TextWatcher) to monitor and get text from edittext at run time.

Implementing traffic signal in Android

I'm trying to implement a traffic signal which will change color form red to green then to yellow. For this I used a button and I'm changing the background of the button to respected color. I'm using CountDownTimer for this purpose. Here is my code:
public class MainActivity extends Activity {
Button button1 = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setBackgroundColor(Color.RED);
while(true){
change(Color.GREEN);
change(Color.BLUE);
change(Color.RED);
}
}
void change(final int color)
{
CountDownTimer ctd = new CountDownTimer(3000, 3000)
{
#Override
public void onTick(long arg0) {}
#Override
public void onFinish() {
button1.setBackgroundColor(color);
}
};
ctd.start();
}
}
But the above code doesn't seems to work, the color of the button is not at all changing. What's the problem in this code?
This worked for me:
public class TestActivity extends Activity {
Button button1 = null;
long timeout = Long.MAX_VALUE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setBackgroundColor(Color.RED);
change();
}
void change() {
final int[] colors = {Color.GREEN, Color.BLUE, Color.RED};
CountDownTimer ctd = new CountDownTimer(timeout, 3000) {
int current = 0;
#Override
public void onTick(long arg0) {
Log.d("TEST", "Current color index: " + current);
button1.setBackgroundColor(colors[current++]);
if (current == 3)
current = 0;
}
#Override
public void onFinish() {
}
};
ctd.start();
}
}

Showing duration time using stopwatch in android?

I need to toast the stopwatch's value
ie.,time taken between start and stop
If i click the stop button it should toast that time duration.
How to do this?
Here i have tried some code
chrono_meter.java
public class Chrono_meter extends Activity {
Chronometer chr;
Button btn_stop_travel;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chronometer_layout);
chr = (Chronometer)findViewById(R.id.chronometer1);
chr.start();
btn_stop_travel = (Button)findViewById(R.id.btn_stop_inspection);
btn_stop_travel.setOnClickListener(mStopListener);
}
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
chr.stop();
}
};
}
Try this
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
chr.stop();
Toast.makeText(Chrono_meter.this, chr.getText(), Toast.LENGTH_LONG).show() ;
}
};

How to save state when activity it destroyed with this

public class Talk extends Activity {
private ProgressDialog progDialog;
int typeBar;
TextView text1;
EditText edit;
Button respond;
private String name;
private String textAtView;
private String savedName;
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.dorothydialog);
text1 = (TextView)findViewById(R.id.dialog);
edit = (EditText)findViewById(R.id.repsond);
respond = (Button)findViewById(R.id.button01);
respond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text1.setText("Welcome! Enter your name!");
respond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = edit.getText().toString();
text1.setText("Cool! your name is "+name);
}
});
}
});
}
}
Okay so i want to figure out how i would save the state of this activity. this is just a small snippet from my code to show you guys an example. So i want to save the state so when the activity is destroyed the user will come back where they left off.
Second thing, I would like to show a quick 5 second Progress dialog spinner between each button click.
For the second thing
This should work:
public class TestActivity extends Activity implements Runnable, OnClickListener {
private TextView tv;
private ProgressDialog pd;
private Button btn;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.tv);
btn = (Button)findViewById(R.id.btn);
tv.setText("initial text");
btn.setOnClickListener(this);
}
public void onClick(View v) {
pd = ProgressDialog.show(TestActivity.this, "Please wait...", "Details here", true, false);
Thread thread = new Thread(TestActivity.this);
thread.start();
}
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
tv.setText("text after 5 sec passed");
}
};
}

Categories

Resources