ThePoloDoc
ThePoloDoc

Reputation: 340

How to check Internet connection and spawn a Dialog if not connected

My app is mostly internet based and when the device has not got internet it just crashes due to it trying to download the files but with no success. I have also just realised while typing this that if the data it requires goes offline it will also crash. I have tried reading documentation and trying to add it to my app but it appears I need something different to what I have been reading.

I use my MainActivity to just load the fragments so I doubt I could put some kind of code in it to show dialog on the fragment's used area. Either way I will add my MainActivity and my internet loading fragment.

MainActivity.class:

public class MainActivity extends SherlockFragmentActivity {

    private ViewPager mViewPager;
    private TabSwipe mTabSwipe;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new FirstLaunchEULA(this).show();



        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.pager);
        mViewPager.setOffscreenPageLimit(2);
        setContentView(mViewPager);

        final ActionBar bar = getSupportActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mTabSwipe = new TabSwipe(this, mViewPager);
        mTabSwipe.addTab(bar.newTab().setText("Games"), A_Internet_Service.class, null);
        mTabSwipe.addTab(bar.newTab().setText("Movies"), Test_Fragment.class, null);
        mTabSwipe.addTab(bar.newTab().setText("Tech"), Purchase_Fragment.class, null);


    }

}

A_Internet_Service.class:

public class A_Fragment_Service extends Fragment {

    // All static variables
    static final String URL = "this.is.a.url";
    // XML node keys
    static final String KEY_DATA = "data"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_DATE1 = "date1";
    static final String KEY_DATE2 = "date2";
    static final String KEY_DATE3 = "date3";
    static final String KEY_DATE2VIS = "date2vis";
    static final String KEY_DATE3VIS = "date3vis";
    static final String KEY_PLATFORMS = "platforms";
    static final String KEY_THUMB_URL = "thumb_url";


    ArrayList<HashMap<String, String>> songsList;
    View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TheTask().execute();




    /*
    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {


        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

        }
    }); */
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        view = inflater.inflate(R.layout.main, container, false);
        //list = (ListView) view.findViewById(R.id.data_list);
        return view;

    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    class TheTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... params) {
            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML from URL
            songsList = new ArrayList<HashMap<String, String>>();
            Document doc = parser.getDomElement(xml); // getting DOM element
            NodeList nl = doc.getElementsByTagName(KEY_DATA);
            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                map.put(KEY_ID, parser.getValue(e, KEY_ID));
                map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                map.put(KEY_DATE1, parser.getValue(e, KEY_DATE1));
                map.put(KEY_DATE2, parser.getValue(e, KEY_DATE2));
                map.put(KEY_DATE3, parser.getValue(e, KEY_DATE3));
                map.put(KEY_DATE2VIS, parser.getValue(e, KEY_DATE2VIS));
                map.put(KEY_DATE3VIS, parser.getValue(e, KEY_DATE3VIS));
                map.put(KEY_PLATFORMS, parser.getValue(e, KEY_PLATFORMS));
                map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

                // adding HashList to ArrayList
                songsList.add(map);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Getting adapter by passing xml data ArrayList
            LazyAdapter adapter = new LazyAdapter(getActivity(), dataList);
            view = getView();
            ListView mlist = (ListView) view.findViewById(R.id.data_list);
            mlist.setAdapter(adapter);
            super.onPostExecute(result);
        }
    }

}

Edited Fragment section:

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

    return view;
    if(!isConnected(getActivity())) buildDialog(getActivity()).show();
    else {
        new TheTask().execute();


    }

}

public boolean isConnected(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netinfo = cm.getActiveNetworkInfo();

    if (netinfo != null && netinfo.isConnectedOrConnecting()) {
        android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
        else return false;
    } else
        return false;
}

public AlertDialog.Builder buildDialog(Context c) {

    AlertDialog.Builder builder = new AlertDialog.Builder(c);
    builder.setTitle("No Internet connection.");
    builder.setMessage("You have no internet connection");

    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
        }
    });

    return builder;
}
//All the other code

Upvotes: 2

Views: 9027

Answers (2)

TeeTracker
TeeTracker

Reputation: 7350

I give you a network-util, maybe help your forever.

public final class NetworkUtils {
public static final byte CONNECTION_OFFLINE = 1;
public static final byte CONNECTION_WIFI = 2;
public static final byte CONNECTION_ROAMING = 3;
public static final byte CONNECTION_SLOW = 4;
public static final byte CONNECTION_FAST = 5;

private static String sUserId;

private NetworkUtils() {}


/**
 * Check if the device is connected to the internet (mobile network or
 * WIFI).
 */
public static boolean isOnline(Context _context) {
    boolean online = false;

    TelephonyManager tmanager = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE);
    if (tmanager != null) {
        if (tmanager.getDataState() == TelephonyManager.DATA_CONNECTED) {
            // Mobile network
            online = true;
        } else {
            // WIFI
            ConnectivityManager cmanager = (ConnectivityManager) _context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cmanager != null) {
                NetworkInfo info = cmanager.getActiveNetworkInfo();
                if (info != null)
                    online = info.isConnected();
            }
        }
    }

    return online;
}

/**
 * Get the User Agent String in the format
 * AppName + AppVersion + Model + ReleaseVersion + Locale
 */
public static String getUserAgentString(Context _c, String _appName) {
    if(_appName == null)
        _appName = "";

    String agent = _appName + " " + BackendUtil.getAppVersionString(_c) + " (" + Build.MODEL + "; Android "
            + Build.VERSION.RELEASE + "; " + Locale.getDefault() + ")";

    if(agent.startsWith(" "))
        agent = agent.substring(1);

    return agent;
}

/**
 * Evaluate the current network connection and return the
 * corresponding type, e.g. CONNECTION_WIFI.
 */
public static byte getCurrentNetworkType(Context _context){
    NetworkInfo netInfo = ((ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if(netInfo == null)
        return CONNECTION_OFFLINE;

    if(netInfo.getType() == ConnectivityManager.TYPE_WIFI)
        return CONNECTION_WIFI;

    if(netInfo.isRoaming())
        return CONNECTION_ROAMING;

    if(!(netInfo.getType() == ConnectivityManager.TYPE_MOBILE 
            &&  (netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_UMTS 
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSDPA
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSUPA
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPA 
              || netInfo.getSubtype() == 13 // NETWORK_TYPE_LTE
              || netInfo.getSubtype() == 15))) // NETWORK_TYPE_HSPAP  
         {

        return CONNECTION_SLOW;
    }

    return CONNECTION_FAST;
}


/**
 * Return the current IP adresse of the device or null if it could not be
 * found.
 */
public static String getIpAdress() {
    String result = null;
    try {
        for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
            NetworkInterface iface = interfaces.nextElement();
            for (Enumeration<InetAddress> adresses = iface.getInetAddresses(); adresses.hasMoreElements();) {
                InetAddress ip = adresses.nextElement();
                if (!ip.isLoopbackAddress())
                    result = ip.getHostAddress();
            }
        }
    } catch (SocketException _e) {
        LL.error("Could not find device's ip adress");
    }
    return result;
}


/**
 * Return a MD5 hash of the device id.
 */
public static synchronized String getUserId(Context _context) {
    if (sUserId == null) {
        TelephonyManager tm = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE);
        String id = tm.getDeviceId();
        try {
            MessageDigest digester = MessageDigest.getInstance("MD5");
            digester.update(id.getBytes());
            byte[] digest = digester.digest();

            // Convert to hex string
            BigInteger converter = new BigInteger(1, digest);
            String md5 = converter.toString(16);
            while (md5.length() < 32)
                md5 = "0" + md5;
            sUserId = md5;
        } catch (NoSuchAlgorithmException _e) {
            LL.error("Could not find MD5");
        }
    }
    return sUserId;
}

}

Upvotes: 0

Philipp Jahoda
Philipp Jahoda

Reputation: 51411

You could for example check your Internet connection like this:

It will return true if the device has Internet connection or is about to have Internet connection.

public boolean isConnected(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();

        if (netinfo != null && netinfo.isConnectedOrConnecting()) {
            android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
            else return false;
        } else
            return false;
    }

And this is how u use it in your application: (inside a Fragments onCreateView for example, if the device is not connected, show the dialog, see the code below of how to spawn a simple dialog)

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

    // getActivity() will hand over the context to the method
    // if you call this inside an activity, simply replace getActivity() by "this"
    if(!isConnected(getActivity())) buildDialog(getActivity()).show();
    else {
        // we have internet connection, so it is save to connect to the internet here
        new TheTask().execute();
    }

    // do other stuff
    return view;
}

public boolean isConnected(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netinfo = cm.getActiveNetworkInfo();

    if (netinfo != null && netinfo.isConnectedOrConnecting()) {
        android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
        else return false;
    } else return false;
}

public AlertDialog.Builder buildDialog(Context c) {

    AlertDialog.Builder builder = new AlertDialog.Builder(c);
    builder.setTitle("No Internet connection.");
    builder.setMessage("You have no internet connection");

    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
        }
    });

    return builder;
}

This can be done anywhere in your code, for example in the onCreate() method of your Activity, or in the onCreateView() method of your Fragment - wherever you desire to connect to the internet, check first - then do the Internet stuff.

Don't forget permissions:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

I hope this helps ;)

Upvotes: 12

Related Questions