java - Android JSONParser 中的 NullPointerException

标签 java android nullreferenceexception

我有一个 Android 应用程序,每当我按下登录按钮时就会崩溃;我的 JSONParser 中不断出现空指针异常。我真心希望你能帮忙。

这是我的 UserFunctions.java:

package com.example.sabre9.library;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;

public class UserFunctions {

    private JSONParser jsonParser;

    // Testing in localhost using wamp or xampp 
    // use http://10.0.2.2/ to connect to your localhost ie http://localhost/
    private static String loginURL = "http://10.0.2.2/Sabre1/";
    //private static String registerURL = "http://10.0.2.2/Sabre1/";

    private static String login_tag = "login";
    //private static String register_tag = "register";

    // constructor
    public UserFunctions(){
        jsonParser = new JSONParser();
    }

    /**
     * function make Login Request
     * @param email
     * @param password
     * */
    public JSONObject loginUser(String email, String password){
        // Building Parameters
        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.makeHttpRequest(loginURL, "POST", params);
        // return json
        // Log.e("JSON", json.toString());
        return json;
    }

    /**
     * function make Register Request
     * @param name
     * @param email
     * @param password
     * */
    /*
    public JSONObject registerUser(String name, String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", register_tag));
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));


        //getting JSON Object
        JSONObject json = jsonParser.makeHttpRequest(registerURL, "POST", params);
        // return json
        return json;
    }*/

    /**
     * Function get Login status
     **/
    public boolean isUserLoggedIn(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        int count = db.getRowCount();
        if(count > 0){
            // user logged in
            return true;
        }
        return false;
    }

    /**
     * Function to logout user
     * Reset Database
     * */
    public boolean logoutUser(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        db.resetTables();
        return true;
    }
}

JSONParser.java:

package com.example.sabre9.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";

        // constructor
        public JSONParser() {

        }

        // function get json from url
        // by making HTTP POST or GET mehtod
        public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

                // Making HTTP request
                try {

                        // check for request method
                        if(method == "POST"){
                                // request method is POST
                                // defaultHttpClient
                                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();

                        }else if(method == "GET"){
                                // request method is GET
                                DefaultHttpClient httpClient = new DefaultHttpClient();
                                String paramString = URLEncodedUtils.format(params, "utf-8");
                                url += "?" + paramString;
                                HttpGet httpGet = new HttpGet(url);

                                HttpResponse httpResponse = httpClient.execute(httpGet);
                                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();
                } catch (Exception e) {
                        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 JSON String
                return jObj;

        }
}

这是我的 logcat 错误:

02-13 03:15:01.921: E/Buffer Error(1263):   Error converting result java.lang.NullPointerException: lock == null
02-13 03:15:01.931: E/JSON Parser(1263):    Error parsing data org.json.JSONException: End of input at character 0 of 
02-13 03:15:02.891: E/Buffer Error(1263):   Error converting result java.lang.NullPointerException: lock == null
02-13 03:15:02.891: E/JSON Parser(1263):    Error parsing data org.json.JSONException: End of input at character 0 of 

编辑:我的LoginActivity.java:

package com.example.sabre9;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.sabre9.library.DatabaseHandler;
import com.example.sabre9.library.UserFunctions;

public class LoginActivity extends Activity {
    Button btnLogin;
    //Button btnLinkToRegister;
    EditText inputEmail;
    EditText inputPassword;
    TextView loginErrorMsg;

    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    //private static String KEY_ERROR = "error";
    //private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";

    private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {

        protected JSONObject doInBackground(String... params) {
                UserFunctions userFunction = new UserFunctions();
                if (params.length != 2)
                        return null;
                JSONObject json = userFunction.loginUser(params[0], params[1]);
                return json;
        }

        protected void onPostExecute(JSONObject json) {
                try {
            if (json != null && json.getString(KEY_SUCCESS) != null) {
                loginErrorMsg.setText("");
                String res = json.getString(KEY_SUCCESS);
                if(Integer.parseInt(res) == 1){
                    // user successfully logged in
                    // Store user details in SQLite Database
                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    JSONObject json_user = json.getJSONObject("user");

                    // Clear all previous From in database
                    UserFunctions userFunction = new UserFunctions();
                    userFunction.logoutUser(getApplicationContext());
                    db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        

                    // Launch Main Screen
                    Intent main = new Intent(getApplicationContext(), MainActivity.class);

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

                    // Close Login Screen
                    finish();
                }else{
                    // Error in login
                    loginErrorMsg.setText("Incorrect username/password");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        }
}

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

        // Importing all assets like buttons, text fields
        inputEmail = (EditText) findViewById(R.id.loginEmail);
        inputPassword = (EditText) findViewById(R.id.loginPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        //btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
        loginErrorMsg = (TextView) findViewById(R.id.login_error);

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

            public void onClick(View view) {
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();                
                new MyAsyncTask().execute(email, password);
            }

        });

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

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });*/
    }
}

最佳答案

您的 java.lang.NullPointerException: lock == null 发生 >= Android 3.0,因为主 (UI) 线程上不允许联网,除非通过 StrictMode 策略覆盖。尝试:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

请注意,因此,httpClient.execute(httpPost); 会在等待响应时严重锁定系统。 (相反,您可以在 AsyncTask 中执行此操作,这样它就不会锁定主线程。)希望这会有所帮助。

关于java - Android JSONParser 中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21748885/

相关文章:

c# - httpcontext.current.server.mappath 对象引用未设置为对象的实例

Java上的kill方法

java - Java 中的 Tic Tac Toe

java - 单击信息窗口 Google Maps V2 的监听器

用于 Android 调试的 Android Studio 和 Visual Studio 模拟器

android - 与 Android 4.4.4 相比,通用图像加载器库在 Android 5.0 上运行缓慢

Java 突然停止写入 ArrayList

android - 如何像imageview一样裁剪位图中心?

c# - Entity Framework 5 线程敏捷性

c# - 我是怎么在构造函数之后在这里得到这个 NullReferenceException 错误的?