ProgressDialog does not work even using thread - android

I am new in Android development. I am trying to show a ProgressDialog. I see lots of tutorial that say for showing dialog must use thread. As you can see snippet code is using thread.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
refreshFromFeed();
} catch (InterruptedException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_main);
}
private void refreshFromFeed() throws InterruptedException {
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis()/1000));
}
};
th.start();
dialog.dismiss();
}
protected void onRefresh(View view) throws InterruptedException {
refreshFromFeed();
}
The log shows it took 5 second, however, I cannot see any dialog on my screen and I can do anything on the screen. Even I use on a physical device. I've used debugging mode. There is no exception.
onRefresh is an event by onClick that declared on it's xml.

I've made a little bit changes of your code read it carefully.
private void refreshFromFeed() throws InterruptedException {
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
dialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo",String.valueOf(System.currentTimeMillis()/1000));
}
};
th.start();
}

private void refreshFromFeed() throws InterruptedException {
final ProgressDialog dialog = ProgressDialog.show(getActivity(),"Loading","Wake up after some sleep");
Thread th = new Thread() {
public void run() {
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis() / 1000));
try {
Thread.sleep(5000);
dialog.dismiss(); // dismiss your dialog here
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis() / 1000));
}
};
th.start();
}

You still run the ProgressDialog in your UI thread.
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
New thread created after this line, not before this line!

You are dismissing your dialog just right after showing it.
Maybe you want to move your "dialog.dismiss();" to inside the thread. Remember that you need to dismiss the dialog on UI Thread, otherwise it will crash your app:
private void refreshFromFeed() throws InterruptedException {
final ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis()/1000));
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
});
}
};
th.start();
}
I see lots of tutorial that say for showing dialog must use thread.
You don't explicitly need a thread to show a ProgressDialog, this is just an example to dismiss it after 5000 ms

Related

Unable to update seekbar with Handler

I am trying to update seekbar with respect to the progress of the song in MediaPlayer.
I am using Thread to do that task.
First i have used Thred inside thread and trying to update the UI but it crashing the app and says that only original thread can attached to the view.
Then i have try to update it with handler inside the thread runnable. which works fine but it is not updating the seekbar. When i have do log then i come to know loop is not going inside my handler. I dont know where is the problem. Please help me to updating SeekBar.
Code:
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
if ((musicPath != mIRemoteService.getPath())) {
System.out.println("..... MUSIC CHANGE.....");
setOrUpdateData();
updateFragmentLayout();
}
// Displaying Current Duration time/Progress
new Handler().post(new Runnable() {
#Override
public void run() {
try {
songCurrentDurationLabel.setText(""+ Utilities.milliSecondsToTimer(mIRemoteService.position()));
songProgressBar.setProgress((int)mIRemoteService.position());
System.out.println("Runnnnn.........");
//songProgressBar.invalidate();
} catch (RemoteException e) {
e.printStackTrace();
System.out.println("Runnnnn......... EXCEPTION....");
}
}
});
System.out.println("Runnnnn.........MAIN....");
if (!(mIRemoteService.isPlayerRunning())) {
btnPlay.setImageDrawable(getResources().getDrawable(R.drawable.play_now_playing));
mHandler.removeCallbacks(mUpdateTimeTask);
System.out.println("Runnnnn.........MAIN....IF");
}else{
System.out.println("Runnnnn.........MAIN....ELSE");
mHandler.post(mUpdateTimeTask);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
you can use either a handler or a thread, with thread you should make sure to post the modifications on the UI thread:
private class UpdateSeekBar extends Thread
{
#Override
public void run()
{
super.run();
while (null != mp && mp.isPlaying() && this.isAlive())
{
//final int min = (mp.getCurrentPosition() / 1000) / 60;
//final int sec = (mp.getCurrentPosition() / 1000) % 60;
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
try
{
songCurrentDurationLabel.setText("" + Utilities.milliSecondsToTimer(mIRemoteService.position()));
songProgressBar.setProgress((int) mIRemoteService.position());
System.out.println("Runnnnn.........");
// songProgressBar.invalidate();
}
catch (RemoteException e)
{
e.printStackTrace();
System.out.println("Runnnnn......... EXCEPTION....");
}
}
});
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}

Run a thread in android after one thread completes its execution

I want run run a thread after one thread completes its execution.
Here I am using progress bar, after progress bar completes the method do1() should execute but when I am run the application the application force close.
here is my code..
public void onenc(View view) {
progressBar = new ProgressDialog(view.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("Ecoding Text ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();
}
I have also tried AsyncTask but both run simultaneously.
Please help me I am a newbie in android.
Thanks in advance.
Update:
After AsyncTask
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
return null;
//Do Stuff
}
public void progressUpdate(Integer progress) {
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}
#Override
protected void onPostExecute(Boolean result) {
//Call your next task
Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();
}
}
Now not even a single thread is executing the application force closes
After Another Update
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
return null;
//Do Stuff
}
public void progressUpdate(Integer progress) {
}
#Override
protected void onPostExecute(Boolean result) {
do1();
//Call your next task
/* Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();*/
}
}
Now the function do1() executes before progress bar completes.
Finally Solved it....Here is the answer.
Hope it will help others
class MyFirstTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.show();
}
#Override
protected String doInBackground(String... params) {
int i=0;
while(fileSize<100)
{
fileSize=fileSize+1;
publishProgress(""+(int)(fileSize));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
publishProgress(""+(int)(fileSize));
return null;
}
public void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
progressBar.dismiss();
do1();
}
}
Don't use Thread() at all. Use AsyncTask as it makes life easier and implement the onPostExecute() method to call the next AsyncTask
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
//Do Stuff that takes ages (background thread)
for(int i=0;i<100;i++){
doStuff();
Thread.sleep(1000L); //sleep because I'm just tired
publishProgress(i);
Thread.sleep(2000L); //sleep some more
}
}
#Override
public void progressUpdate(Integer progress) {
//Update progress bar (ui thread)
progressBar.setProgress(progress);
}
#Override
protected void onPostExecute(Boolean result) {
//Call your next task (ui thread)
new MyNextTask().execute();
}
Start your first task
new MyFirstTask().execute();
You can simply use join() method.
Thread first = new Thread();
Thread secThread =new Thread();
first.start();
first.join();
secThread.start();
but do not do this on main thread.

http connection from MainActivity

I have a little problem. In my android app, i have to connect to an online server.
The connection should be called with an click-button an as an backround service. I know that I must put the network connection in a thread, but i don't know how it works.
I put the call in a own method wich creates a thread but at compilation i got a error message.
here is my code:
Button:
ImageView refresher = (ImageView)findViewById(R.id.imgRefresh);
refresher.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
httpThread();
}
});
thread method:
private void httpThread(){
final Handler h = new Handler();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
h.post(new Runnable(){
#Override
public void run() {
try{
vomServerholenUndSpeichern();
FileInputStream inStream = null;
try {
inStream = openFileInput("test.xml");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
leseDatei(inStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
createListView("test.xml");
System.out.println(inStream);
drawListView();
} catch (Exception e){
e.printStackTrace();
}
}
});
}
});
thread.start();
}
Can someone help me to fix the problem?
You have to use AsyncTask, is not difficult.
AsyncTask are necessary to avoid block UI during your connection operation, the method doInbackGround of AsyncTask is used for this kind of operations (it runs in a thread different from the UI), while int the onPostExecute (this run on the UI) of the task you will manage your httpResult;)

Show Toast from a thread started in a broadcast receiver

I have a BroadcastReceiver.
There I create a new Thread.
How can I show a toast in that thread?
Thanks
Use below code for perform UI operation from non-UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Try This code
public void start_insert() {
pDialog.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
// Do Something in Background
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
handler22.sendMessage(handler22.obtainMessage(what));
}
}.start();
}
private Handler handler22 = new Handler() {
#Override
public void handleMessage(Message msg) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "SuccessFull",
10).show();
}
};
Activity_Name.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Use this code to update UI thread or execute any UI related operation.

Android Loading Dialog Freez

I have this code in android. But when the Thread begging the loading in freezing. How can I prevent this freezing happens. Here is the code related the issue:
private void reload(final String criteria) {
try {
myProgressDialog = ProgressDialog.show(myfiles.this,
"Please wait...", "Loading Your Photos... Please Wait",
false);
new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// Fetch the fact
try {
/* here my code */
} catch (Exception e) {
myProgressDialog.dismiss();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Dismiss the Dialog
myProgressDialog.dismiss();
}
}.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It would be great if someone can check
By using runOnUiThread you are doing your intensive load task on the UI thread which will freeze the UI. You want to run your task in a background thread, and then on task completion update the ui.
Thread task = new Thread(new Runnable() {
void run() {
//load some data.
// notify UI thread using Handler
}
});
task.start();

Categories

Resources