Question

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)
Was it helpful?

Solution

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();
     }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top