1

I already created an android app which uses a web service to send and retrieve JSON data.

When I make a request while the device is online it works fine but when the device goes offline the app is stuck and prints Null Pointer Exception error.

Is there a way to listen to the internet connection?

Benny Bottema
  • 11,111
  • 10
  • 71
  • 96
Naham Soft
  • 91
  • 2
  • 12

4 Answers4

2

From your question and comments, looks like you have a problem if the connection is lost during the request/response process. So in order to listen for this change you need to crate a BroadcastReceiver (NetworkStateReceiver) to listen to network state change, something like this: NetworkStateReceiver.java

package your.package.name;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.ArrayList;
import java.util.List;

public class NetworkStateReceiver extends BroadcastReceiver {
    // Listeners list
    protected List<NetworkStateReceiverListener> listeners;

    // Connection flag
    protected Boolean connected;

    /**
     * Public constructor
     */
    public NetworkStateReceiver() {
        listeners = new ArrayList<NetworkStateReceiverListener>();
        connected = null;
    }

    /**
     *
     * @param context  Context - Application context
     * @param intent  Intent - Manages application actions on network state changes
     */
    public void onReceive(Context context, Intent intent) {
        if(intent == null || intent.getExtras() == null) return;

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = manager.getActiveNetworkInfo();

        if((ni != null) && ni.isConnected()) {
            connected = true;
        } else {
            connected = false;
        }

        mNotifyStateToAll();
    }

    /**
     * Notify the state to all needed methods
     */
    private void mNotifyStateToAll() {
        for(NetworkStateReceiverListener listener : listeners)
            mNotifyState(listener);
    }

    /**
     * Notify the network state
     * @param listener  NetworkStateReceiverListener - receives network state change
     */
    private void mNotifyState(NetworkStateReceiverListener listener) {
        if(connected == null || listener == null) return;

        if(connected == true) {
            listener.networkAvailable();
        } else {
            listener.networkUnavailable();
        }
    }

    /**
     * Add listener once it is needed
     * @param l  NetworkStateReceiverListener - receives network state change
     */
    public void addListener(NetworkStateReceiverListener l) {
        listeners.add(l);
        mNotifyState(l);
    }

    /**
     * Remove the listener once it is not needed anymore
     * @param l  NetworkStateReceiverListener - receives network state change
     */
    public void removeListener(NetworkStateReceiverListener l) {
        listeners.remove(l);
    }

    /**
     * Set interface to communicate with Main methods
     */
    public interface NetworkStateReceiverListener {
        public void networkAvailable();
        public void networkUnavailable();
    }
}

Your activity needs to implement this:

public class MyActivity extends Activity implements NetworkStateReceiver.NetworkStateReceiverListener {
    // Receiver that detects network state changes
    private NetworkStateReceiver networkStateReceiver;
    private boolean mNetworkAvailable;

    ...
    // What ever the code you want or need
    ...

    /**
     * Call back for NetworkStateReceiver to set the network state to available
     */
    @Override
    public void networkAvailable() {
        Log.d(TAG, "I'm in, baby! Dance, dance revolution!");
        sNetworkAvailable = true;
        // Network available again do things here
    }

    /**
     * Call back for NetworkStateReceiver to set the network state to unavailable
     */
    @Override
    public void networkUnavailable() {
        Log.d(TAG, "I'm dancing with myself, noone can see me.");
        sNetworkAvailable = false;
        // Network broke, warn the user, or do alternative action
    }

    /**
     * Need to register the receiver
     */
    @Override
    public void onResume() {
        super.onResume();

        // Register the network state receiver to listen to network state change
        if (networkStateReceiver == null) {
            networkStateReceiver = new NetworkStateReceiver();
            networkStateReceiver.addListener(this);
            this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
        }
    }

    /**
     * Unregister the receiver as you do not need it anymore
     */
    @Override
    public void onDestroy() {
        super.onDestroy();

        // Remove network state receiver and listener as we don't need them at this point
        if (networkStateReceiver != null) {
            networkStateReceiver.removeListener(this);
            this.unregisterReceiver(networkStateReceiver);
            networkStateReceiver = null;
        }
    }

    ...
    // What ever the code you want or need
    ...

}
Slobodan Antonijević
  • 2,533
  • 2
  • 17
  • 27
1
  • You can check if it is connected to internet through this.

    private boolean isNetworkAvailable() { 
            ConnectivityManager manager = (ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            boolean isAvailable = false;
    
            if(networkInfo != null && networkInfo.isConnected()) {
                isAvailable = true;
    
            } 
    
            return isAvailable;
     }
    
MrRobot9
  • 2,402
  • 4
  • 31
  • 68
0

In your manifest add permission

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

Java

public boolean networkstatus() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
 }


if(networkstatus())
{
// do your process
}
else
{
//alert message for no internet connection
}
sasikumar
  • 12,540
  • 3
  • 28
  • 48
  • I have done like this before the process started but when the device go offline and the process had not done the app go on an error – Naham Soft Apr 19 '16 at 08:23
0

before request the web service call this method

private boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = cm.getActiveNetworkInfo();

    if (NInfo != null && NInfo.isConnectedOrConnecting())
        return true;
    else
        return false;
}

if(isOnline()){
 // request the service 
 // but make sure that U have surrounded the calling web-service by try and catch
try{
     // here make your request when the connection go offline the app will    catch   the error and ignore the process 
}catch (Exception e) {
}

add this permission

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  • And if the connection breaks during the request process it will fail. – Slobodan Antonijević Apr 19 '16 at 09:04
  • yes it will fail .this is the logic . but the app will not stuck or break –  Apr 19 '16 at 09:13
  • That is not the solution. catch (Exception e) should never be used, you should always catch the exact exception. [Don't Catch Generic Exception](https://source.android.com/source/code-style.html#dont-catch-generic-exception) – Slobodan Antonijević Apr 19 '16 at 09:23
  • it is work fine my brother . and we use exact exception when we need to do something to correct error but in my problem I need to do nothing just avoid app stuck – Naham Soft Apr 19 '16 at 13:31