Mysql数据库通过php和android搜索

时间:2015-08-13 05:43:43

标签: java php android mysql wamp

我一直在研究一个基本的WAMP数据库测试应用程序,我遇到了一个很大的问题。我已经设法访问所有数据,添加新数据,甚至删除我的MySQL数据库上的数据,所有这些都来自我的Android应用程序使用PHP。但是,此时,每当我添加规范来搜索特定数据(如用户名或ID号)时,我的代码中都会出现错误,我无法弄清楚。

首先,这是我的JSONParser代码:

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) {

    is = null;
    jObj = null;
    json = "";

    // 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);   /////THIS WHERE THE ERROR POINTS TO
            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");
            HttpGet httpGet = new HttpGet(url);
            url += "?" + paramString;

            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");

                Log.i("1 ", line);
        }
        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;

}
}

对JSONParser类的调用来自一个单独的Java类,它扩展了AsyncTask:

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

                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            "http://10.0.2.2/android_connect/get_product_details.php", "GET", params);

接下来是我用来搜索特定项目信息的PHP文件:

<?php

require 'connect.php';

if(isset($_GET['pid'])){
    $pid = trim($_GET['pid']);

    if($people = $db->prepare("SELECT * FROM products WHERE pid = ?")){
        $people->bind_param('i', $pid);
        $people->execute();

        $people->bind_result($pid, $name, $price, $desc, $created_at, $updated_at);

        $product = array();

        while($people->fetch()){
                $product["pid"] = $pid;
                $product["name"] = $name;
                $product["price"] = $price;
                $product["description"] = $desc;
                $product["created_at"] = $created_at;
                $product["updated_at"] = $updated_at;
        }

        $response["success"] = 1;

        $response["product"] = array();
        $response["product"] = $product;


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

?>

PHP已在Web浏览器上多次测试并且运行良好。但每当我使用Android应用程序调用它时,似乎都会失败,因为没有返回任何内容。

接下来是我的logCat信息:

08-13 01:16:50.259    2764-2764/com.dev.zane.testserver I/url﹕ http://10.0.2.2/UnCorkd/android_connect/get_product_details.php
08-13 01:16:50.259    2764-2764/com.dev.zane.testserver I/url﹕ http://10.0.2.2/UnCorkd/android_connect/get_product_details.php?pid=6
08-13 01:16:50.260    2764-2764/com.dev.zane.testserver D/AndroidRuntime﹕ Shutting down VM
08-13 01:16:50.261    2764-2764/com.dev.zane.testserver E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.dev.zane.testserver, PID: 2764
    android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
            at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
            at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
            at libcore.io.IoBridge.connect(IoBridge.java:122)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
            at java.net.Socket.connect(Socket.java:882)
            at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
            at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
            at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
            at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
            at com.dev.zane.testserver.JSONParser.makeHttpRequest(JSONParser.java:73)
            at com.dev.zane.testserver.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:131)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

错误似乎在JSONParser类的行上:&#39; HttpResponse httpResponse = httpClient.execute(httpGet);&#39;在GET部分下。

可能导致此错误的原因是什么? GET / POST之间是否存在格式或混淆?

任何帮助都会让人觉得很棒,因为我已经把头发撕掉了几天,并且似乎无法在网上找到任何明确的答案。如果我错过任何信息或您需要更多信息,我会更乐意添加/修改。

谢谢!

1 个答案:

答案 0 :(得分:0)

在单独的线程上执行网络操作。 您可以使用AsyncTask来实现此目的。正如您的日志所说,您正在主线程上执行网络操作。

android.os.NetworkOnMainThreadException

将此代码放在doInBackground()

AsycTask方法中
JSONObject json = jsonParser.makeHttpRequest(                            "http://10.0.2.2/android_connect/get_product_details.php", "GET", params);

来自s