All i want to do is display a text for 1000 milliseconds and get the next thing.. dialogs are slow to pop up so i used a textview..but its not working.. the code snippet is given..
What am I doing wrong?
Thread sleep_for_sometime = new Thread() {
public void run() {
try {
correct.setVisibility(TextView.VISIBLE);
sleep(1000);
correct.setVisibility(TextView.INVISIBLE);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
get_question(questionset[i]);
}
}
};
//sleep_for_sometime.setDaemon(false);
sleep_for_sometime.start();
You should change visibility in UI thread. Read painless threading
AsyncTask is great, but overused in some ways I think. Just use post/postDelayed. You're not really doing background work, you just want to delay some UI-thread work. Definitely read Nikita's link, but I would do something like:
correct.setVisibility(View.VISIBLE);
correct.postDelayed(new Runnable() {
correct.setVisibility(View.INVISIBLE);
get_question(questionset[i]);
}, 1000);
Expanding Nikita's Answer , you could do something like this
private class SleepTask extends AsyncTask<Void,Integer,Void> {
#Override
protected Void doInBackground(Void... params) {
try {
publishProgress(0);
sleep(1000);
publishProgress(1);
}catch(Exception e){
//null
}
}
#Override
protected void onProgressUpdate(Integer... i){
if(i[0]==0){
correct.setVisibility(TextView.VISIBLE);
}else{
correct.setVisibility(TextView.INVISIBLE);
}
}
#Override
protected void onPostExecute(Void res) {
get_question(questionset[i]);
}
#Override
protected void onPreExecute() {
//do something before execution
}
}
to start the thread , do this
new SleepTask().execute();
Related
I am working on an android app in which i want to hide my image view after some interval. i am using this code but it is not hiding. can anybody tell me how i can hide it ???
showtrue1.setBackgroundResource(R.drawable.ticktrue);
showtrue1.setVisibility(View.VISIBLE);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
showtrue1.setVisibility(View.GONE);
Try CountDownTimer:
new CountDownTimer(1000, 100) {
public void onTick(long millisUntilFinished) {
// implement whatever you want for every tick
}
public void onFinish() {
showtrue1.setVisibility(View.GONE);
}
}.start();
You can use async Task also to solve your problem . In its backgound function make a thread sleep for particular second and in the post method make trhe visibility gone for your image viiew.
Call the execute method in your oncreate
new MyAsyncTask().execute();
and make an inner class as defined below:
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
// show your progress dialog
showtrue1.setBackgroundResource(R.drawable.ticktrue);
showtrue1.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... voids){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void params)
{
showtrue1.setVisibility(View.GONE);
}
}
Create a separate thread that sleeps for 1 seconds then call runOnUiThread to hide the view.
Thread thread = new Thread() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do some stuff
showtrue1.setVisibility(View.GONE);
}
});
}
};
i got this progress dialog code:
new Thread() {
#Override
public void run() {
try {
sleep(1000);
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
progressDialog.dismiss();
}
}.start();
and i got text that will apear after some httprequest actions:
editText2.setText(stringEr);
how do i sync between them? i want that the text will be hidden untill the progress will finish
tnx!
You have to use Handlers to update your UI. A little modification here,
new Thread()
{
#Override
public void run()
{
try
{
//Instead of sleep, call your http request method here.
handler.sendEmptyMessage(0);
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
progressDialog.dismiss();
}
}.start();
And create a handler in onCreate(),
Handler handler=new Handler()
{
public void handleMEssage(Message msg)
{
if(msg.what==0)
editText2.setText(stringEr);
}
};
i think you should use AsyncTask for that and you can hide in OnPreExecute Method i mean when asynctask in started and show in OnPostExecute method. after complete the progress.
Android skip the painful Threading concept, Use Asyntask class.
http://developer.android.com/reference/android/os/AsyncTask.html
private class UIOperation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
//show dialog
}
#Override
protected String doInBackground(String... params) {
//collect data
return null;
}
#Override
protected void onPostExecute(String result) {
//dismiss dialog
//update UI
}
}
here is my code,
public ProgressDialog loadingdialog;
public void ShowManager() {
//do something
}
public void startScan() {
loadingdialog = ProgressDialog.show(WifiManagementActivity.this,
"","Scanning Please Wait",true);
new Thread() {
public void run() {
try {
sleep(4000);
ShowManager();
} catch(Exception e) {
Log.e("threadmessage",e.getMessage());
}
loadingdialog.dismiss();
}
}.start();
}
startScan();
A basic progressdialog show function, but on the line where ShowManager() is called, getting error ,
01-07 23:11:36.081: ERROR/threadmessage(576): Only the original thread
that created a view hierarchy can touch its views.
EDIT:
ShowManager() is a function that change the view elements. shortly something like,
public void ShowManager()
{
TextView mainText = (TextView) findViewById(R.id.wifiText);
mainText.setText("editted");
}
I found the answer. I don't like to answer my own question but maybe this will help someone else. We cannot update most UI objects while in a separate thread. We must create a handler and update the view inside it.
public ProgressDialog loadingdialog;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
loadingdialog.dismiss();
ShowManager();
}
};
public void ShowManager()
{
TextView mainText = (TextView) findViewById(R.id.wifiText);
mainText.setText("editted");
}
public void startScan() {
loadingdialog = ProgressDialog.show(WifiManagementActivity.this,
"","Scanning Please Wait",true);
new Thread() {
public void run() {
try {
sleep(4000);
handler.sendEmptyMessage(0);
} catch(Exception e) {
Log.e("threadmessage",e.getMessage());
}
}
}.start();
}
startScan();
use this instead of just loadingdialog.dismiss()
runOnUiThread(new Runnable() {
#Override
public void run() {
loadingdialog.dismiss();
}
});
This is because you are trying to dismiss the dialog from the thread, while it was created in the main UI thread. Try moving the ProgressDialog.show statement inside the Thread. I would prefer using AsyncTask as they are much simpler to manage as in this example
something like this it's 'ok':
public void startScan() {
new Thread() {
public void run() {
loadingdialog = ProgressDialog.show(WifiManagementActivity.this,
"","Scanning Please Wait",true);
try {
sleep(4000);
ShowManager();
} catch(Exception e) {
Log.e("threadmessage",e.getMessage());
}
loadingdialog.dismiss();
}
}.start();
}
note the position of ProgressDialog.show(...), here the dialog.dismiss() is called in the thread that created the dialog.
but the cleanest way to achive that it's by using AsynTask
I've developed an application that takes content from the internet and shows it accordingly on the device's screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to load and display the content . I would like to put all the code that fetches the content and displays it in a background thread and while the program is doing those functions , I would like to display a progress dialog. Could you help me do this ? I would like especially to learn how to put the code in a background thread.
MY CODE
public class Activity1 extends Activity
{
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(Activity1.this, "",
"Loading...");
}
#Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
/*
* This is run on a background thread, so we can sleep here
* or do whatever we want without blocking UI thread. A more
* advanced use would download chunks of fixed size and call
* publishProgress();
*/
Thread.sleep(params[0]);
// HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
/*
* The task succeeded
*/
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
/*
* Update here your view objects with content from download. It
* is save to dismiss dialogs, update views, etc., since we are
* working on UI thread.
*/
AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Download succeeded");
}
else
{
b.setMessage("Download failed");
}
b.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dlg, int arg1)
{
dlg.dismiss();
}
});
b.create().show();
}
}.execute(2000);
new Thread()
{
#Override
public void run()
{
// dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
}
}
Check ASyncTask, its specifically created for such tasks.
public Runnable NameOfRunnable = new Runnable()
{
#Override
public void run()
{
while (true)
{
// TODO add code to refresh in background
try
{
Thread.sleep(1000);// sleeps 1 second
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
now start this with
Thread name = new Thread(NameOfRunnable);
name.start();
How to work with Background Thread.
Note: Do not work with UI with this background thread.
AsyncTask.execute(new Runnable() {
#Override
public void run() {
//TODO background code
}
});
Hope this would help you.
I want show dialog after finish Thread.
In thread I am changing TextView's Value like as 0 to 100...
When TextView Value is reach 100 then i want to show dialog..
What i do for it.
Thanks in advance...
Code Snippet:
final Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
synchronized (this)
{
try
{
for(int i=0 ; i<speed; i++)
{
final int value=i+1;
wait(3000/speed);
Test.this.runOnUiThread(new Runnable() {#Override public void run()
{
accText.setText(String.valueOf(value));
}});
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread.start();
this is asyntask code snippet...
class setTextBackgroundTask extends AsyncTask<String , Integer, Void>
{
#Override
protected void onPreExecute()
{
}
#Override
protected Void doInBackground(String... params)
{
Thread th = new Thread();
int value;
for(int i=0 ; i<speed; i++)
{
value=i+1;
publishProgress(value);
try {
th.sleep(3000/speed);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
accText.setText(String.valueOf(values[0]));
System.out.println("Value=="+values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result)
{
showShareDialog();
}
}
This document explains how you can create dialogs.
Please note that you will have to do any dialog creation code on the UI thread.
You already have code that runs something on the UI thread, just do that outside the loop,but with the dialog creation code inside.
You should use AsyncTask: subclass AsyncTask, override doInBackground() to execute your time consuming action on another thread, and then override onPostExecute() to show your dialog.
Note that you cannot change UI elements from a non-UI (background) thread. AsyncTask takes care of that for you: it calls doInBackground() on a new thread and then calls onPostExecute() on the UI thread as soon as the background task is complete.