Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to use a AlertDialog in Android which will notify the users that they are runing in offline mode after checking the internet connection.

I have used the following codes:

protected Void doInBackground(Void... params) {
            if (this.isOnline()) {
                    new GetJson().execute();
            } else {

        AlertDialog.Builder builder1 = new AlertDialog.Builder(homeFragment);
        builder1.setMessage("INTERNET CONNECTION NOT AVAILABLE. Now you are viewing the news in Offline Mode.");
        builder1.setCancelable(true);

        AlertDialog alert1 = builder1.create();
        alert1.show();

        try {
            saveFile = new SaveIntoFile(fileName);
            jsonStr = saveFile.read();
            // Log.d(TAG,"offline data reading from a file");
            if (!jsonStr.equals(null))
                new GetDatas().execute();
            else {

            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
    return null;

}

But I am getting the error on adding the codes for AlertDialog. The app works fine without the codes for AlertDialog. What can be the mistakes with this code and how can i correct it to work well??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

doInBackground() runs on a separate thread, other than the main thread. You can use UI elements only on main thread. Try using runOnUiThread() method inside doInBackground() to show the dialog.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...