本文介绍了Android的显示java.lang.NullPointerException:锁== NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了下面的错误。显示java.lang.NullPointerException:锁== NULL而来自server.I得到JSON文件一派,但不能找到这个任何解决方案。我使用WAMP服务器,MySQL和PHP连接到我的数据库,但是当我尝试注册我得到下面的错误。

我已经在网上189和232这是在块报价突出了错误的。你能帮我什么是错的这些行。

错误日志

  -04 19:41:08.572 2414年至2481年/ com.brad.visor E /缓存器的错误:错误转换结果显示java.lang.NullPointerException:锁== NULL
07-04 19:41:08.572 2414年至2481年/ com.brad.visor E / JSON解析器:错误解析数据org.json.JSONException:在字符输入0结束
07-04 19:41:08.602 2414年至2414年/ com.brad.visor E / AndroidRuntime:致命异常:主要
    工艺:com.brad.visor,PID:2414
    显示java.lang.NullPointerException:试图调用虚拟方法java.lang.String中org.json.JSONObject.getString(java.lang.String中)一空对象引用
            在com.brad.visor.Register $ ProcessRegister.onPostExecute(Register.java:232)
            在com.brad.visor.Register $ ProcessRegister.onPostExecute(Register.java:189)
            在android.os.AsyncTask.finish(AsyncTask.java:636)
            在android.os.AsyncTask.access $ 500(AsyncTask.java:177)
            在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:653)
            在android.os.Handler.dispatchMessage(Handler.java:102)
            在android.os.Looper.loop(Looper.java:135)
            在android.app.ActivityThread.main(ActivityThread.java:5257)
            在java.lang.reflect.Method.invoke(本机方法)
            在java.lang.reflect.Method.invoke(Method.java:372)
            在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903)
            在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Register.java文件

 公共类注册扩展活动{
    / **
     * JSON响应节点名称。
     ** /
    私人静态字符串KEY_SUCCESS =成功;
    私人静态字符串KEY_UID =UID;
    私人静态字符串KEY_FIRSTNAME =FNAME;
    私人静态字符串KEY_LASTNAME =LNAME;
    私人静态字符串KEY_USERNAME =的uname;
    私人静态字符串KEY_EMAIL =电子邮件;
    私人静态字符串KEY_CREATED_AT =created_at;
    私人静态字符串KEY_ERROR =错误;    / **
     *定义布局项目。
     ** /    的EditText inputFirstName;
    的EditText inputLastName;
    的EditText inputUsername;
    的EditText inputEmail;
    的EditText控件inputPassword;
    按钮btnRegister;
    TextView的registerErrorMsg;
    / **
     *当第一次创建活动调用。
     * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.register);        / **
         *定义所有版面项目
         ** /
        inputFirstName =(EditText上)findViewById(R.id.fname);
        inputLastName =(EditText上)findViewById(R.id.lname);
        inputUsername =(EditText上)findViewById(R.id.uname);
        inputEmail =(EditText上)findViewById(R.id.email);
        控件inputPassword =(EditText上)findViewById(R.id.pword);
        btnRegister =(按钮)findViewById(R.id.register);
        registerErrorMsg =(的TextView)findViewById(R.id.register_error);/ **
 *它切换回登录屏幕上点击按钮
                ** /                按钮登录=(按钮)findViewById(R.id.bktologin);
                login.setOnClickListener(新View.OnClickListener(){
                    公共无效的onClick(查看视图){
                意图myIntent =新意图(view.getContext(),Login.class);
                startActivityForResult(myIntent,0);
                完();
            }        });        / **
         *注册按钮的Click事件。
         *一个敬酒时设置字段为空,以提醒。
         *另一个敬酒被设置为提醒用户名必须是5个字符。
         ** /        btnRegister.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(查看视图){                !。如果((inputUsername.getText()的toString()等于())及及(inputPassword.getText()的toString()等于(!。))及&放大器;!(inputFirstName。的getText()的toString()等于())及和放大器;的toString()等于(inputLastName.getText(!)。())及和放大器;的toString((inputEmail.getText(!)。 )。等于()) )
                {
                    如果(。inputUsername.getText()的toString()长度()→4){
                        NetAsync(视图);                    }
                    其他
                    {
                        Toast.makeText(getApplicationContext(),
                                用户名应该是最少5个字符,Toast.LENGTH_SHORT).show();
                    }
                }
                其他
                {
                    Toast.makeText(getApplicationContext(),
                            一个或多个字段为空,Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    / **
     *异步任务来检查网络连接是否正常工作
     ** /    私有类NetCheck扩展的AsyncTask<字符串,字符串,布尔值>
    {
        私人ProgressDialog nDialog;        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            nDialog =新ProgressDialog(Register.this);
            nDialog.setMessage(中..);
            nDialog.setTitle(检查网络);
            nDialog.setIndeterminate(假);
            nDialog.setCancelable(真);
            nDialog.show();
        }        @覆盖
        保护布尔doInBackground(字符串参数... args){
/ **
 *获取工作通过尝试谷歌的互联网连接当前的设备状态和检查。
 ** /
            ConnectivityManager厘米=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            NetInfo的的NetworkInfo = cm.getActiveNetworkInfo();
            如果(NetInfo的= NULL&放大器;!&安培; netInfo.isConnected()){
                尝试{
                    网址URL =新的URL(http://www.google.com);
                    HttpURLConnection的urlc =(HttpURLConnection类)url.openConnection();
                    urlc.setConnectTimeout(3000);
                    urlc.connect();
                    如果(urlc.getResponse code()== 200){
                        返回true;
                    }
                }赶上(MalformedURLException的E1){
                    // TODO自动生成catch块
                    e1.printStackTrace();
                }赶上(IOException异常五){
                    // TODO自动生成catch块
                    e.printStackTrace();
                }
            }
            返回false;        }
        @覆盖
        保护无效onPostExecute(布尔日){            如果(日==真){
                nDialog.dismiss();
                新ProcessRegister()执行();
            }
            其他{
                nDialog.dismiss();
                registerErrorMsg.setText(网络连接错误);
            }
        }
    }

        /**
         * Defining Process dialog
         **/
        private ProgressDialog pDialog;

        String email,password,fname,lname,uname;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            inputUsername = (EditText) findViewById(R.id.uname);
            inputPassword = (EditText) findViewById(R.id.pword);
            fname = inputFirstName.getText().toString();
            lname = inputLastName.getText().toString();
            email = inputEmail.getText().toString();
            uname= inputUsername.getText().toString();
            password = inputPassword.getText().toString();
            pDialog = new ProgressDialog(Register.this);
            pDialog.setTitle("Contacting Servers");
            pDialog.setMessage("Registering ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected JSONObject doInBackground(String... args) {


            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);

            return json;


        }
        @Override
        protected void onPostExecute(JSONObject json) {
            /**
             * Checks for success message.
             **/
            try {
                    registerErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS);

                    String red = json.getString(KEY_ERROR);

                    if(Integer.parseInt(res) == 1){
                        pDialog.setTitle("Getting Data");
                        pDialog.setMessage("Loading Info");

                        registerErrorMsg.setText("Successfully Registered");


                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        /**
                         * Removes all the previous data in the SQlite database
                         **/

                        UserFunctions logout = new UserFunctions();
                        logout.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
                        /**
                         * Stores registered data in SQlite Database
                         * Launch Registered screen
                         **/

                        Intent registered = new Intent(getApplicationContext(), Registered.class);

                        /**
                         * Close all views before launching Registered screen
                         **/
                        registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        pDialog.dismiss();
                        startActivity(registered);


                        finish();
                    }

                    else if (Integer.parseInt(red) ==2){
                        pDialog.dismiss();
                        registerErrorMsg.setText("User already exists");
                    }
                    else if (Integer.parseInt(red) ==3){
                        pDialog.dismiss();
                        registerErrorMsg.setText("Invalid Email id");
                    }

                }


                else{
                    pDialog.dismiss();

                    registerErrorMsg.setText("Error occured in registration");
                }

            } catch (JSONException e) {
                e.printStackTrace();


            }
        }}
    public void NetAsync(View view){
        new NetCheck().execute();
    }}

Manifest.java File

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.brad.visor" >

    <application
        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login">
        </activity>
        <activity

            android:name=".Register">
        </activity>
        <activity
            android:name=".Registered">
        </activity>
        <activity
            android:name=".Main">
        </activity>
        <activity
            android:name=".PasswordReset">
        </activity>
        <activity
            android:name=".ChangePassword">
        </activity>
    </application>

    <!-- Allow to connect with internet and to know the current network state-->

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


</manifest>

Userfunction.java Code

public class UserFunctions {

    private JSONParser jsonParser;

    //URL of the PHP API
    private static String loginURL =    "http://192.168.0.3:8080/bradvisor_login_api/";
    private static String registerURL = "http://192.168.0.3:8080/bradvisor_login_api/";
    private static String forpassURL =  "http://192.168.0.3:8080/bradvisor_login_api/";
    private static String chgpassURL =  "http://192.168.0.3:8080/bradvisor_login_api/";

    private static String login_tag = "login";
    private static String register_tag = "register";
    private static String forpass_tag = "forpass";
    private static String chgpass_tag = "chgpass";


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

    /**
     * Function to Login
     **/

    public JSONObject loginUser(String email, String password){
        // Building Parameters
        List params = new ArrayList();
        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);
        return json;
    }

    /**
     * Function to change password
     **/

    public JSONObject chgPass(String newpas, String email){
        List params = new ArrayList();
        params.add(new BasicNameValuePair("tag", chgpass_tag));

        params.add(new BasicNameValuePair("newpas", newpas));
        params.add(new BasicNameValuePair("email", email));
        JSONObject json = jsonParser.getJSONFromUrl(chgpassURL, params);
        return json;
    }

    /**
     * Function to reset the password
     **/

    public JSONObject forPass(String forgotpassword){
        List params = new ArrayList();
        params.add(new BasicNameValuePair("tag", forpass_tag));
        params.add(new BasicNameValuePair("forgotpassword", forgotpassword));
        JSONObject json = jsonParser.getJSONFromUrl(forpassURL, params);
        return json;
    }

    /**
     * Function to  Register
     **/
    public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
        // Building Parameters
        List params = new ArrayList();
        params.add(new BasicNameValuePair("tag", register_tag));
        params.add(new BasicNameValuePair("fname", fname));
        params.add(new BasicNameValuePair("lname", lname));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("uname", uname));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.getJSONFromUrl(registerURL,params);
        return json;
    }

    /**
     * Function to logout user
     * Resets the temporary data stored in SQLite Database
     * */
    public boolean logoutUser(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        db.resetTables();
        return true;
    }

}

JsonPraser.java File

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List params) {

        // Making HTTP request
        try {
            // 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();

        } 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) {
            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;

    }
解决方案

You can call Async Task from within another Async Task. Problem is in RegisteredUser Function.

这篇关于Android的显示java.lang.NullPointerException:锁== NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:09