I have the following three classes:
When I try to show a progressDialog when the WorkingThread is running, the ProgressDialog only shows up after the WorkingThread is done. What am I doing wrong?
I am not interested in using an AsyncTask!
-StartActivity:
public class StartActivity extends Activity implements OnClickListener
{
public ProgressDialog pgd;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgv = (ImageView)findViewById(R.id.imageView1);
tv = (TextView)findViewById(R.id.textview);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
}
public void onClick(View v)
{
pgd = ProgressDialog.show(StartActivity.this, "", "Loading picture"); // Start ProgressDialog before starting activity
Intent ActivityIntent = new Intent(this, FirstActivity.class);
startActivityForResult(ActivityIntent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK)
{
pgd.dismiss(); //Stop ProgressDialog when FirstActivity is "done"
}
}
}
-
-FirstActivity:
public class FirstActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
WorkingThread wt = new WorkingThread();
wt.start();
try
{
wt.join();
Intent ActivityIntent = getIntent();
setResult(RESULT_OK, ActivityIntent);
finish();
}
catch (Exception e)
{
}
}
}
-WorkingThread:
public class WorkingThread extends Thread
{
@Override
public void run()
{
super.run();
try
{
Thread.sleep(5000);
}
catch (Exception e)
{
}
}
}
Use an AsyncTask. Here's an example:
I just show your edit that you don't want to use an AsyncTask. I will not delete this answer (unless you want me to) since it is another way of doing what you wanted to do.
The problem is
ProgressDialog
always need current Activity context for display.But in your caseProgressDialog
is little unfortunateThe reason is as soon as you fire
ProgressDialog
the next couple of lines take out Context from Current activity and starts Next Activity i.eFirstActivity
.So yourprogressDialog
gets no chance to present itself on the Screen.here is your problem. The UI thread is waiting the Working Thread to finish becaouse of the
join()
.