handler.postDelayed application stopped working [duplicate] - android

This question already has answers here:
How do you display a Toast from a background thread on Android?
(14 answers)
Closed 7 years ago.
my application always crash whenever it reach Toast(parent) part. i tried emptying the entire run() and there were no problem.
this codes work fine in emulator but not on device.
please ignore the Toast if you would like to, my main problem is not the Toast but its the codes onwards. they crash on device.
im merely using the Toast to know where the application crashed.
public class LoadingActivity extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 2000;
Intent intent;
LoadingActivity parent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_loading);
intent = getIntent();
parent = this;
ImageView logo = (ImageView) findViewById(R.id.imageView);
TextView splash = (TextView) findViewById(R.id.splash);
splash.setText(intent.getStringExtra(Constant.SPLASH_TEXT));
TranslateAnimation animator = new TranslateAnimation(logo.getX(), logo.getX(), logo.getY(), logo.getY() + 300);
animator.setDuration(2000);
animator.setFillAfter(true);
logo.startAnimation(animator);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
//error on here
Toast.makeText(parent, "im still fine", Toast.LENGTH_LONG).show();
/* Create an Intent that will start the Menu-Activity. */
Intent nextIntent = new Intent(parent, HomeActivity.class);
nextIntent.putExtra(Constant.LOGIN_USERNAME, intent.getStringExtra(Constant.LOGIN_USERNAME));
parent.startActivity(nextIntent);
Toast.makeText(parent, "passed", Toast.LENGTH_LONG).show();
LoadingActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
}

You cannot use Toast(any UI related elements) inside background thread because worker thread doesn't access Ui elements , so you can use Activity.runOnUiThread(Runnable) , also you can use your Activity context to make your Toast.
Toast.makeText(LoadingActivity.this, "passed", Toast.LENGTH_LONG).show();
How to display a Toast inside a Handler/thread?

Related

How to show image 15 seconds, while data loading to the app?

I am making an app and i am using sqlite database. On the first launch of my application and on its onUpdate, i am add data to sqlite db from the xml file. Consequently, on the first launch of my app, it shows me white screen ~15 seconds. I want to show my full screen), ~15 seconds. How i can do that?
You can use SplashActivity display your Image, use Hander.postDelayed() to delay this screen 15s before startActivity to main screen.
Here is example:
public class Splash extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 15000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
//Load data
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this,MainActivity.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
}

Add the loading screen in starting of the android application

My app is loading the start page in 10 seconds. In that time of 10 sec android screen is blank.
In that time I want to add the loading screen. How to add it?
And tell me in app how to know the starting page is loading? And tell me how to do in my app?
use ProgressDialog.
ProgressDialog dialog=new ProgressDialog(context);
dialog.setMessage("message");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();
hide it whenever your UI is ready with data. call :
dialog.hide();
You can use splash screen in your first loading Activity like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread welcomeThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000); //Delay of 10 seconds
} catch (Exception e) {
} finally {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}
Hope this code helps you.
Please read this article
Chris Stewart wrote there:
Splash screens just waste your time, right? As an Android developer,
when I see a splash screen, I know that some poor dev had to add a
three-second delay to the code.
Then, I have to stare at some picture for three seconds until I can
use the app. And I have to do this every time it’s launched. I know
which app I opened. I know what it does. Just let me use it!
Splash Screens the Right Way
I believe that Google isn’t contradicting itself; the old advice and
the new stand together. (That said, it’s still not a good idea to use
a splash screen that wastes a user’s time. Please don’t do that.)
However, Android apps do take some amount of time to start up,
especially on a cold start. There is a delay there that you may not be
able to avoid. Instead of leaving a blank screen during this time, why
not show the user something nice? This is the approach Google is
advocating. Don’t waste the user’s time, but don’t show them a blank,
unconfigured section of the app the first time they launch it, either.
If you look at recent updates to Google apps, you’ll see appropriate
uses of the splash screen. Take a look at the YouTube app, for
example.
You can create a custom loading screen instead of splash screen. if you show a splash screen for 10 sec, it's not a good idea for user experience. So it's better to add a custom loading screen. For a custom loading screen you may need some different images to make that feel like a gif. after that add the images in the res folder and make a class like this :-
public class LoadingScreen {private ImageView loading;
LoadingScreen(ImageView loading) {
this.loading = loading;
}
public void setLoadScreen(){
final Integer[] loadingImages = {R.mipmap.loading_1, R.mipmap.loading_2, R.mipmap.loading_3, R.mipmap.loading_4};
final Handler loadingHandler = new Handler();
Runnable runnable = new Runnable() {
int loadingImgIndex = 0;
public void run() {
loading.setImageResource(loadingImages[loadingImgIndex]);
loadingImgIndex++;
if (loadingImgIndex >= loadingImages.length)
loadingImgIndex = 0;
loadingHandler.postDelayed(this, 500);
}
};
loadingHandler.postDelayed(runnable, 500);
}}
In your MainActivity, you can pass a to the LoadingScreen class like this :-
private ImageView loadingImage;
Don't forget to add an ImageView in activity_main.
After that call the LoadingScreen class like this;
LoadingScreen loadingscreen = new LoadingScreen(loadingImage);
loadingscreen.setLoadScreen();
I hope this will help you
public class Splash extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 3000; //set your time here......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this,MainActivity.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
}
}
If the application is not doing anything in that 10 seconds, this will form a bad design only to make the user wait for 10 seconds doing nothing.
If there is something going on in that, or if you wish to implement 10 seconds delay splash screen,Here is the Code :
ProgressDialog pd;
pd = ProgressDialog.show(this,"Please Wait...", "Loading Application..", false, true);
pd.setCanceledOnTouchOutside(false);
Thread t = new Thread()
{
#Override
public void run()
{
try
{
sleep(10000) //Delay of 10 seconds
}
catch (Exception e) {}
handler.sendEmptyMessage(0);
}
} ;
t.start();
//Handles the thread result of the Backup being executed.
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
pd.dismiss();
//Start the Next Activity here...
}
};
Write the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread welcomeThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000) //Delay of 10 seconds
} catch (Exception e) {
} finally {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}

Android app wont run a second time

I have an Android app that shows a frame-by-frame animation activity. At the end of the animation it starts a background service and closes the activity. Here is the code:
cont = getApplicationContext();
final ImageView img = (ImageView)findViewById(R.id.img);
img.setBackgroundResource(R.drawable.intro);
img.post(new Runnable() {
public void run() {
animation = (AnimationDrawable)img.getBackground();
animation.setOneShot(true);
animation.start();
timer = new Timer();
timer.schedule(new timer_exp(), 3400);
}
});
}
class timer_exp extends TimerTask{
#Override
public void run() {
//start service
Intent serviceIntent = new Intent(cont, MainService.class);
startService(serviceIntent);
//kill activity
finish();
}
}
When I run the app I can see the animation and then the service starts. When I press on the app's icon again, I get a black screen and the app crashes.
Any Ideas to what the problem might be?
Thanks,
PB
After some investigation, it turned out that the service was the problem.
I had some Thread.sleep() in several places that caused the UI thread to crash.
After adding another thread for these actions the problem solved.

thread causing application to crash

EDIT:
just incase you read this i got the problem sorted i had gotten confused by my layouts and was editing the wrong one when i realised this all was sorted!
END EDIT!
every time i add a thread to my application it causes it to crash when the activity containing the thread is called below is the code piece containing the thread:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cam);
Toast t = Toast.makeText(this, "Just Click The Magnifying Glass To Search", 5000); //creates a new pop up message that lasts for 5 seconds
t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
t.show();
bt = (ImageButton)findViewById(R.id.button); //creates instance of button
bt.setOnClickListener(search); //starts an on click listener for button
preview = (SurfaceView)findViewById(R.id.myview); //creates instance of surfaceview
previewHolder = preview.getHolder(); //creates a surfaceholder
previewHolder.addCallback(this); //sets surfaceholder callback as the activity
previewHolder.setType(3); //sets the type to SURFACE_TYPE_PUSH_BUFFERS
th = new Thread() {
public void run() {
handler.post(new Runnable() {
public void run() {
tv.setVisibility(0);
}
});
}
};
th.start();
}
if anyone could shed some light on the situation it would be greatly appreciated
EDIT:
i have got the thread working and got it to call a method which creates Toast however when i try to modify a setting of the textview it throws an NullPointerException error
I don't see initialization of TextView tv in your code (tv = (TextView)findViewById(R.id.id_of_textview);).
May be it is the cause of the problem?
To show TextView after 5 seconds, you can use handler.postDelayed()
If you're doing TextView tv = new TextView(); then this is wrong and even if you're doing TextView tv = (TextView)findViewById(R.id.tv); then the layout will not be inflated before setContentView(); so you have to initialize tv in onCreate() method.

How can I make the android program display a layout and then wai a few sec. and the display another layout?

Hi guys I just want the program to display the layout main0 and stay for a few secounds then display layout main1 like the programs we see in any phone where an image or layout show up at the start of the program and then fade.
/**the main activity */
public class rdwt extends Activity implements OnClickListener{
Button b1;
Button b2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main0);
//Here
setContentView(R.layout.main1);
b1= (Button)findViewById(R.id.Button01);
b2= (Button)findViewById(R.id.Button02);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
public void onClick(View v) {
if (v==this.b1){
Intent callwrite = new Intent(this, wto.class);
startActivity(callwrite);
}
if(v==this.b2){
Intent callread = new Intent(this, rfr.class);
startActivity(callread);
}
}
}
You need to read a technical article about Updating the UI from a Timer
I think there are particularly two different approaches.
1) use a android.os.Handler and send a delayed message
2) use a timer and a timer task to update your layout after a specific amount of time
Code example:
TimerTask bla = new YourTask();
Timer timer = new Timer();
timer.schedule(bla, 1000);
And your class YourTask:
public class YourTask extends TimerTask {
public void run() {
updateYourLayout();
}
}
Edit: However I think you're looking for a splashscreen. This simple tutorial explains how to do it: http://www.anddev.org/simple_splash_screen-t811.html
// Place the following line in your code.
timer(3500); // Waits 3.5 seconds before moving on to the next activity.
public void timer(int counter){
new Handler().postDelayed(new Runnable(){
#Override
// counter is in milliseconds.
public void run() {
Intent mainIntent = new Intent(THISCLASSNAME.this,CLASSNAMETOJUMPTO.class);
startActivity(mainIntent);
finish();

Categories

Resources