为什么我的字符串不能转换为JSONObject

时间:2019-05-21 16:02:05

标签: java php android mysql json

我正在尝试遵循有关使用php和sql将数据插入数据库的教程。当我的应用程序运行时,当我的JSONParser.class尝试将字符串转换为JSONParser.java的第92行上的JSONObject时,尝试将数据插入数据库失败,错误为

2019-05-21 10:32:10.490 7491-7541/com.example.sqltest E/JSON Parser: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

我的问题是我无法在代码中的任何地方找到

<br 

被转换为字符串。我什至找不到任何代码中的字符组合。我的服务器上还没有任何html文件,并且我的php中没有分页符。

这是我的JSONParser.java

package com.example.sqltest;

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 method
        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 {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            return jObj;
        }

这是我的NewPackageActivity.java,它获取要插入到数据库中的数据

package com.example.sqltest;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.json.JSONObject;
import com.example.sqltest.JSONParser;
import java.util.ArrayList;
import java.util.List;

public class NewPackageActivity extends AppCompatActivity {
    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();

    // url to create new product
    private static String url_create_package = "http://govtracker.000webhostapp.com/create_package.php";

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

    EditText inputDateRec;
    EditText inputNameTo;
    EditText inputTrackingNum;
    EditText inputNameFrom;
    EditText inputDeliveredName;
    EditText inputStatus;
    private Button AddPackageDBBtn;

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

        AddPackageDBBtn = findViewById(R.id.AddPackageDBBtn);

        //Edit Text
        inputDateRec = (EditText) findViewById(R.id.DateReceivedTextput);
        inputNameTo = (EditText) findViewById(R.id.nameToTextput);
        inputTrackingNum = (EditText) findViewById(R.id.TrackingNumTextput);
        inputNameFrom = (EditText) findViewById(R.id.NameFromTextput);
        inputDeliveredName = (EditText) findViewById(R.id.DeliveredNameTextput);
        inputStatus = (EditText) findViewById(R.id.StatusTextput);

        //Implement onclick

        AddPackageDBBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new CreateNewPackage().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewPackage extends AsyncTask<String, String, String> {
        /**
         * Creating product
         * */
        @SuppressWarnings("deprecation")
        protected String doInBackground(String... args) {
            String dateRec = inputDateRec.getText().toString();
            String nameTo = inputNameTo.getText().toString();
            String trackingNum = inputTrackingNum.getText().toString();
            String nameFrom = inputNameFrom.getText().toString();
            String deliveredName = inputDeliveredName.getText().toString();
            String status = inputStatus.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("dateReceived", dateRec));
            params.add(new BasicNameValuePair("nameTo", nameTo));
            params.add(new BasicNameValuePair("trackingNum", trackingNum));
            params.add(new BasicNameValuePair("nameFrom", nameFrom));
            params.add(new BasicNameValuePair("deliveredName", deliveredName));
            params.add(new BasicNameValuePair("status", status));

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

            return null;
        }

    }
}

这是我的create_package.php

<?php

/*
 * Following code will create a new package row
 * All package details are read from HTTP Post Request
 */

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

  //check required fields
if(isset($_POST['dateReceived']) && isset($_POST['nameTo']) && isset($_POST['trackingNum']) && isset($_POST['nameFrom']) && isset($_POST['deliveredName']) && isset($_POST['status'])){

    $dateReceived = $_POST['dateReceived'];
    $nameTo = $_POST['nameTo'];
    $trackingNum = $_POST['trackingNum'];
    $nameFrom = $_POST['nameFrom'];
    $deliveredName = $_POST['deliveredName']; 
    $status = $_POST['status'];

    // 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 packages(dateReceived, nameTo, trackingNum, nameFrom, deliveredName, status) 
                            VALUES('$deliveredDate', '$nameTo', '$trackingNum', '$nameFrom', '$deliveredName', '$status')");

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

    //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);
    }
}
    ?>

我想知道如何修复我的代码,但是我也知道我正在使用折旧的库,并且愿意遵循更新的教程来完成从android处理数据库的工作。任何帮助将不胜感激。

0 个答案:

没有答案