Ошибка Android при разборе данных org.json.JSONException: конец ввода в символе 0 из - PullRequest
0 голосов
/ 21 сентября 2019

Я пытаюсь отправить данные на сервер sql.Код работает нормально на локальном хосте, но этот код падает на живом сервере.И выдадим ошибку, Вот трассировка стека

09-21 15: 19: 50.419: E / JSON Parser (1712): Ошибка синтаксического анализа данных org.json.JSONException: Конец ввода в символ 0от 09-21 15: 19: 50.609: W / dalvikvm (1712): threadid = 11: поток завершается с неперехваченным исключением (группа = 0x40a122a0) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): ФАТАЛЬНОЕ ИСКЛЮЧЕНИЕ:AsyncTask # 1 09-21 15: 19: 50.880: E / AndroidRuntime (1712): java.lang.RuntimeException: произошла ошибка при выполнении doInBackground () 09-21 15: 19: 50.880: E / AndroidRuntime (1712): вandroid.os.AsyncTask $ 3.done (AsyncTask.java:299) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): на java.util.concurrent.FutureTask $ Sync.innerSetException (FutureTask.java:273)09-21 15: 19: 50.880: E / AndroidRuntime (1712): в java.util.concurrent.FutureTask.setException (FutureTask.java:124) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): вjava.util.concurrent.FutureTask $ Sync.innerRun (FutureTask.java:307) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): на java.util.concurrent.FutureTask.run (FutureTask.java:137) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1076) 09-21 15:19:50.880: E / AndroidRuntime (1712): на java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:569) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): на java.lang.Thread.run (Thread.java:856) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): вызвано: java.lang.NullPointerException 09-21 15: 19: 50.880: E / AndroidRuntime (1712): вcom.example.androidhive.NewProductActivity $ CreateNewProduct.doInBackground (NewProductActivity.java:100) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): в com.example.androidhive.NewProductActivity $ CreateNewProduct.doInBackground (NewProductAj: 1) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): на android.os.AsyncTask $ 2.call (AsyncTask.java:287) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): at java.util.concurrent.FutureTask $ Sync.innerRun (FutureTask.java:305) 09-21 15: 19: 50.880: E / AndroidRuntime (1712): ... еще 4 09-21 15: 19: 52.819: I / Process (1712): отправка сигнала.PID: 1712 SIG: 9

, когда я изменил URL-адрес на http://148.66.138.164/create_product.php, тогда он выдаст эту ошибку

 Error parsing data org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();


    // url to create new product
    private static String url_create_product = "http://maxsportslive.com/create_product.php";

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

    @Override
    public void onCreate(Bundle savedInstanceState) {



        // button click event
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String price = inputPrice.getText().toString();
            String description = inputDesc.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("description", description));

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

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

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    /*
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);*/


                    // closing this screen9
                    //finish();
                    Intent intent = getIntent();
                    finish();
                    startActivity(intent);
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();  

            pDialog.dismiss();
        }

    }

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;

    }
}

Create_Product.php

<?php
// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {

    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];

    // 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 products(name, price, description) VALUES('$name', '$price', '$description')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product 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);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

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

DB_config.php

<?php

/*
 * All database connection variables
 */

define('DB_USER', "xxxxxxxxx"); // db user
define('DB_PASSWORD', "xxxxxxxx"); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "148.66.138.164"); // db server
?>

DB_connect.php

<?php

class DB_CONNECT {

    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }

    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

        // returing connection cursor
        return $con;
    }

    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }

}

?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...