0

我正在android中制作一个简单的日志记录系统。我正在关注本教程。在测试我的应用程序时,我不断得到NullException error. 此错误在下面的这一行if(json.getString(KEY_SUCCESS) != null)LoginScreensActivity。我不知道为什么 json 为空。请帮助我我在哪里犯错。

这是我的代码

单击登录按钮时触发的功能。这是 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;
}
}

这是我的日志猫

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 
4

1 回答 1

2

您的问题的根本原因是 UnknownHostException,似乎emailEditText 没有链接到有效的 URL,该 URL 返回json导致 NullPointerException 的空值。

你在输入email什么?

添加

明确地说,教程代码:

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

仅检查从 getString() 返回的字符串是否不为空。在你的情况下json是 null 所以你需要这样的测试:

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 指向你的服务器和路径。

于 2012-05-26T17:27:58.530 回答