JSON Parser:解析数据时出错org.json.JSONException:

时间:2016-08-21 11:00:41

标签: javascript java android json parsing

我在android studio中有这个错误:

  

E / Buffer Error:转换结果时出错   java.lang.NullPointerException:lock == null E / JSON Parser:Error   解析数据org.json.JSONException:

的字符0处的输入结束

我的代码是add_student.java

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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 add_student extends AppCompatActivity {
   Button add;
    EditText name, phone, email;
    String jname, jphone, jemail;

    int value;
    JSONParser jsonParser;
    ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_student);
        add=(Button)findViewById(R.id.add);
        name=(EditText)findViewById(R.id.name);
        email=(EditText)findViewById(R.id.email);
        phone=(EditText)findViewById(R.id.phone);
        jsonParser=new JSONParser();
       jname=name.getText().toString();
         jphone=phone.getText().toString();
         jemail=email.getText().toString();


        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AddStudentTask().execute();
            }
        });

    }


    class AddStudentTask extends AsyncTask<String,String,String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog=new ProgressDialog(add_student.this);
            progressDialog.setTitle("Wait...");
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {

            List<NameValuePair> list= new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("Name",jname));
            list.add(new BasicNameValuePair("Mobile",jphone));
            list.add(new BasicNameValuePair("Email",jemail));

            JSONObject jsonObject=jsonParser.makeHttpRequest("http://10.0.2.2/billapp/add_student.php","POST",list);

            try{
                if(jsonObject!=null && !jsonObject.isNull("value")){
                    value=jsonObject.getInt("value");
                }else{
                    value=0;
                }

            }catch (Exception e){
                Log.d("ERROR",e.getMessage());
            }

            return null;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(value==1){
                Toast.makeText(getApplicationContext(),"Done", Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_LONG).show();

            }
            progressDialog.dismiss();
        }
    }
}

JSONParser.java

   

import android.util.Log;

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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

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,"utf-8"));

                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;

    }
}

add_student.php

<?php


require_once __DIR__ . '/db_connect.php';

$response = array();


if(isset($_POST['Name'])){

	
$name = $_POST['Name'];

	$email = $_POST['Email'];

	$mobile = $_POST['Mobile'];

	
$db = new DB_CONNECT();

	mysql_query("SET NAMES utf8");

	$result=mysql_query("INSERT INTO student('Name','Email','Mobile') VALUES ('$name','$email','$mobile')");

	if($result){
	
	$response['value']=1;


	}else{

		$response['value']=0;

	}
}else{
	$response['value']=-1;

	
}
echo json_encode($response);





?>

如果有人知道我怎么能解决这个问题,请直到我

0 个答案:

没有答案