Android update TextView inside dialog in runOnUiThread - android

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

Related

How to perform click continuously while something is enable

I'm beginner... I need to run some code after 10 seconds continuously while my button is enable.
and when I clicked on it and it turned to disable-state, timer get stop.
I use below code but it run just once when I click on timerbutton every time again...
I think I have to use threed and I think I used it too! But I did not get to my goal.
private View.OnClickListener ontimerclicked = new View.OnClickListener() {
#Override
public void onClick(View view) {
Handler myHandler = new Handler();
myHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (endistimer==false) {
endistimer=true;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#E91E63"));
varbtnimgnext.performClick();
intdelay=10000;
}
else
{
endistimer=false;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#dddddd"));
intdelay=0;
}
}
}, intdelay);
}
};
I finaly solved it with below code.I put it for anothers:
private View.OnClickListener ontimerclicked = new View.OnClickListener() {
#Override
public void onClick(View view) {
mHandler = new Handler();
if (endistimer==false) {
endistimer=true;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#E91E63"));
}
else
{
endistimer=false;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#dddddd"));
intdelay=5000;
cntsec=0;
varbtnplusfive.setText(arrsec[0] +" Sec");
}
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (endistimer) {
try {
Thread.sleep(intdelay);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// your codes
// you can set continue_or_stop to false, for stop
}
});
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(slideword.this,e.toString(),Toast.LENGTH_SHORT);
}
}
}
}).start();
}
};

Download View and show popup message

How to show message in showDialog();
I want when freshDownloadView is finished show showDialog.
My code is as follows:
public class MainActivity extends Activity implements View.OnClickListener {
private FreshDownloadView freshDownloadView;
private Button btDownloaded;
private TextView btReset;
private TextView btDownloadError;
private final int FLAG_SHOW_OK = 10;
private final int FLAG_SHOW_ERROR = 11;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int progress = (int) msg.obj;
freshDownloadView.upDateProgress(progress);
switch (msg.what) {
case FLAG_SHOW_OK:
break;
case FLAG_SHOW_ERROR:
freshDownloadView.showDownloadError();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
freshDownloadView = (FreshDownloadView) findViewById(R.id.pitt);
btDownloaded = (Button) findViewById(R.id.bt_downloaded);
btReset = (Button) findViewById(R.id.bt_reset);
btDownloadError = (Button) findViewById(R.id.bt_download_error);
btDownloaded.setOnClickListener(this);
btReset.setOnClickListener(this);
btDownloadError.setOnClickListener(this);
}
this is button freshDownload
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_downloaded:
if (freshDownloadView.using()) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = Message.obtain();
message.obj = i;
handler.sendMessage(message);
showDialog();
}
}
}).start();
break;
case R.id.bt_reset:
freshDownloadView.reset();
break;
case R.id.bt_download_error:
if (freshDownloadView.using()) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 30; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = Message.obtain();
if (i == 30) {
message.what = FLAG_SHOW_ERROR;
}
message.obj = i;
handler.sendMessage(message);
}
}
}).start();
break;
}
}
public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setMessage(R.string.download_app)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}
protected void onPause() {
// unregisterReceiver(receiver);
super.onPause();
}
protected void onResume() {
// registerReceiver(receiver, new IntentFilter(
// WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
}
I suggest you use AsyncTask for this. You can initiate the download in the doInBackground method and show the alert dialog (as needed) in the onPostExecute method. This will also free you from using Thread.sleep(100) which isn't a good practice on Android.
However, if you still prefer to use the FreshDownloadView please update your question with the code for FreshDownloadView and we can suggest something.

How to implement two countdown timers alternatively in Android

I have implemented one counter and onFinish() of first counter,I started second counter but the first counter not able to finish.Text "Bye Guyz" remain for some time so how to finish the text.
Please help me.
Thanks in advance.!!!
Code :-
counter= new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
if (count == 0) {
tv.setText("First counter");
tv2.setVisibility(View.VISIBLE);
tv2.setText("Hello Guyz");
}
}
public void onFinish() {
if(!flag) {
tv2.setText("Bye Guyz");
count = 0;
try {
counter.cancel();
}catch (Exception e){}
}
else if(flag) {
counter1 = new CountDownTimer(9000, 1000) {
public void onTick(long millisUntilFinished) {
flag = false;
tv.setText("Second counter");
tv2.setVisibility(View.VISIBLE);
tv2.setText("Hello Girls");
count = 0;
}
public void onFinish() {
tv2.setVisibility(View.VISIBLE);
tv2.setText("Bye Girls");
count = 0;
}
}.start();
Did you "debug" the code to be sure the code is arriving to counter1 = new CountDownTimer(9000, 1000)?
Are you sure when the first counter arrives to onFinish() the flag variable is true?
Why do you call counter.cancel() in onFinish() when obviously the counter is already over?
public void onFinish() {
if(!flag) {
tv2.setText("Bye Guyz");
count = 0;
try {
counter.cancel();
}catch (Exception e){}
}
If you say your tv2 displays "Bye Guyz" it means that your flag is set to false, so the "else if" part is not being executed. onFinish() is only executed once, so you need to make sure the flag is set for true to start the second counter.
Also you shouldn't cancel your counter in onFinish() because it's already finished.
Here is my alternative is as follows
Create the custom Counterextending Thread
class Counter extends Thread {
private long timeOne, timeTwo;
private OnCounterFinishedListener mCounterFinishedListener;
private Thread t;
Activity activity = null;
Counter(Context context){
t = new Thread(this);
activity = (Activity)context;
}
#Override
public void run() {
try {
sleep(timeOne);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mCounterFinishedListener.firstCounterFinished();
}
});
sleep(timeTwo);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mCounterFinishedListener.secondCounterFinished();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void setTimes(long timeOne, long timeTwo){
this.timeOne = timeOne;
this.timeTwo = timeTwo;
}
public void start(OnCounterFinishedListener listener){
mCounterFinishedListener = listener;
t.start();
}
interface OnCounterFinishedListener{
void firstCounterFinished();
void secondCounterFinished();
}
}
Then inside your main thread you can start this counter as
final Counter counter = new Counter(this);
counter.setTimes(5000, 5000);
counter.start(new Counter.OnCounterFinishedListener() {
#Override
public void firstCounterFinished() {
// Update your first TextView
}
#Override
public void secondCounterFinished() {
// Update your second TextView
}
});

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

Categories

Resources