【问题标题】:E/JSON Parser(1506): Error parsing data [End of input at character 0 of ]E/JSON Parser(1506):解析数据时出错 [在字符 0 处输入结束]
【发布时间】:2014-09-26 19:19:45
【问题描述】:

我的应用程序应该将用户输入数据传输到我的 SQL 数据库。我应该填写所有字段,然后单击保存,以便在我的 sql 数据库中更新数据。在清理了很多错误之后,我终于陷入了 1 个我无法解决的错误。提供的任何帮助将不胜感激。请告知我可以进行哪些更改以消除错误。错误是

       08-04 05:47:48.799: E/JSON Parser(1506): Error parsing data [End of input at character 0 of ] 

我的代码如下:

    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputDriver;
    EditText inputLicence;
    EditText inputOfficer;
    EditText inputSpeed;
    EditText FineAppl;
    EditText inputCategory;
    TextView registerFine;

    // url to create new fine
    private static String url_create_fine = "http://192.168.1.1/android_api/create.php";

    // JSON Node names/
    private static final String TAG_SUCCESS = "success";


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

        speed = (EditText) findViewById(R.id.editText3);    
        Fine = (TextView)findViewById(R.id.editText4);  
        btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
        btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
        inputDriver = (EditText) findViewById(R.id.editText1);
        inputLicence = (EditText) findViewById(R.id.editText2);
        inputOfficer = (EditText) findViewById(R.id.editText5);
        inputSpeed = (EditText) findViewById(R.id.editText3);
        FineAppl = (EditText) findViewById(R.id.editText4);
        inputCategory = (EditText) findViewById(R.id.editText6);
        registerFine = (TextView) findViewById(R.id.fineregistered);


        // Create button
       Button btnRegisterfine = (Button) findViewById(R.id.savefine);





                        // button click event
                        btnRegisterfine.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                // creating new product in background thread
                                new CreateNewFine().execute();
                            }


                      });
        }
                        /**
                         * Background Async Task to Create new product
                         * */
                        class CreateNewFine extends AsyncTask<String, String, String> {


                            @Override
                            protected void onPreExecute() {
                                super.onPreExecute();
                                pDialog = new ProgressDialog(FineCalc.this);
                                pDialog.setMessage("Registering Fine..");
                                pDialog.setIndeterminate(false);
                                pDialog.setCancelable(true);
                                pDialog.show();
                            }


                            protected String doInBackground(String... args) {
                                String driver = inputDriver.getText().toString();
                                String licencenum = inputLicence.getText().toString();
                                String officer = inputOfficer.getText().toString();
                                String speed = inputSpeed.getText().toString();
                                String fine= FineAppl.getText().toString();
                                String category = inputCategory.getText().toString();


                                // Building Parameters
                                List<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("driver", driver));
                                params.add(new BasicNameValuePair("licencenum", licencenum));
                                params.add(new BasicNameValuePair("officer", officer));
                                params.add(new BasicNameValuePair("speed", speed));
                                params.add(new BasicNameValuePair("fine", fine));
                                params.add(new BasicNameValuePair("category", category));

                                // getting JSON Object
                                // Note that create product url accepts POST method
                                JSONObject json = jsonParser.makeHttpRequest(url_create_fine, "POST", params);


                                // check log cat from response
                                //Log.d("Create Response", json.toString());

                                // check for success tag
                                try {
                                       //if (json.getString(TAG_SUCCESS) != null) {
                                    if(json != null && !(json).isNull(TAG_SUCCESS)){
                                    registerFine.setText("");
                                    String success = json.getString(TAG_SUCCESS);
                                   // int success = json.getInt(TAG_SUCCESS);

                                   // if (success == 1) {
                                    if(Integer.parseInt(success) == 1){
                                        // successfully created product
                                       //Intent i = new Intent(getApplicationContext(), UserLogin.class);
                                        //startActivity(i);
                                        registerFine.setText("Successful");

                                        // closing this screen
                                        finish();
                                    } else {
                                    }   // failed to create product
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                return null;
                            }

JSONParser.java

public class JSONParser {

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

// constructor
public JSONParser() {

}

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, HTTP.UTF_8), 8);
        //BufferedReader reader = new BufferedReader(new InputStreamReader(
               // is, HTTP.UTF_8), 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());
        Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
    }

    // return JSON String
    return jObj;

}


}



                            protected void onPostExecute(String file_url) {
                                // dismiss the dialog once done
                                pDialog.dismiss();
                            }

                        }      

还有我的 php

      <?php


// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['driver'], $_POST['licencenum'], $_POST['officer'], $_POST['speed'] , $_POST['fine'],$_POST['category'])){

$driver = $_POST['driver'];
$licencenum = $_POST['licencenum'];
$officer = $_POST['officer'];
$speed = $_POST['speed'];
$fine = $_POST['fine'];
$category = $_POST['category'];


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO fineregister(driver,licencenum,officer,speed,fine,category) VALUES                ('$driver','$licencenum','$officer','$speed','$fine',      '$category')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Speed Ticket Successfully Registered.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

【问题讨论】:

  • 请不要发布整个代码,因为它很难调试。所以贴出相关代码。
  • 并且在发布之前格式化您的代码。目前它非常难以阅读,到处都是缩进和巨大的空白。
  • 您没有包含完整的异常堆栈跟踪也无济于事:( 请阅读tinyurl.com/stack-hints
  • 请注意,您现在有六个问题,其中两个有反对票,没有一个有赞成票。如果你继续问不好的问题,你将被自动禁止再问 - 所以请努力让你的问题变得更好。
  • 又一个 json 错误。规则 1:始终确保您从 json 对象读取的文件与您想要的文件相对应,例如如果你想要 int,请确保它是 int 而不是字符串。

标签: java php json


【解决方案1】:
HttpResponse response = client.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());

pass the string into json array and get the response value

            JSONArray jsArray = new JSONArray(responseBody);
            JSONObject js = jsArray.getJSONObject(0);
            String returnvalmsg = js.getString("message");
            String returnvalsucc = js.getString("success");

提示:将成功传递为“0”而不是 0

【讨论】:

  • 我很抱歉问这个问题,但我在这方面完全是新手。我将在何处以及如何添加此代码。
  • 在 json parser.java 中。 if(method=="post") 更改最后两行,即 get 是字符串而不是输入流
  • 所以我正在尝试这个但我得到一个客户端无法在这里解决 HttpResponse response = client.execute(httpPost);
  • 将上述内容整理出来,但现在我得到了这个奇怪的错误 08-05 09:15:18.787: E/Buffer Error(2342): Error conversion result java.lang.NullPointerException: lock == null 08 -05 09:15:18.787: E/JSON Parser(2342): 解析数据时出错 org.json.JSONException: 在字符 0 处输入结束
  • 调试php端检查是否返回null或value。
猜你喜欢
  • 2014-06-03
  • 2013-08-20
  • 2017-08-01
  • 2014-07-11
  • 1970-01-01
  • 2017-05-17
  • 2013-02-27
相关资源
最近更新 更多