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

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

Related

Android: Button method works only once

I'm pretty new to Android's Java (so please don't beat me up) and I have a question to my button action. The called method is running only one time. When I click the button the second time nothing happens anymore. I do not understand why. No errors, no flaws, the method is doing what is expected. Any hints?
Thanks!
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView mainFortuneTextView;
Button mainFortuneButton;
private int counter, i, x;
//private int randomNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 1. Access the TextView defined in layout XML
// and then set its text
mainFortuneTextView = (TextView) findViewById(R.id.fortuneTextView);
// 2. Access the Button defined in layout XML
// and listen for it here by using "this"
mainFortuneButton = (Button) findViewById(R.id.fortuneButton);
mainFortuneButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// happens on button action in main view
runThread();
Random rnd = new Random();
x = rnd.nextInt(11) + 1;
}
private void runThread() {
mainFortuneButton.setEnabled(false);
new Thread() {
public void run() {
while (i++ < 10) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
mainFortuneTextView.setText("#" + i);
}
});
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// activate button again
runOnUiThread(new Runnable() {
#Override
public void run() {
mainFortuneButton.setEnabled(true);
}
});
}
}.start();
}
}
Your variable i used in your while is a field. That means that it will not reset. That's why the second time you call your thread the i value will be 10 and it will be called not again. You have to reset your i again before starting a new thread.

What is the difference between a UIHandler and a Handler

I want to show numbers from 1 to 100 in sequel order in the TextView and to wait 1 second after printing each number. I also want to implement it using Android services.
I don't know the difference between UIHandler and Handler. When I google about this issue, all I am getting is the difference between handler and a thread.
Please help me out of this,
Thanks in advance
private static final int SHOW_MESSAGE = 1;
private static final int m_cdelay = 1000;
private UIHandler m_cUIHandler;
public int m_cI= 0;
TextView m_cTextShow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_cTextShow = (TextView) findViewById(R.id.textview1);
for(m_cI=1; m_cI <= 100; m_cI++){
//m_cUIHandler = new UIHandler();
//m_cUIHandler.sendEmptyMessageDelayed(SHOW_MESSAGE, 1000);
showMessage(m_cI);
}
}
private void showMessage(int m_cI2) {
for(m_cI=1; m_cI <= 100; m_cI++){
m_cTextShow.setText(""+m_cI);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(m_cdelay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}).start();
}
}
#Override
protected void onResume() {
super.onResume();
startService(new Intent(this, NumberService.class));
}
public final class UIHandler extends Handler {
#Override
public void handleMessage(Message pObjMessage) {
switch(pObjMessage.what) {
case SHOW_MESSAGE:
m_cTextShow.setText(""+m_cI);
break;
}
}
}
You can actually rewrite your code like that to make it probably work.
Pls test it and respond.
public void showMessage(int number){
runOnUiThread(new Runnable(){
public void run() {
//Write your number onto the screen
}
});
}
protected void onCreate(Bundle savedInstanceState) {
//Blablabla...
for(m_cI=1; m_cI <= 100; m_cI++){
//m_cUIHandler = new UIHandler();
//m_cUIHandler.sendEmptyMessageDelayed(SHOW_MESSAGE, 1000);
showMessage(m_cI);
Thread.sleep(1000);
}
}

Android update TextView inside dialog in runOnUiThread

I have been spending couple hours to try to update the textview inside the dialog, but failed.
When the option is clicked, there are new dialog is shown, and inside the dialog, there are textviews and button, when I click the button, the textview will be update.
Here is the code related to the button onClick listener:
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
final String currentNum = String.valueOf(i + 1);
Thread t = new Thread() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(currentNum); //it is fine
currentNum.setText(currentNum); //it is the problem, the setText only work when the for loop is finished.
}
});
}
};
t.start();
}
}
});
Please let me know if you need more information. Thanks a lot in advance!
//it is a optionmenu
case R.id.action_refresh:
final TextView currentNum;
final ImageButton start;
String currentNum = Integer.toString(songList.size());
final Dialog lyricsAnalysis = new Dialog(this,R.style.cust_dialog);
lyricsAnalysis.requestWindowFeature(Window.FEATURE_NO_TITLE);
lyricsAnalysis.setContentView(R.layout.analysis);
lyricsAnalysis.setCancelable(true); //back button to cancel
lyricsAnalysis.setCanceledOnTouchOutside(true);
start = (ImageButton) lyricsAnalysis.findViewById(R.id.start);
//first value
currentNum.setText(String.valueOf(currentNum));
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTextView(lyricsAnalysis,i);
}
}
});
lyricsAnalysis.show();
lyricsAnalysis.getWindow().setLayout(600, 1000);
break;
}
return super.onOptionsItemSelected(item); }
public void updateTextView(Dialog dialog, int i) {
final TextView currentNum = (TextView) dialog.findViewById(R.id.currentNum);
currentNum.setText(Stri`enter code here`ng.valueOf(i));
//return;
}
Try this method. This may helps you. It's work for me.(But I am not use this in dialog)
public void updateTextView(String toThis) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(toThis);
//return;
}
try like this
int elapsedtime=0;
boolean isTimerRunning=false;
Timer timerr;
inside onCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//declare your textview here;
timerr=new Timer();
startTimer();
}
/*
* timer for displaying message bubble
*/
protected static void startTimer() {
isTimerRunning = true;
elapsedtime = 0;
// recordingseek.setProgress(0);
timerr.scheduleAtFixedRate(new TimerTask() {
public void run() {
// increase every sec
elapsedtime++;
mmHandler.obtainMessage(1).sendToTarget();
System.out.println("recording time" + elapsedtime);
if(elapsedtime==50)
timerr.cancel();
}
}, 1000, 2000);
};
public static Handler mmHandler = new Handler() {
public void handleMessage(Message msg) {
textview.setText(elapsedtime);
}
};
}
};

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

Android Thread Exception?

i got thread exception in android , what i intend to do is, while clicking a button i started a thread going to dynamically invoke the handler ,handler update the text view with integer value , while reaching integer 10, i going to stop the thread and have to show an alert ,but it will cause an error, what i possibly doing is shown below
public class sample extends Activity implements Runnable{
public Camcorder()
{
try{
counterThread = new Thread(this);
}catch(Exception ee)
{
}
}
public void run()
{
try{
while(counterFlag)
{
System.out.println("The time starts at : "+counter);
Thread.sleep(1000);
calculate(counter);
counter++;
}
}catch(Exception ee){
System.out.println("Err in ee : "+ee);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c=this.getApplicationContext();
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.main);
authalert3 = new AlertDialog.Builder(this);
authalert3.setTitle("Save Video");
authalert3.setMessage("Do you want to save this Video?");
authalert3.setPositiveButton("Yes", null);
Button test = (Button) findViewById(R.id.widget33);
test.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter = 0;
counterFlag = true;
counterThread.start();
}
});
public void calculate(int counter2) {
// TODO Auto-generated method stub
if(counter2<60){
if(counter2<10)
{
smin="0"+counter2;
}
else{
smin=""+counter2;
}
}
else{
hours++;
counter=0;
smin="00";
if(hours<10){
shours="0"+hours;
}
else{
shours=""+hours;
}
}
handler.sendEmptyMessage(0);
}
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
String tes=shours+":"+smin;
time.setText(tes);
test();
};
};
public void test(){
duration=1;
if(duration==hours){
counterFlag = false;
videoPath=camcorderView.stopRecording();
authalert3.create().show();
counterThread.stop();
}
}
the error is thrown at counterThread.stop();
Anyone suggest me , how to solve this error.
You don't stop threads by calling counterThread.stop. This method is deprecated. In your case, by setting counterFlag = false; your thread should be stopping itself.
You will also be getting an exception if you click twice on your button: you cannot call start on a Thread that has already been started. You must create a new instance of that Thread and start that new instance (stop the old instance before if necessary).
You can see that SO answer for some sample code on how to create/stop threads: Android thread in service issue. I suggest that you also read some tutorial on Java Threads (this is not specific to Android).
Additionally I think that you don't need a thread at all, you are doing nothing complicated and thus you could simply use the handler to do all the work:
private static final int MSG_REFRESH_UI = 0;
private static final int MSG_UPDATE_COUNTER = 1;
private int counter = 0;
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if (msg.what==MSG_REFRESH_UI) {
String tes=shours+":"+smin;
time.setText(tes);
test();
} else if (msg.what==MSG_UPDATE_COUNTER) {
counter++;
if (counter<10) {
calculate(counter);
handler.sendEmptyMessageDelayed(MSG_UPDATE_COUNTER, 1000);
handler.sendEmptyMessage(MSG_REFRESH_UI);
}
}
};
};
public void onResume() {
handler.sendEmptyMessage(MSG_UPDATE_COUNTER);
}
public void calculate(int counter2) {
if (counter2<10) {
smin = "0"+counter2;
} else if (counter2<60) {
smin = ""+counter2;
} else{
hours++;
counter=0;
smin="00";
if(hours<10){
shours="0"+hours;
} else {
shours=""+hours;
}
}
}
This will stop the thread at 10
while(counterFlag)
{
System.out.println("The time starts at : "+counter);
Thread.sleep(1000);
calculate(counter);
counter++;
if(counter == 10) counterFlag = false;
}

Categories

Resources