简体   繁体   中英

I'm getting the JSON encoded data with other data as a response from the database to a my android app

I'm a beginner in android and PHP and I'm trying to connect my android app to a Wamp database server

I'm following this course here http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

The idea is using a PHP code to execute basic SQL operations

I have and activity that takes a product name ,price, and a description and store it on the database returning a JSON encoded data with the information about if the insertion was successful or not

But I get an error trying to create a JSONObject out of it

so here's what I tried

Log.e("JSON",json);

I used a log to see what the data is and here is what I got

05-26 15:25:56.164 7801-7886/products.android.com.connectingproducts E/JSON: <br />
 <font size='1'><table class='xdebug-error xe-deprecated' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
 <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp64\www\android_connect\db_connect.php on line <i>28</i></th></tr>
 <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
 <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
 <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0007</td><td bgcolor='#eeeeec' align='right'>241312</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\android_connect\create_product.php' bgcolor='#eeeeec'>...\create_product.php<b>:</b>0</td></tr>
 <tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0012</td><td bgcolor='#eeeeec' align='right'>252032</td><td bgcolor='#eeeeec'>DB_CONNECT->__construct(  )</td><td title='C:\wamp64\www\android_connect\create_product.php' bgcolor='#eeeeec'>...\create_product.php<b>:</b>22</td></tr>
 <tr><td bgcolor='#eeeeec' align='center'>3</td><td bgcolor='#eeeeec' align='center'>0.0012</td><td bgcolor='#eeeeec' align='right'>252120</td><td bgcolor='#eeeeec'>DB_CONNECT->connect(  )</td><td title='C:\wamp64\www\android_connect\db_connect.php' bgcolor='#eeeeec'>...\db_connect.php<b>:</b>11</td></tr>
 <tr><td bgcolor='#eeeeec' align='center'>4</td><td bgcolor='#eeeeec' align='center'>0.0016</td><td bgcolor='#eeeeec' align='right'>252936</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.mysql-connect' target='_new'>mysql_connect</a>
 (  )</td><td title='C:\wamp64\www\android_connect\db_connect.php' bgcolor='#eeeeec'>...\db_connect.php<b>:</b>28</td></tr>
 </table></font>
{"success":1,"message":"Product successfully created."}

the data got seems to have some html style code and at the end it has the message I want :

{"success":1,"message":"Product successfully created."}

so here is my JSONParser Code

package products.android.com.connectingproducts;

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;
    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.equals("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.equals("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());
        }


        Log.e("JSON",json);

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

    }

}

and here is my php file

<?php

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

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

please help if you know why is this data is added to the json encoded data

Thanks

As amendezcabrera said in the comments, mysql_connect() is deprecated

so I used mysqli_connect() and that lead to some other errors in my php code that I have fixed and now it's working

it turns out that the other data send with the json encoded data that I want includes php error messages so I fixed them

amendezcabrera thanks for your help

尝试在httpPost.setEntity(new UrlEncodedFormEntity(params))之后添加以下内容:

httpPost.setHeader("Accept", "application/json");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM