0

I have a button that calls CheckNetworkConnectivity. If WiFi is not available it shows a toast with some text (Network not available), that is fine. But when WiFi connectivity is available, Activity will crash when accessing a URL.

My problem is sometimes WiFi network is available but you have to login to access the server. It shows in your mobile as WiFi connected.

ExampleActivity.java:

public class ExampleActivity extends ListActivity {
    // url to make request
    private static String url = "http://10.0.2.2/test/index.php";

    // JSON Node usds
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_CURRENCY = "currency";
    private static final String TAG_BUY = "buy";
    private static final String TAG_SALE = "sale";
    private static final String TAG_UPDATE = "update";

    // contacts JSONArray
    JSONArray contacts = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.example_layout);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_CONTACTS);

            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String currency = c.getString(TAG_CURRENCY);
                String buy = c.getString(TAG_BUY);
                String sale = c.getString(TAG_SALE);
                String update = c.getString(TAG_UPDATE);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_CURRENCY, currency);
                map.put(TAG_BUY, buy);
                map.put(TAG_SALE, sale);
                map.put(TAG_UPDATE, update);

                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item_exchange,
                new String[] { TAG_CURRENCY, TAG_BUY, TAG_SALE, TAG_UPDATE }, new int[] {
                        R.id.currency, R.id.buy, R.id.sale, R.id.update });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();
    }
}
Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52
user1710911
  • 657
  • 3
  • 7
  • 15
  • 2
    Is the solution beyond a `try{...}catch(...){...}`? – ChiefTwoPencils Sep 10 '13 at 08:14
  • 1
    Post your logcat traces.. – CRUSADER Sep 10 '13 at 08:15
  • You should include exampleActivity class as it looks the URL connection is there, not in InfoActivity. Logcat exception stack trace would be helpful as well. Also, no need to pass InfoActivity.this to the Intent (that's for inner classes), this will be just fine. And I think passing result null or not passing is probably the same. – momo Sep 10 '13 at 08:18

4 Answers4

1

You can simply use this:

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

and use by:

   if(isNetworkAvailable()){

     // do your stuff
  }else{
  // no network..
  }

And add permission to Android Manifest file:

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

you can't update your UI in main thread so...use this in you Activity..and call this function on onCreate() method:

like :

  new DowloadTest().execute();


  public class DowloadTest extends AsyncTask<String, Integer, String> {
    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(c);
        pDialog.setMessage("Please wait..");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    };

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub



        JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String currency = c.getString(TAG_CURRENCY);
            String buy = c.getString(TAG_BUY);
            String sale = c.getString(TAG_SALE);
            String update = c.getString(TAG_UPDATE);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_CURRENCY, currency);
            map.put(TAG_BUY, buy);
            map.put(TAG_SALE, sale);
            map.put(TAG_UPDATE, update);

            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        runOnUiThread(new Runnable() {
            public void run() {

                try {
                    if (pDialog != null) {
                        pDialog.dismiss();
                    }

                     ListAdapter adapter = new  SimpleAdapter(this, contactList,R.layout.list_item_exchange,new String[] { TAG_CURRENCY, TAG_BUY, TAG_SALE, TAG_UPDATE }, new int[] {
                    R.id.currency, R.id.buy, R.id.sale, R.id.update });

                    setListAdapter(adapter);

                    // selecting single ListView item
                    ListView lv = getListView();

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



            }

        });
        return;
    }
}
Piyush
  • 18,895
  • 5
  • 32
  • 63
  • thanks for your replay, If Network not available it will show toast, but when url server is not available it will crash – user1710911 Sep 10 '13 at 08:39
  • So have to check that if url is null then display alert message and in else part do your stuff.. – Piyush Sep 10 '13 at 08:40
  • +1 for the UI connection guess, you beat me while I was writing the same ;-) – momo Sep 10 '13 at 08:59
  • I have done that but there are some error i couldn't figure out. I have updated my all code, can you update your code with main. i will appreciate... – user1710911 Sep 10 '13 at 09:07
  • Dear Piyush.... My problem is sometime WiFi network available but you have to login then access the server... it shows in your mobile WiFi connected... – user1710911 Sep 10 '13 at 09:17
0

Try this

 public Boolean check() {
 ConnectivityManager conn = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conn != null) {
        NetworkInfo[] net = conn.getAllNetworkInfo();
        if(net!=null)
        for (int i = 0; i < net.length; i++)
            if (net[i].getState() == NetworkInfo.State.CONNECTED)
                return true;
    }

Then Retrieve it in MainActivity

ConnectionDetector connection = new ConnectionDetector(this);
    Boolean internetConnection = connection.check();
    if (internetConnection == false) {
        Toast.makeText(getApplicationContext(), "No Internet Connectivity",
                Toast.LENGTH_SHORT).show();
    }
else
{
// enter code here
}
gbl
  • 178
  • 2
  • 12
0

Please make sure that, You specify the required permissions in manifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Ciril
  • 420
  • 3
  • 9
0

Assuming URL is not null in ExampleActivity, I guess you can be getting a NetworkOnMainThreadException (this will happen in Android 3.0 and onwards).

Check this answer on performing connections on the UI Thread (using JParser.getJSONFromURL() too) getJSONfromURL - Null Pointer Exception

You can solve it by using AsyncTask. Can also use a Thread like this:

new Thread(new Runnable() {
 public void run() {
  JSONObject json = jParser.getJSONFromUrl(url);
  ...
 }
}.start();

This will execute the connection in another Thread and will not block the UI nor launch the Exception.

UPDATE: Regarding the situation where the phone is connected to WIFI but didn't authenticate/login to the hotspot yet (thus, the getJSONFromURL method will crash because the connection will return a wifi login page instead of the intended JSON). You can do as follows:

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // Do whatever
}

from: https://stackoverflow.com/a/3841407/801913

Community
  • 1
  • 1
momo
  • 3,404
  • 6
  • 37
  • 66
  • thanks for your help Momo, where shall i put this code exactly? I appreciate your help... – user1710911 Sep 11 '13 at 05:37
  • Just where you check the connectivity before getting the JSON. However, I don't think this guarantees the device is authenticated on the wifi. There are 2 options: surround the getJSONfromURL method with a try/catch (easiest and you should be doing it already as it's very easy to parse something worng and get and exception), OR you create a method where you open a HTTPURLCOnnection to you server and check the response is not a HTTP redirect to the wifi login page (this is harder, crappy and not too reliable). Also, accept some answer if it helped! ;) – momo Sep 11 '13 at 09:09