尝试在空对象引用上调用虚拟方法'void SessionManager.setLogin(boolean)' 对话框中出错



我正试图在Dialog中像这样使用这个好的教程用于Login action:

public class MainActivity extends AppCompatActivity {
    private SQLiteHandler db;
    public ProgressDialog pDialog;
    public SessionManager session;
    private DrawerLayout drawerLayout;
    private static final String TAG = MainActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Displaying the user details on the screen
        TextView txtName = (TextView) findViewById(R.id.usernamehd);
        TextView txtEmail = (TextView) findViewById(R.id.emailuserr);
        db = new SQLiteHandler(getApplicationContext());
        HashMap<String, String> user = db.getUserDetails();
        String name = user.get("name");
        String email = user.get("email");
        txtName.setText(name);
        txtEmail.setText(email);

        TextView sgnin = (TextView) findViewById(R.id.signinbtn);
        sgnin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Dialog d = new Dialog(MainActivity.this);
                d.setContentView(R.layout.dialog);
                String title = getResources().getString(R.string.dialog_title);
                d.setTitle(title);
                d.show();
                // first dialog for showing that dialog Login-register
                final EditText inusremail = (EditText) d.findViewById(R.id.emailuserr);
                final EditText inpass = (EditText) d.findViewById(R.id.passworduser);
                final Button btnLogin = (Button) d.findViewById(R.id.Login);
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setCancelable(false);
                btnLogin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String email = inusremail.getText().toString();
                        String password = inpass.getText().toString();
                        if (email.trim().length() > 0 && password.trim().length() > 0) {
                            checkLogin(email, password);
                        } else {
                            Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
                        }
                    }
                });
                                                //end the Login button
            }
        });

这是CheckLogin:的函数

private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";
        pDialog.setMessage("Logging in ...");
        showDialog();
        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_REGISTER, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();
                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);
                        // Launch main activity
                        Intent intent = new Intent(MainActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("tag", "login");
                params.put("email", email);
                params.put("password", password);
                return params;
            }
        };
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }
    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }
    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

但是,有一个问题,我不知道是什么:

java.lang.NullPointerException: Attempt to invoke virtual method 'void client.package.helper.SessionManager.setLogin(boolean)' on a null object reference
            at client.package.MainActivity$6.onResponse(MainActivity.java:257)
            at client.package.MainActivity$6.onResponse(MainActivity.java:242)
            at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
            at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
            at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

i just change the package name

当然,Register正在工作,我可以将用户凭据保存在服务器端,但这也有类似的问题,我不知道如何在一个Acttivity中解决这个问题。

任何帮助都会很棒。

session.setLogin(true);

您必须确保session已初始化。。

要格外小心:

if(session!=null)
  session.setLogin(true);

错误显示SessionManager的Object为null。您尚未在声明后初始化对象。

SessionManager session; //declared

session = New SessionManager(Arguments); //Intialized

最新更新