0

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);
}
}
Yoh Hendry
  • 417
  • 6
  • 15
  • The problem is that you want to show a Toast in a background thread, but it seems to me like you should use logging instead, because it looks like you're toasting development information. Maybe go for `Log.d("MyActivity", "I'm still fine");`. That way the Toast does not annoy the user if it accidentally stays in the app. – kevinpelgrims Apr 29 '15 at 05:31
  • re edited my codes. problem is when running in device. there were no problem in emulator – Yoh Hendry Apr 29 '15 at 05:31

1 Answers1

1

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?

Community
  • 1
  • 1
Arash GM
  • 10,316
  • 6
  • 58
  • 76