简单登录应用程序中出现Null Exception错误

时间:2012-05-26 17:19:42

标签: java android

我正在android中创建一个简单的日志系统。我正在关注这个tutorial。在测试我的应用时,我不断获得NullException error。此错误位于if(json.getString(KEY_SUCCESS) != null)下方的LoginScreensActivity行。我不知道为什么json是null。请帮帮我,我在哪里弄错了。

这是我的代码

单击登录按钮时触发的功能。这是LoginScreensActivity.java类

btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.loginUser(email,password);

            try {
                if(json.getString(KEY_SUCCESS) != null) {
                    loginErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS);
                    if(Integer.parseInt(res) == 1) {
                        Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);

                        // Close all views before launching Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);

                        // Close Login Screen
                        finish();
                    }
                } else {
                    Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

在上面的代码中触发的loginUSer函数

public JSONObject loginUser(String email, String password) {
    //Toast.makeText(context, "loginUser function", Toast.LENGTH_LONG).show();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));

    JSONObject json = jsonParser.getJSONFromUrl(loginUrl, params);
    //Log.e("JSON", json.toString());
    //Log.d("TAG", json.toString());
    return json;
}

这是我的JSONPareser类

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;

        while((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }

        is.close();
        json = sb.toString();
        Log.e("JSON",json);
    } catch (Exception e) {
        //e.printStackTrace();
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;
}
}

这是我的logcat

05-26 20:16:52.658: I/Process(31217): Sending signal. PID: 31217 SIG: 9
05-26 20:16:59.793: D/dalvikvm(31361): GC_EXTERNAL_ALLOC freed 41K, 50% free 2725K/5379K, external 0K/0K, paused 31ms
05-26 20:16:59.843: D/dalvikvm(31361): GC_EXTERNAL_ALLOC freed 7K, 50% free 2743K/5379K, external 455K/518K, paused 32ms
05-26 20:16:59.973: D/CLIPBOARD(31361): Hide Clipboard dialog at Starting input: finished by someone else... !
05-26 20:17:06.883: W/System.err(31361): java.net.UnknownHostException: zafarsaleem.info
05-26 20:17:06.883: W/System.err(31361):    at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
05-26 20:17:06.883: W/System.err(31361):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
05-26 20:17:06.883: W/System.err(31361):    at java.net.InetAddress.getAllByName(InetAddress.java:256)
05-26 20:17:06.883: W/System.err(31361):    at    org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
05-26 20:17:06.883: W/System.err(31361):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-26 20:17:06.883: W/System.err(31361):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-26 20:17:06.883: W/System.err(31361):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
05-26 20:17:06.883: W/System.err(31361):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-26 20:17:06.888: W/System.err(31361):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-26 20:17:06.888: W/System.err(31361):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-26 20:17:06.888: W/System.err(31361):    at library.JSONParser.getJSONFromUrl(JSONParser.java:38)
05-26 20:17:06.888: W/System.err(31361):    at library.UserFunctions.loginUser(UserFunctions.java:37)
05-26 20:17:06.888: W/System.err(31361):    at com.zafar.loginscreens.LoginScreensActivity$1.onClick(LoginScreensActivity.java:48)
05-26 20:17:06.888: W/System.err(31361):    at android.view.View.performClick(View.java:2538)
05-26 20:17:06.888: W/System.err(31361):    at android.view.View$PerformClick.run(View.java:9152)
05-26 20:17:06.888: W/System.err(31361):    at android.os.Handler.handleCallback(Handler.java:587)
05-26 20:17:06.888: W/System.err(31361):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-26 20:17:06.888: W/System.err(31361):    at android.os.Looper.loop(Looper.java:130)
05-26 20:17:06.888: W/System.err(31361):    at android.app.ActivityThread.main(ActivityThread.java:3691)
05-26 20:17:06.888: W/System.err(31361):    at java.lang.reflect.Method.invokeNative(Native Method)
05-26 20:17:06.888: W/System.err(31361):    at java.lang.reflect.Method.invoke(Method.java:507)
05-26 20:17:06.888: W/System.err(31361):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
05-26 20:17:06.888: W/System.err(31361):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
05-26 20:17:06.888: W/System.err(31361):    at dalvik.system.NativeStart.main(Native Method)
05-26 20:17:06.893: E/Buffer Error(31361): Error converting result java.lang.NullPointerException
05-26 20:17:06.893: E/JSON Parser(31361): Error parsing data org.json.JSONException: End of input at character 0 of 
05-26 20:17:06.893: D/AndroidRuntime(31361): Shutting down VM
05-26 20:17:06.893: W/dalvikvm(31361): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
05-26 20:17:06.893: E/AndroidRuntime(31361): FATAL EXCEPTION: main
05-26 20:17:06.893: E/AndroidRuntime(31361): java.lang.NullPointerException
05-26 20:17:06.893: E/AndroidRuntime(31361):    at com.zafar.loginscreens.LoginScreensActivity$1.onClick(LoginScreensActivity.java:51)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at android.view.View.performClick(View.java:2538)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at android.view.View$PerformClick.run(View.java:9152)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at android.os.Handler.handleCallback(Handler.java:587)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at android.os.Looper.loop(Looper.java:130)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at android.app.ActivityThread.main(ActivityThread.java:3691)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at java.lang.reflect.Method.invokeNative(Native Method)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at java.lang.reflect.Method.invoke(Method.java:507)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
05-26 20:17:06.893: E/AndroidRuntime(31361):    at dalvik.system.NativeStart.main(Native Method)

更新

添加if(json != null && json.getString(KEY_SUCCESS) != null) {后,我得到以下logcat

05-26 20:44:46.243: W/System.err(32680): java.net.UnknownHostException: zafarsaleem.info
05-26 20:44:46.243: W/System.err(32680):    at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
05-26 20:44:46.243: W/System.err(32680):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
05-26 20:44:46.243: W/System.err(32680):    at java.net.InetAddress.getAllByName(InetAddress.java:256)
05-26 20:44:46.248: W/System.err(32680):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
05-26 20:44:46.248: W/System.err(32680):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-26 20:44:46.248: W/System.err(32680):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-26 20:44:46.248: W/System.err(32680):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
05-26 20:44:46.248: W/System.err(32680):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-26 20:44:46.248: W/System.err(32680):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-26 20:44:46.248: W/System.err(32680):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-26 20:44:46.248: W/System.err(32680):    at library.JSONParser.getJSONFromUrl(JSONParser.java:38)
05-26 20:44:46.248: W/System.err(32680):    at library.UserFunctions.loginUser(UserFunctions.java:37)
05-26 20:44:46.248: W/System.err(32680):    at com.zafar.loginscreens.LoginScreensActivity$1.onClick(LoginScreensActivity.java:49)
05-26 20:44:46.248: W/System.err(32680):    at android.view.View.performClick(View.java:2538)
05-26 20:44:46.248: W/System.err(32680):    at android.view.View$PerformClick.run(View.java:9152)
05-26 20:44:46.248: W/System.err(32680):    at android.os.Handler.handleCallback(Handler.java:587)
05-26 20:44:46.248: W/System.err(32680):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-26 20:44:46.248: W/System.err(32680):    at android.os.Looper.loop(Looper.java:130)
05-26 20:44:46.248: W/System.err(32680):    at android.app.ActivityThread.main(ActivityThread.java:3691)
05-26 20:44:46.248: W/System.err(32680):    at java.lang.reflect.Method.invokeNative(Native Method)
05-26 20:44:46.248: W/System.err(32680):    at java.lang.reflect.Method.invoke(Method.java:507)
05-26 20:44:46.248: W/System.err(32680):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
05-26 20:44:46.248: W/System.err(32680):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
05-26 20:44:46.248: W/System.err(32680):    at dalvik.system.NativeStart.main(Native Method)
05-26 20:44:46.248: E/Buffer Error(32680): Error converting result java.lang.NullPointerException
05-26 20:44:46.248: E/JSON Parser(32680): Error parsing data org.json.JSONException: End of input at character 0 of 

1 个答案:

答案 0 :(得分:2)

麻烦的根本原因是UnknownHostException,似乎email EditText没有链接到有效的URL,该URL返回json的空值,导致NullPointerException。

你在email进入了什么?

<强>加成

明确地说,教程代码:

if(json.getString(KEY_SUCCESS) != null) {

仅检查从getString()返回的String是否为空。在您的情况下,json为空,因此您需要进行如下测试:

if(json != null && json.getString(KEY_SUCCESS) != null) {

检测空指针并优雅地退出应用程序。

添加2

正如用户功能类所述,如果您的服务器是在线托管的,则需要在UserFunctions类中更改这些代码行:

private static String loginURL = "http://10.0.2.2/ah_login_api/";
private static String registerURL = "http://10.0.2.2/ah_login_api/";

如果您是Stack Overflow,您可以尝试类似:

private static String loginURL = "http://www.stackoverflow.com/ah_login_api/";
private static String registerURL = "http://www.stackoverflow.com/ah_login_api/";

但您不是Stack Overflow,当然,您需要将这些URL指向您的服务器和路径。