为什么它显示nullpointerexception?

时间:2016-01-13 06:15:35

标签: android nullpointerexception

我知道这是一个非常常见的主题,但我收到了这个错误,不知道为什么。代码在Eclipse中工作得非常好,但在Studio中按下Button键时崩溃了。我能想到的唯一区别是Request.Method而不是Eclipse中的Method。之前我认为它是因为,来自edittext的值没有得到。但它在Toast上的表现。

Error

01-13 11:13:34.242 14427-14427/com.sam.sports E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sam.sports, PID: 14427
java.lang.NullPointerException
at com.sam.sports.LoginPage.checkLogin(LoginPage.java:180)
at com.sam.sports.LoginPage.access$200(LoginPage.java:28)
at com.sam.sports.LoginPage$1.onClick(LoginPage.java:80)
at android.view.View.performClick(View.java:4562)
at android.view.View$PerformClick.run(View.java:18918)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5388)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
at dalvik.system.NativeStart.main(Native Method)
01-13 11:13:38.996 14427-14427/com.sam.sports I/Process: Sending signal. PID: 14427 SIG: 9
public class LoginPage extends AppCompatActivity {
    private static final String TAG = RegisterPage.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    String name;

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

        inputEmail = (EditText) findViewById(R.id.email_login);
        inputPassword = (EditText) findViewById(R.id.password_login);
        btnLogin = (Button) findViewById(R.id.login_btn);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinktoRegd);



        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginPage.this, HomePage.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                    //Toast.makeText(getApplicationContext(), email + "\n" + password, Toast.LENGTH_LONG ).show();
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                startActivity(new Intent(LoginPage.this, RegisterPage.class));
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    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_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    String status = jObj.getString("status");

                    // Now check status value
                    if (status.equals("0")) {

                        Toast.makeText(getApplicationContext(), "Email or Password may be incorrect! Please try again.", Toast.LENGTH_LONG).show();

                    }else if(status.equals("1")){
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        JSONObject userData = jObj.getJSONObject("userData");
                        String uid = userData.getString("id");
                        String name = userData.getString("name");
                        String email = userData.getString("email");
                        String created_at = userData.getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        startActivity(new Intent(LoginPage.this, HomePage.class));
                        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();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, 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("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();
    }



}

1 个答案:

答案 0 :(得分:0)

虽然这不是您问题的解决方案(对于下面的解决方案),但重构 checkLogin 方法肯定有助于找到错误原因。由于 checkLogin 方法很长,我将一些代码移到其他方法中。

复制它,运行它并告诉我们哪一行会引发错误。

SELECT Products.ProductID FROM Products
INER JOIN OrderDetail on OrderDetail.ProductID = Products.ProductID
GROUP BY Products.ProductID
ORDER BY COUNT(OrderDetail.Quantity)

现在找到实际解决方案:您需要将AppControler添加到Android Manifest。您可以通过在清单文件中添加以下行来执行此操作:

/**
 * function to verify login details in mysql db
 * */
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_LOGIN, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();
            checkStatus();
        }
    }, 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("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

private void checkStatus() {
    try {
        JSONObject jObj = new JSONObject(response);
        String status = jObj.getString("status");

        // Now check status value
        if (status.equals("0")) {
            processStatusZero();
        }else if(status.equals("1")){
            processStatusOne(jObj);
        } else {
            processStatusError(jObj);
        }
    } catch (JSONException e) {
        // JSON error
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

private void processStatusZero() {
    Toast.makeText(getApplicationContext(), "Email or Password may be incorrect! Please try again.", Toast.LENGTH_LONG).show();
}

private void processStatusOne(JSONObject jObj) {
    // user successfully logged in
    // Create login session
    session.setLogin(true);

    // Now store the user in SQLite
    JSONObject userData = jObj.getJSONObject("userData");
    String uid = userData.getString("id");
    String name = userData.getString("name");
    String email = userData.getString("email");
    String created_at = userData.getString("created_at");

    // Inserting row in users table
    db.addUser(name, email, uid, created_at);

    // Launch main activity
    startActivity(new Intent(LoginPage.this, HomePage.class));
    finish();
}

private void processStatusError(JSONObject jObj) {
    // Error in login. Get the error message
    String errorMsg = jObj.getString("error_msg");
    Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}

这样 AppController.getInstance()将停止返回null。