-1

I got following error. java.lang.NullPointerException: lock == null while get json file from server.I googled but cant find any solution for this. I am using wamp server, mysql and php to connect to my database, however when I try to register I get the below error.

I have highlighted both of error on line 189 and 232 which are in block quotes. could you please help me with what is wrong with these lines.

Error Log

    -04 19:41:08.572    2414-2481/com.brad.visor E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
07-04 19:41:08.572    2414-2481/com.brad.visor E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
07-04 19:41:08.602    2414-2414/com.brad.visor E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.brad.visor, PID: 2414
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
            at com.brad.visor.Register$ProcessRegister.onPostExecute(Register.java:232)
            at com.brad.visor.Register$ProcessRegister.onPostExecute(Register.java:189)
            at android.os.AsyncTask.finish(AsyncTask.java:636)
            at android.os.AsyncTask.access$500(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Register.java File

public class Register extends Activity {


    /**
     *  JSON Response node names.
     **/


    private static String KEY_SUCCESS = "success";
    private static String KEY_UID = "uid";
    private static String KEY_FIRSTNAME = "fname";
    private static String KEY_LASTNAME = "lname";
    private static String KEY_USERNAME = "uname";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";
    private static String KEY_ERROR = "error";

    /**
     * Defining layout items.
     **/

    EditText inputFirstName;
    EditText inputLastName;
    EditText inputUsername;
    EditText inputEmail;
    EditText inputPassword;
    Button btnRegister;
    TextView registerErrorMsg;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        /**
         * Defining all layout items
         **/
        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 = (Button) findViewById(R.id.register);
        registerErrorMsg = (TextView) findViewById(R.id.register_error);



/**
 * Button which Switches back to the login screen on clicked
                **/

                Button login = (Button) findViewById(R.id.bktologin);
                login.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), Login.class);
                startActivityForResult(myIntent, 0);
                finish();
            }

        });

        /**
         * Register Button click event.
         * A Toast is set to alert when the fields are empty.
         * Another toast is set to alert Username must be 5 characters.
         **/

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (  ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
                {
                    if ( inputUsername.getText().toString().length() > 4 ){
                        NetAsync(view);

                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(),
                                "Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(),
                            "One or more fields are empty", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    /**
     * Async Task to check whether internet connection is working
     **/

    private class NetCheck extends AsyncTask<String,String,Boolean>
    {
        private ProgressDialog nDialog;

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            nDialog = new ProgressDialog(Register.this);
            nDialog.setMessage("Loading..");
            nDialog.setTitle("Checking Network");
            nDialog.setIndeterminate(false);
            nDialog.setCancelable(true);
            nDialog.show();
        }

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


/**
 * Gets current device state and checks for working internet connection by trying Google.
 **/
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnected()) {
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(3000);
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return false;

        }
        @Override
        protected void onPostExecute(Boolean th){

            if(th == true){
                nDialog.dismiss();
                new ProcessRegister().execute();
            }
            else{
                nDialog.dismiss();
                registerErrorMsg.setText("Error in Network Connection");
            }
        }
    }
        private class ProcessRegister extends AsyncTask<String, String, JSONObject> { // Error Here
        /**
         * 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 {

if (json.getString(KEY_SUCCESS) != null) { //Error here

                    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;

    }
5
  • Possibly relevant threads: stackoverflow.com/a/8214974/535871 and stackoverflow.com/questions/8740381/… Commented Jul 5, 2015 at 19:52
  • Both of them are unhelpful, could you please help me I got the code from learn2crack.com/2013/08/… and you can downloald the source file to look at the code, however mine is not working for some reason could you please help. Commented Jul 5, 2015 at 19:55
  • I'm going to tell you the same thing that those posts say: most likely there's a problem with the JSON coming back from the server (in particular, the response appears to be empty).That's causing the JSONException which is then causing the NullPointerException (and possibly other problems). The empty response problem may be caused by a problem on the server side or in how you are setting up the request. Commented Jul 5, 2015 at 20:00
  • I dont think that their is any problems with the database connection, however could you please rewrite or help as those post are all not useful. Commented Jul 5, 2015 at 20:02
  • The best way to diagnose this is to set a breakpoint inside getJSONFromUrl on the line that calls httpClient.execute(httpPost). Then examine the contents of the httpPost entity and determine exactly what's being sent to the server in the request. (You could also insert a line ((UrlEncodedFormEntity) httpPost.getEntity).writeTo(System.out); to see in logcat what's being sent.) If all looks good, then test whether you are indeed receiving the expected response. (I did notice a bug: your reading loop should be appending line + "\n", not line + "n".) Commented Jul 5, 2015 at 20:18

3 Answers 3

0

The problem seems to be that doInBackground is returning null. Thus, when onPostExecute runs, the argument json is null. To avoid an exception, test whether json is null before proceeding with the rest of the logic. You'll probably have to find out why userFunction.registerUser(...) is returning null to truly fix the problem.

Sign up to request clarification or add additional context in comments.

9 Comments

Ted How do I test weather json is null, I am new too android studio. I normally use eclipse.
With a simple if (json == null) { ... } statement. The body of the if might log an error message and return, or do something else. The important thing is to avoid executing json.getString() whenever json is null.
could you edit the code for me
@james - Come on. You can figure this little bit out yourself. Just insert something like this at the very beginning of onPostExecute: if (json == null) { Log.e("ProcessRegister", "json was null!"); return; }. You might also want to throw up a Toast until you figure out the real problem.
Ted once I have added this into the code I am now getting the same error plus one more error 07-05 19:12:02.771 2394-2436/com.brad.visor E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null 07-05 19:12:02.771 2394-2436/com.brad.visor E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of 07-05 19:12:02.815 2394-2394/com.brad.visor E/ProcessRegister﹕ json was null!
|
0

in userFunction.registerUser ( as your refisterUser function returned a JsonObject), better to check the returned String before converting it to Json as

add a check as

if(returnedString == null || returnedString == "null") { return; }

9 Comments

also share code userFunction.registerUser(...) of function, problem is in this function.
When adding this in I am getting an error, could you please rewrite the code for me with the added part as II am getting error it is not recognising returnedstring
share userFunction.registerUser(...) code
returnedString is the response that you read, you may be using another variable for this, I just wrote you, so that you can get an idea, the real problem is in your registerUser() function,
I have added my userfuction.java and Jsonparser.java file. These two are library files.
|
0

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

6 Comments

the solution to your problem is, chek your Network Connectivity, when you perform ClickEvent on Button, and after parsing all your data, then call new ProcessRegister().execute();
Could you please advise or rewrite the code for me
My internet connection is strong and its connected to my database which I am using wamp server, when I try to register users I get the above errors. could you please advise.
Where did you get the idea that an AsyncTask cannot initiate another AsyncTask? That's simply wrong.
its not matter of Strong Internet Connectivity, its matter of Rules, You are calling Async Task from within another, thats problem.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.