Android JSONParsing error: E / Buffer Error: Error converting result java.lang.NullPointerException: lock == null

AM is trying to send data from android to localhost but I get the following errors:

  • E / Buffer error: error conversion result java.lang.NullPointerException: lock == null
  • E / JSON Parser: error parsing data org.json.JSONException: end of input character 0 from

Below is my code for register.xml

    <ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@color/MediumVioletRed"
    tools:context=".register">
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_margin="10dp"

        >

        <ImageView
            android:id="@+id/profile"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:src="@drawable/profile"/>

        <EditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_below="@+id/profile"
            android:layout_marginTop="20dp"
            android:background="@color/White"
            android:hint="@string/name"/>
        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_below="@+id/username"
            android:layout_marginTop="20dp"
            android:background="@color/White"
            android:inputType="textEmailAddress"
            android:hint="@string/email"/>
        <EditText
            android:id="@+id/phone"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_below="@+id/email"
            android:layout_marginTop="20dp"
            android:background="@color/White"
            android:hint="@string/phone"/>
        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_below="@+id/phone"
            android:inputType="textPassword"
            android:hint="@string/password"
            android:layout_marginTop="20dp"
            android:background="@color/White"/>
        <EditText
            android:id="@+id/confirmpassword"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_below="@+id/password"
            android:layout_marginTop="20dp"
            android:inputType="textPassword"
            android:background="@color/White"
            android:hint="@string/password"
            />
        <Button
            android:id="@+id/registerbutton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/confirmpassword"
            android:text="@string/register"
            android:layout_marginTop="20dp"
            />


    </RelativeLayout>



</ScrollView>

      

Below is my register.java code

package com.bluelinktech.simon.salama;

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;

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

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


public class register extends Activity {

    JSONParser JSONPARSER = new JSONParser();

    private static String url="http://10.0.2.2/register.php";
    private static final String TAG_SUCCESS = "success";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);



        Button REGISTER   =(Button)findViewById(R.id.registerbutton);
        REGISTER.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //REGISTER NEW USER
               new RegisterNewUser().execute();

            }
        });


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_register, menu);
        return true;
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



    private class RegisterNewUser extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... args) {

            EditText NAME     =(EditText)findViewById(R.id.username);
            EditText EMAIL    =(EditText)findViewById(R.id.email);
            EditText PHONE    =(EditText)findViewById(R.id.phone);
            EditText PASSWORD =(EditText)findViewById(R.id.password);

            String name     = NAME.getText().toString();
            String email    =EMAIL.getText().toString();
            String phone    =PHONE.getText().toString();
            String password = PASSWORD.getText().toString();

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("NAME",name));
            params.add(new BasicNameValuePair("EMAIL",email));
            params.add(new BasicNameValuePair("PHONE",phone));
            params.add(new BasicNameValuePair("PASSWORD",password));

            JSONObject json = JSONPARSER.makeHttpRequest(url,"post",params);

            return null;
        }
    }
}

      

Below is my JSONParser.java code

package com.bluelinktech.simon.salama;

/**
 * Created by simon on 6/10/15.
 */
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;

    }

    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to 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 the JSON Object.
        return jObj;

    }
}

      

Below is my phpcode register.php

        <?php

    $name=$_POST['name'];
    $email=$_POST['email'];
    $phone=$_POST['phone'];
    $password=$_POST['password'];

    $link = mysqli_connect("localhost","root","java","salama");
    if($link)
    {
        echo "connected";
    }
    else
    {
        echo "could not connect";
    }

    $result=mysqli_query("INSERT INTO user(name,email,phone,password)
                                      VALUES('$name','$email','$phone','$password')");

    if($result)
    {
        echo "Registered";
    }
    else
    {
    echo "Not registered";
    }

?>

      

Please help me to solve this problem.

+3


source to share


2 answers


You have to run all EditText in onCreate method, so update your class to:

EditText NAME, EMAIL , PHONE, PASSWORD; 
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

            NAME     =(EditText)findViewById(R.id.username);
            EMAIL    =(EditText)findViewById(R.id.email);
            PHONE    =(EditText)findViewById(R.id.phone);
            PASSWORD =(EditText)findViewById(R.id.password);


        Button REGISTER   =(Button)findViewById(R.id.registerbutton);
        REGISTER.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //REGISTER NEW USER
               new RegisterNewUser().execute();

            }
        });


    }

      



AND

private class RegisterNewUser extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... args) {


            String name     = NAME.getText().toString();
            String email    =EMAIL.getText().toString();
            String phone    =PHONE.getText().toString();
            String password = PASSWORD.getText().toString();

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("NAME",name));
            params.add(new BasicNameValuePair("EMAIL",email));
            params.add(new BasicNameValuePair("PHONE",phone));
            params.add(new BasicNameValuePair("PASSWORD",password));

            JSONObject json = JSONPARSER.makeHttpRequest(url,"post",params);

            return null;
        }
    }

      

+1


source


You are probably getting an empty response from your HttpRequest, so you cannot parse it and get a null pointer exception. In my experience, I suggest you use Volley for online transactions: https://developer.android.com/training/volley/simple.html . It takes a while to set up, but it definitely performs better than HttpRequest.



0


source







All Articles