Andrew Quebe
Andrew Quebe

Reputation: 2293

AlertDialog on Android App Startup

I'm trying to make this dialog box run when the user has first downloaded the app and then never show again.

Here is my code:

Thread t = new Thread(new Runnable() {

@Override
public void run() {
    SharedPreferences getPrefs = PreferenceManager
        .getDefaultSharedPreferences(getBaseContext());
    boolean isFirstStart = getPrefs.getBoolean("key", true);

    if (isFirstStart) {
        //Line 39 is next
        new AlertDialog.Builder(MainActivity.this)
        .setTitle("Sample Title")
        .setMessage("Sample Message")
        .setNeutralButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                }
        })
        .show();

            SharedPreferences.Editor e = getPrefs.edit();
            e.putBoolean("key", false);
            e.commit();
        }

    }
});

t.start();

This code is in an onCreate method inside a FragmentActivity. Specifically one that has three scroll tabs.

I am getting the following RunTimeError:

03-13 16:54:02.803    6759-6784/com.hidden.hidden E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-7125
    Process: com.hidden.hidden, PID: 6759
    java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
            at android.os.Handler.<init>(Handler.java:200)
            at android.os.Handler.<init>(Handler.java:114)
            at android.app.Dialog.<init>(Dialog.java:109)
            at android.app.AlertDialog.<init>(AlertDialog.java:114)
            at android.app.AlertDialog$Builder.create(AlertDialog.java:931)
            at android.app.AlertDialog$Builder.show(AlertDialog.java:950)
            at com.hidden.hidden.MainActivity$1.run(MainActivity.java:39)
            at java.lang.Thread.run(Thread.java:841)

Note: Package name is hidden for security.

Where am I going wrong?

Thanks for any help.

Upvotes: 1

Views: 584

Answers (3)

hes_theman
hes_theman

Reputation: 628

It's seem like you're trying to change the UI from outside of the main thread. Put your AlertDialog code outside of your new thread object and it should run normally.

Upvotes: 0

user1889890
user1889890

Reputation:

Try putting the alertdialog in your onCreate() method and using:

if (isFirstStart) {
    dialog.show()
}

Upvotes: 1

Jorge Alfaro
Jorge Alfaro

Reputation: 924

Why do you put the code inside a thread?, if you put the alert outside the thread it should run fine, if its a must to use a thread show the alert dialog inside "runOnUiThread"

Upvotes: 2

Related Questions