ProgressDialog doesn't show with I using intent in Android - android

Everything is working fine, and the second Activity is running but My progress Dialog doesn't appear when I using Intent.
Is there an error in the code? , I can't find stack.
an idea ???
Please help me , Thanks!
public class StartActivity extends AppCompatActivity {
private Intent mIntent;
private final int totalProgressTime = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
public void onClick(View view) {
new DownloadTask().execute();
mIntent = new Intent(this, MainActivity.class);
startActivity(mIntent);
}
private class DownloadTask extends AsyncTask<String,Void,Object>{
ProgressDialog mIndicator = new ProgressDialog(StartActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
mIndicator.setMessage("Wait..");
mIndicator.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mIndicator.setProgress(0);
mIndicator.setMax(totalProgressTime );
mIndicator.show();
new Thread(new Runnable() {
#Override
public void run(){
int counter = 0;
while(counter < totalProgressTime ){
try {
Thread.sleep(300);
counter ++;
mIndicator.setProgress(counter);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mIndicator.dismiss();
}
}).start();
}
#Override
protected Object doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
mIndicator.dismiss();
}
}
}

Let's not talk about how wrong is to use AsyncTask as you used it here. I suppose you have some bigger picture, and this is just some test snippet.
So with
new DownloadTask().execute();
you started AsyncTask.
And just after that you started new activity:
mIntent = new Intent(this,MainActivity.class);
startActivity(mIntent);
So, AsyncTask continue to work in separate thread, but StartActivity is no longer active (probably not even visible), because MainActivity is in foreground now.
So, you want to see ProgressBar in StartActivity, but you are in MainActivity.
Try to wait AsyncTask to finish, than start MainActivity.
#Override
protected void onPostExecute(Object o) {
mIndicator.dismiss();
mIntent = new Intent(this, MainActivity.class);
startActivity(mIntent);
}

Related

overridePendingTransition not working on android 2.3.5

This code of mine is not working... I have checked all the links on this site and also tried animation listener but still its not working.
public class SplashScreenPage extends Activity implements Runnable{
Thread splash;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen_page_layout);
splash = new Thread(this);
splash.start();
}
#SuppressWarnings("static-access")
#Override
public void run() {
try {
splash.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(SplashScreenPage.this,LoginPage.class);
startActivity(intent);
finish();
SplashScreenPage.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
}
#Override
protected void onPause() {
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
super.onPause();
}
}
The problem is with your device's default settings. Go to settings > display > animation > allow "all animations". This will allow overridePendingTransition to work properly.
The problem I see is that you're using your animation in a different Thread of the main thread. That main thread is also known as the UI Thread. So, you need to get back to that UI Thread. This should work (I use overridePendingTransition(0, 0) to remove any animation, you can experiment with others:
public class SplashActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_splash);
presentLogo();
}
/** Called to present the Splash image for an amount of time */
private void presentLogo() {
final SplashActivity splashActivity = this;
new Thread() {
public void run() {
synchronized (splashActivity) {
try {
sleep(Constants.SPLASH_PRESENTATION_DURATION);
} catch (InterruptedException e) {
} finally {
runOnUiThread(new Runnable() {
public void run() {
finish();
overridePendingTransition(0, 0);
// After splash, go to the new activity
Intent intent = new Intent();
intent.setClass(splashActivity, LoginActivity.class);
startActivity(intent);
}
});
}
}
}
}.start();
}
}
Try this:
Intent intent = new Intent(SplashScreenPage.this,LoginPage.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);

Splash Image for android

I made a splash image to show at the start of my activity..
The image show perfectly.But the problem is when i call this
public class SplashImageActivity extends Activity {
protected boolean active = true;
protected int splashTime = 5000; // time to display the splash screen in ms
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while(active && (waited < splashTime)) {
sleep(100);
if(active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
startActivity(new Intent(SplashImageActivity.this,Myapps.class));
finish();
//startActivity(new Intent("com.splash.com.MyApps"));
//startActivity( new Intent(getApplicationContext(), Myapps.class));
}
}
};
splashTread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
active = false;
}
return true;
}
}
go for next activity the stop() does not work. And it does not go to this activity. I add all activity in manifest. The stop() shows in code like this
what's the problem?
No need to call stop() and call finish() after starting activity
finally
{
startActivity(new Intent(currentclass.this,nextActivity.class);
finish();
}
I use thread to show the Splash screen, and it works for me:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mSplashThread = new Thread(){
#Override
public void run(){
try {
synchronized(this){
wait(4000);
}
}catch(InterruptedException ex){
}
finish();
Intent i=new Intent(getApplicationContext(),NextActivity.class);
startActivity(i);
interrupt();
}
};
mSplashThread.start();
}
Please try below code..
public class Splashscreen extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread t2 = new Thread() {
public void run() {
try {
sleep(2000);
startActivity( new Intent(getApplicationContext(), Exercise.class));
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
};
t2.start();
}
}
No need to call stop() just call finish() after starting activity
finally {
startActivity(new Intent(currentclass.this,nextActivity.class);
finish();
}
You can also use handler an postdelayed() to make a splash screen like below
public class SplashScreenActivity extends Activity{
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
final Runnable runnable = new Runnable() {
#Override
public void run() {
Intent intent=new Intent(SplashScreenActivity.this, nextActivity.class);
startActivity(intent);
finish();
}
};
handler = new Handler();
handler.postDelayed(runnable, 5000);
}
}
You will show your splash screen for 5 seconds and then move to next Activity
first thing it is not onStop of Activity so looks you are calling stop function of thread which is Deprecated that's why you are getting the strike line so use other way to stop the thread of use better way to implement the splash ........
as looks you try some thing like this link

Run progress bar while switching Activity

im stuck in a situation where i am switching from activity 1 to activity 2.
i am using Thread.sleep(5000) to start another activity after 5 seconds
But the progress bar which i want to run for five seconds also sleeps with the first activity
Pleaze help me as to when i click next Button on first activity a progress bar shoud run for five sec
and then activity should be loaded
My Code is:
public class Activity1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.B);
final ProgressBar p=(ProgressBar) findViewById(R.id.pr);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
p.setVisibility(4);
Thread t=new Thread();
try{
t.sleep(5000);
}
catch(Exception e){}
Intent myIntent = new Intent(view.getContext(), activity2.class);
startActivityForResult(myIntent, 0);
}
});
}}
Change your OnClickListener for this. This will not block your main thread, as you are doing (that explains why your application freezes for 5 seconds):
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new AsyncTask<Integer, Long, Boolean>()
{
ProgressDialog pd;
#Override
protected Boolean doInBackground(Integer... params)
{
pd = new ProgressDialog(Activity1.this);
pd.setTitle("Loading Activity");
pd.setMessage("Please Wait ...");
pd.setMax(params[0]);
pd.setIndeterminate(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
publishProgress(0L);
long start = System.currentTimeMillis();
long waitTime = params[0] * 1000;
try
{
while (System.currentTimeMillis() - start < waitTime)
{
Thread.sleep(500);
publishProgress(System.currentTimeMillis() - start);
}
}
catch (Exception e)
{
return false;
}
return true;
}
#Override
protected void onProgressUpdate(Long... values)
{
if (values[0] == 0)
{
pd.show();
}
else
{
pd.setProgress((int) (values[0] / 1000));
}
}
#Override
protected void onPostExecute(Boolean result)
{
pd.dismiss();
Intent myIntent = new Intent(view.getContext(), activity2.class);
startActivityForResult(myIntent, 0);
}
}.execute(5);
});
Don't use Thread.sleep() - it is the root to all evil. Instead, use a Handler and its postDelayed( Runnable, time )-method like below:
public class Activity1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.B);
final ProgressBar p=(ProgressBar) findViewById(R.id.pr);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
p.setVisibility(4);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent myIntent = new Intent(view.getContext(), activity2.class);
startActivityForResult(myIntent, 0);
}
}, 5000);
}
});
}
You better use an AsyncTask for this purpose.Using threads like that in your activity is not proper and can lead to some fails.Check this docs about AsyncTask.
http://developer.android.com/resources/articles/painless-threading.html
First of all in the Above code, you need to start the Thread using this.
t.start();
you can also try below code,
new Thread ( new Runnable()
{
public void run()
{
// Place your Intent Code here
}
}.start();

startActivityForResult to an activity that only displays a progressdialog

I'm trying to make an activity that is asked for some result. This result is normally returned instantly (in the onCreate), however, sometimes it is nesesary to wait for some internet-content to download which causes the "loader"-activity to show. What I want is that the loader-activity don't display anything more than a progressdialog (and that you can still se the old activity calling the loader-activity in the background) and I'm wondering wheather or not this is possible.
The code I'm using as of now is:
//ListComicsActivity.java
public class ListComicsActivity extends Activity
{
private static final int REQUEST_COMICS = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_comics);
Button button = (Button)findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intents.ACTION_GET_COMICS);
startActivityForResult(intent, REQUEST_COMICS);
}
});
}
/** Called when an activity called by using startActivityForResult finishes. */
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Toast toast = Toast.makeText(this, "The activity finnished", Toast.LENGTH_SHORT);
toast.show();
}
}
//LoaderActivity.java (answers to Intents.ACTION_GET_COMICS action-filter)
public class LoaderActivity extends Activity
{
private Intent result = null;
private ProgressDialog pg = null;
private Runnable returner = new Runnable()
{
public void run()
{
if(pg != null)
pg.dismiss();
LoaderActivity.this.setResult(Activity.RESULT_OK, result);
LoaderActivity.this.finish();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String action = getIntent().getAction();
if(action.equals(Intents.ACTION_GET_COMICS))
{
Runnable loader = new Runnable()
{
public void run()
{
WebProvider.DownloadComicList();
Intent intent = new Intent();
intent.setDataAndType(ComicContentProvider.COMIC_URI, "vnd.android.cursor.dir/vnd.mymir.comic");
returnResult(intent);
}
};
pg = ProgressDialog.show(this, "Downloading", "Please wait, retrieving data....");
Thread thread = new Thread(null, loader, "LoadComicList");
thread.start();
}
else
{
setResult(Activity.RESULT_CANCELED);
finish();
}
}
private void returnResult(Intent intent)
{
result = intent;
runOnUiThread(returner);
}
}
It turns out you can do this by setting the activitys theme-attribute to #android:style/Theme.Dialog and calling this.setVisible(false); in the onCreate-method of the activity.

Let the splash activity wait a process

My app have a splash activity
It must display at least 5 seconds
But in this activity I have another thread to sync data from internet
Sync process may take more than 5 seconds or less than 5 second.
If less than 5 seconds, the Handler should wait until fifth second
If more then 5 seconds, the Handler should wait until process complete
How to make the Handler wait another thread?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
syncFromInternet(); // another thread may over 5 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent;
intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
}, 5000);
}
You have to make just simple logic Like
When handler completes then check for completion of syncFromInternet method, if it completed open main Activity
When syncFromInternet completes then check for completion of handler, if it completed open main Activity.
Above explanation in code:
boolean isHandlerCompleted = false, isAsyncCompleted = false;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isHandlerCompleted = true;
if (isHandlerCompleted && isAsyncCompleted) {
openMainActivity();// both thread completed
}
}
}, 5000);
// in your async task add this condition when it completes its task
isAsyncCompleted = true;
if (isHandlerCompleted && isAsyncCompleted) {
openMainActivity();// both thread completed
} // till this line
// make this function to open main activity
openMainActivity() {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
You can use an AsyncTask instance and measure the time for syncing with the remote server. If the time is greater than 5 minutes, start the new activity, otherwise - wait till the 5th second:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
private static final long FIVE_SECONDS = 5 * 1000;
private volatile Date mStartTime;
#Override
protected void onPreExecute() {
mStartTime = new Date();
}
#Override
protected Void doInBackground(Void... params) {
// Do the syncing here
syncFromInternet();
Date now = new Date();
long execTime = now.getTime() - mStartTime.getTime();
if(execTime < FIVE_SECONDS) {
Thread.sleep(FIVE_SECONDS - execTime);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(...);
startActivity(intent);
finish();
}
};
asyncTask.execute(null, null);
}
You can use this code :
package com.example.untitled;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.File;
import java.io.IOException;
public class MyActivity extends Activity {
private volatile boolean isAvailable = false;
private volatile boolean isOver = false;
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
if (isOver) {
Log.e("messageHandler","isOver");
transitToNewActivity();
}else {
Log.e("messageHandler","isOver false");
}
break;
}
}
};
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
syncFromInternet(); // another thread may over 5 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isOver = true;
Log.e("mainHandler", "Main handler expired");
if (isAvailable) {
transitToNewActivity();
Log.e("mainHandler", "isAvailable");
}else {
Log.e("mainHandler","isAvailable false");
}
}
}, 50000);
public void transitToNewActivity() {
Log.e("transitToNewActivity","Activity transited");
Intent intent;
intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
public void syncFromInternet() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(80000);
isAvailable = true;
messageHandler.sendEmptyMessage(0);
Log.e("syncFromInternet", "internet data synced");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
and please modify it according to your requirement.
you should implement AsyncTask so that this will wait untill your syncFromInternet() is completed.
private class BackgroundSplashTask extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progressbar
}
#Override
protected Object doInBackground(Object[] params) {
try {
syncFromInternet(); // sync in background
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// dismiss progressbar
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent); // go to SecondActivity after syncFromInternet is completed
finish();
}
}
Call your handler inside syncFromInternet() after execution of thread.

Categories

Resources