Internet connectivity causes Null Pointer Exception in Android application

霸气de小男生 提交于 2019-12-11 16:42:49

问题


I am designing a login screen with having internet connectivity but when I run that code it throws connectivity.

The connectivity code used in broadcast receiver

 public class ConnectivityReceiver extends BroadcastReceiver {

public static ConnectivityReceiverListener connectivityReceiverListener;

public ConnectivityReceiver() {
    super();
}

@Override
public void onReceive(Context context, Intent intent) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();

    if (connectivityReceiverListener != null) {
        connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
    }
}

public static boolean isConnected(){
    ConnectivityManager
            cm = (ConnectivityManager) SpsApplication.getInstance().getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();
}

}

At getApplicationContext() throws error Calling checkConnection() method in onCreate method

public class LoginActivity extends AppCompatActivity implements ConnectivityReceiverListener{

private EditText mEditEmail;
private EditText mEditPassword;

private Button mButtonLoginSPS;

private LinearLayout linearLayoutLogin;

String emailSPS, passwordSPS;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    //Check Internet Connectivity while loading login screen

    linearLayoutLogin = (LinearLayout) findViewById(R.id.main_login);

    mEditEmail = (EditText) findViewById(R.id.emailEditEmail);
    emailSPS = mEditEmail.getText().toString();


    mButtonLoginSPS = (Button) findViewById(R.id.buttonLoginSPS);
    mButtonLoginSPS.setEnabled(false);

    mEditEmail.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (emailSPS.matches(Constant.PATTERN_EMAIL) && s.length() > 0) {
                //mEditEmail.setError("Invalid Email");
                Snackbar.make(linearLayoutLogin, R.string.invalid_email, Snackbar.LENGTH_SHORT).show();
            } else {
                mEditEmail.setError("Valid Email");
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    mEditPassword = (EditText) findViewById(R.id.emailEditPassword);
    mEditPassword.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            callWebserviceEnabled();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

}

private void checkConnection() {

    boolean isConnected = ConnectivityReceiver.isConnected();
    showSnack(isConnected);
}

private void showSnack(boolean isConnected) {

    String message;
    int color;
    if (isConnected) {
        message = "Good! You are connected to network";
        color = Color.WHITE;
    } else {
        message = "Oh ! You are not connected. Please check connectivity";
        color = Color.RED;
    }

    Snackbar snackbar = Snackbar.make(linearLayoutLogin, message, Snackbar.LENGTH_SHORT);
    View sbView = snackbar.getView();
    TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
    textView.setTextColor(color);
    snackbar.show();
}

private void callWebserviceEnabled() {
    passwordSPS = mEditPassword.getText().toString();
    mButtonLoginSPS.setEnabled(true);

    mButtonLoginSPS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Check Internet Connectivity while loading login screen
            checkConnection();

            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
        }
    });
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
    showSnack(isConnected);
}

}

The SPSApplication class

    public class SpsApplication extends Application {

    private static SpsApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized SpsApplication getInstance() {
        return mInstance;
    }

    public void setConnectivityListener(ConnectivityReceiverListener listener) {
       ConnectivityReceiver.connectivityReceiverListener = listener;
    }


}

Here are detailed log of error receive while running application and pressing button

 06-22 14:04:04.443 21986-21986/labs.spoke.com.spokeadmin E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: labs.spoke.com.spokeadmin, PID: 21986
                                                                           java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.ContextWrapper.getApplicationContext()' on a null object reference
                                                                               at labs.spoke.com.spokeadmin.testify.ConnectivityReceiver.isConnected(ConnectivityReceiver.java:32)
                                                                               at labs.spoke.com.spokeadmin.acts.LoginActivity.checkConnection(LoginActivity.java:100)
                                                                               at labs.spoke.com.spokeadmin.acts.LoginActivity.access$300(LoginActivity.java:28)
                                                                               at labs.spoke.com.spokeadmin.acts.LoginActivity$3.onClick(LoginActivity.java:131)
                                                                               at android.view.View.performClick(View.java:5637)
                                                                               at android.view.View$PerformClick.run(View.java:22429)
                                                                               at android.os.Handler.handleCallback(Handler.java:751)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
`

回答1:


Change your method as mentioned with below code.

public static boolean isConnected(Context context){
    ConnectivityManager
            cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();
}

provide context from you are calling this isConnected() method. Hope that helps.




回答2:


NullPointerException is thrown when an application attempts to use an object reference that has the null value .

You should pass Context

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

    public static boolean isConnected(Context ctxOBJ)
   {
      ConnectivityManager cm = (ConnectivityManager) ctxOBJ.getSystemService(Context.CONNECTIVITY_SERVICE);
    .......//Add your code........
   }



回答3:


Try this code hope this will help:

on Application class

public static ApplicationClassName appInstance = null;

@Override
public void onCreate() {
    super.onCreate();

     appInstance = this;

and use this appInstance

   public static boolean isConnectedToInternet() {

      ConnectivityManager connectivity = (ConnectivityManager) ApplicationClassName.appInstance.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) {
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        if (info != null)
            if (info.getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
       }
    return false;
   }

Check if internet connectivity is available or not.

 if(isConnectedToInternet()) {

 // network available

 } else{
 // offline
 }



回答4:


If SpsApplication.getInstance() return application object then no need to call getApplicationContext() method. remove this method.

ConnectivityManager cm = (ConnectivityManager) SpsApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);



回答5:


It looks like SpsApplication is giving the nullpointer

You should add this in your manifest in the application tag

name=".SpsApplication"




回答6:


These are some modification I made to run my code

   public static boolean isConnected(Context context) {
    ConnectivityManager
            cm = (ConnectivityManager) context.getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null

&& activeNetwork.isConnectedOrConnecting();
}

Another change in Login activity by passing context refrence

private void checkConnection() {
    boolean isConnected = ConnectivityReceiver.isConnected(this);
    showSnack(isConnected);
}


来源:https://stackoverflow.com/questions/44692869/internet-connectivity-causes-null-pointer-exception-in-android-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!