Search code examples
androidandroid-internet

Internet Connection in Android


I have work on Application That use Internet.

  • It contains XML parsing from url. than
  • Showing Progress Dialog While parsing time.
  • Stop dialog when parsing is done.
  • set TEXT(Data) in ListView.

my issue is that, When device is connected to internet than my Apps works fine But when Device is not connected to internet "Progress dialog" is running for infinite time.

i want to stop dialog if device is not connected to internet or wifi. how to do this?
Any idea? Sorry guys.... I have change my mind i want to check internet connection when i click on button. what i have tried so far is..

public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.homelayout);
        mclip = (ImageButton) findViewById(R.id.clip);
        mclip.setClickable(true);
        mclip.setFocusable(true);

        mclip.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                ConnectivityManager cm = (ConnectivityManager)              getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnectedOrConnecting()) {
               //if it is connected to internet than start Another Activity.
                startActivity(new Intent(ListViewExample.this, ClipOfDay.class));
                } else if (netInfo == null) {
                    AlertDialog alertDialog = new AlertDialog.Builder(ListViewExample.this).create();
                    alertDialog.setTitle("Connection Problem");
                    alertDialog.setMessage("You are not connected to Internet");
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            return;
                        }
                    });
                    alertDialog.show();
                }

            }
        });
       }

But this is not working.if device is not connected to internet than i want to show AlertDialog. otherwise it will start Activity. can Anybody tell me what to do?
Thanks.


Solution

  • Check network connection
    A simple code for checking connection

    ConnectivityManager cMgr = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cMgr.getActiveNetworkInfo();
                String status = netInfo.getState().toString();
                if (status.equals("CONNECTED")) {
                   //DO you work
                } else {
                    Log.e("error", "No connection available ");
                }