php - Android JSONParsing 错误 : E/Buffer Error﹕ Error converting result java. lang.NullPointerException: lock == null

标签 php android json

AM 尝试将数据从 android 发送到本地主机,但出现以下错误:

  1. E/Buffer Error:转换结果时出错java.lang.NullPointerException: lock == null
  2. E/JSON 解析器:解析数据时出错 org.json.JSONException: End of input at character 0 of

下面是我的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>

下面是我的register.java代码

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

下面是我的JSONParser.java代码

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;

    }
}

下面是我的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";
    }

?>

请帮我解决这个问题。

最佳答案

您必须在 onCreate 方法上初始化所有 EditText,因此请将您的类更新为:

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();

            }
        });


    }

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

关于php - Android JSONParsing 错误 : E/Buffer Error﹕ Error converting result java. lang.NullPointerException: lock == null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30782381/

相关文章:

mysql - 将 MySQL 结果集转换为单个 JSON OBJECT(MySQL 数据类型)

json - 如何在 MonetDB 中使用 JSON

javascript - 如何在 php 代码中使用 jQuery 变量?

php - 如何正确存储注册用户和大会其他参与者所需的信息? (方案 1 有效,但方案 2 和 3 无效)

android - 关闭 DefaultItemizedOverlay 的阴影

android - 创建一个 Android GPS 跟踪应用程序

javascript - 是否有可能利用网络技术构建家庭自动化系统?

php - 如何使用 PHP Wordpress 将沙箱 Paypal 返回值插入 MySQL 表?

android - 对数山图

json - 如何在 D3.js 中动态显示多行文本?