App crashes when trying to show AlertDialog in thread

Arda Kara

I have a login activity with to tabs. One for logging in and other one for signing up. I want to check network connection continuesly so I have coded a thread. I want to show a dialog when there is not a connection which says check your internet connection and try again, and there is a button for trying again.

here is my code:

package com.geniboys.sosyaaal;

import java.util.Locale;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;

public class Logger extends FragmentActivity implements ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    static boolean isBoxOpen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logger);

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setTitle("Sosyaaal");
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar));


        Thread connectivity = new Thread(){
            public void run(){

                try {
                    while(!isBoxOpen)
                    {
                        if( !isOnline() )
                        {
                            isBoxOpen = true;
                              // display error
                            new AlertDialog.Builder(Logger.this)
                            .setTitle("Bağlantı Sorunu")
                            .setMessage("İnternet bağlantısını kontrol edip tekrar deneyin")
                            .setCancelable(false)
                            .setPositiveButton(R.string.yeniden, new DialogInterface.OnClickListener() 
                            {               
                                public void onClick(DialogInterface dialog, int which) 
                                { 
                                    Logger.isBoxOpen = false;// Try Again
                                }
                            })

                             .show();
                        }

                    }
                   } catch (Exception e) {

                   }
            }


        };

        connectivity.start();


        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);
                    }
                });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.logger, menu);
        return true;
    }

    public boolean isOnline() {
        ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
            case 0:
                // Top Rated fragment activity
                return new GirisFragment();
            case 1:
                // Games fragment activity
                return new KayitFragment();
            }

            return null;
        }

        @Override
        public int getCount() {
            // Show 2 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class GirisFragment extends Fragment {

        public static final String ARG_SECTION_NUMBER = "section_number";

        public GirisFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_giris,
                    container, false);

            return rootView;
        }
    }


    public static class KayitFragment extends Fragment {

        public static final String ARG_SECTION_NUMBER = "section_number";

        public KayitFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_kayit,
                    container, false);

            return rootView;
        }
    }

}

and here is the logcat:

01-31 15:21:33.414: W/dalvikvm(7688): threadid=12: thread exiting with uncaught exception (group=0x4104cae0)
01-31 15:21:33.414: E/AndroidRuntime(7688): FATAL EXCEPTION: Thread-608
01-31 15:21:33.414: E/AndroidRuntime(7688): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-31 15:21:33.414: E/AndroidRuntime(7688):     at android.os.Handler.<init>(Handler.java:197)
01-31 15:21:33.414: E/AndroidRuntime(7688):     at android.os.Handler.<init>(Handler.java:111)
01-31 15:21:33.414: E/AndroidRuntime(7688):     at android.app.Dialog.<init>(Dialog.java:114)
01-31 15:21:33.414: E/AndroidRuntime(7688):     at android.app.AlertDialog.<init>(AlertDialog.java:121)
01-31 15:21:33.414: E/AndroidRuntime(7688):     at android.app.AlertDialog$Builder.create(AlertDialog.java:945)
01-31 15:21:33.414: E/AndroidRuntime(7688):     at android.app.AlertDialog$Builder.show(AlertDialog.java:965)
01-31 15:21:33.414: E/AndroidRuntime(7688):     at com.geniboys.sosyaaal.Logger$1.run(Logger.java:74)
01-31 15:21:35.434: I/Process(7688): Sending signal. PID: 7688 SIG: 9
01-31 15:21:37.844: W/dalvikvm(8023): threadid=11: thread exiting with uncaught exception (group=0x4104cae0)
01-31 15:21:37.844: E/AndroidRuntime(8023): FATAL EXCEPTION: Thread-643
01-31 15:21:37.844: E/AndroidRuntime(8023): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-31 15:21:37.844: E/AndroidRuntime(8023):     at android.os.Handler.<init>(Handler.java:197)
01-31 15:21:37.844: E/AndroidRuntime(8023):     at android.os.Handler.<init>(Handler.java:111)
01-31 15:21:37.844: E/AndroidRuntime(8023):     at android.app.Dialog.<init>(Dialog.java:114)
01-31 15:21:37.844: E/AndroidRuntime(8023):     at android.app.AlertDialog.<init>(AlertDialog.java:121)
01-31 15:21:37.844: E/AndroidRuntime(8023):     at android.app.AlertDialog$Builder.create(AlertDialog.java:945)
01-31 15:21:37.844: E/AndroidRuntime(8023):     at android.app.AlertDialog$Builder.show(AlertDialog.java:965)
01-31 15:21:37.844: E/AndroidRuntime(8023):     at com.geniboys.sosyaaal.Logger$1.run(Logger.java:74)
Linga

You must need to create AlertDialog inside UI thread else it will never work. You can use MessageHandler or runOnUiThread(using runnable) to create your dialog inside.

Example:

runOnUiThread(new Runnable() {
    public void run() {
          new AlertDialog.Builder(Logger.this)
          .setTitle("Bağlantı Sorunu")
          .setMessage("İnternet bağlantısını kontrol edip tekrar deneyin")
          .setCancelable(false)
          .setPositiveButton(R.string.yeniden, new DialogInterface.OnClickListener() 
           {               
             public void onClick(DialogInterface dialog, int which) 
             { 
                  Logger.isBoxOpen = false;// Try Again
             }
           })
           .show();
     }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

AlertDialog in PreferenceFragment crashes app

From Dev

AlertDialog crashes app

From Dev

App crashes when trying to implement multilingual support

From Dev

Meteor app crashes when trying to populate collections

From Dev

App crashes when trying to fullscreen activity

From Dev

App crashes when trying to record audio

From Dev

App crashes when trying to open a fragment with listview

From Dev

App crashes when trying to start a new activity

From Dev

App crashes when trying to connect to Neura service

From Dev

App crashes when trying to save to SQLite database

From Dev

App crashes when trying to add a row into table by pressing a button

From Dev

App crashes when trying to display three panoramic photos on one screen

From Dev

Visual Studio crashes when trying to associate Cordova app with store

From Dev

App crashes when nothing is entered in the TextBoxes I'm trying to parse

From Dev

App crashes when trying to access a viewcontroller from AppDelegate

From Dev

App crashes when trying to capture video using a camera intent

From Dev

My Android app crashes when trying to store SQLite data

From Dev

App crashes when trying to access array Android SDK

From Dev

Instagram crashes when my android app trying post on it using intent

From Dev

App crashes when nothing is entered in the TextBoxes I'm trying to parse

From Dev

App crashes when trying to connect to SignalR server after disconnecting it

From Dev

App Crashes When Trying to Set Wallpaper as Activity Background

From Dev

App crashes when trying to reuse toolbar by extending custom activity

From Dev

Android app crashes when trying to set a click listener on ImageButton in Fragment

From Dev

I am trying to show an AlertDialog when a ListView item is clicked within the Adapter class, but a black screen is covering the dialog

From Dev

Trying to setText() crashes Android app

From Dev

Trying to parse a json crashes the app

From Dev

Trying to use sharedPreferences, but the app crashes

From Dev

JsonReader running in thread crashes app

Related Related

  1. 1

    AlertDialog in PreferenceFragment crashes app

  2. 2

    AlertDialog crashes app

  3. 3

    App crashes when trying to implement multilingual support

  4. 4

    Meteor app crashes when trying to populate collections

  5. 5

    App crashes when trying to fullscreen activity

  6. 6

    App crashes when trying to record audio

  7. 7

    App crashes when trying to open a fragment with listview

  8. 8

    App crashes when trying to start a new activity

  9. 9

    App crashes when trying to connect to Neura service

  10. 10

    App crashes when trying to save to SQLite database

  11. 11

    App crashes when trying to add a row into table by pressing a button

  12. 12

    App crashes when trying to display three panoramic photos on one screen

  13. 13

    Visual Studio crashes when trying to associate Cordova app with store

  14. 14

    App crashes when nothing is entered in the TextBoxes I'm trying to parse

  15. 15

    App crashes when trying to access a viewcontroller from AppDelegate

  16. 16

    App crashes when trying to capture video using a camera intent

  17. 17

    My Android app crashes when trying to store SQLite data

  18. 18

    App crashes when trying to access array Android SDK

  19. 19

    Instagram crashes when my android app trying post on it using intent

  20. 20

    App crashes when nothing is entered in the TextBoxes I'm trying to parse

  21. 21

    App crashes when trying to connect to SignalR server after disconnecting it

  22. 22

    App Crashes When Trying to Set Wallpaper as Activity Background

  23. 23

    App crashes when trying to reuse toolbar by extending custom activity

  24. 24

    Android app crashes when trying to set a click listener on ImageButton in Fragment

  25. 25

    I am trying to show an AlertDialog when a ListView item is clicked within the Adapter class, but a black screen is covering the dialog

  26. 26

    Trying to setText() crashes Android app

  27. 27

    Trying to parse a json crashes the app

  28. 28

    Trying to use sharedPreferences, but the app crashes

  29. 29

    JsonReader running in thread crashes app

HotTag

Archive