将android连接到mysql数据库

时间:2011-04-11 14:51:55

标签: android mysql

我一直在尝试这个教程。它显示任何错误,但在模拟器上只显示我给出的网址!

我的连接字符串是:

public static final String KEY_121 = "http://10.0.2.2/index.php";

(我使用10.0.2.2,因为我在本地主机上工作)

当我检查我的logcat时,它显示了我:

error parsing data org.json.JsonException: Value <br of type java.lang.String cannot be converted to JSONArray

我真的不知道我的代码有什么问题。谁能帮帮我吗。在我的最后一年项目中,我真的需要帮助。

这是我的android java代码

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class main extends Activity {
    /** Called when the activity is first created. */

    TextView txt1, txt2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Create a crude view - this should really be set via the layout
        // resources
        // but since its an example saves declaring them in the XML.
        txt1 = (TextView) findViewById(R.id.ip);

        LinearLayout rootLayout = new LinearLayout(getApplicationContext());
        txt1 = new TextView(getApplicationContext());
        rootLayout.addView(txt1);
        setContentView(rootLayout);

        // Set the text and call the connect function.
        txt1.setText("Connecting...");
        // call the method to run the data retreival
        txt1.setText(getServerData(KEY_121));

    }

    public static final String KEY_121 = "http://10.0.2.2/index.php";

    private String getServerData(String returnString) {

        InputStream is = null;

        String result = "";
        // the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year", "1970"));


        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        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();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        // parse json data

        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Log.i("log_tag",
                        "longitude: " + json_data.getDouble("longitude")
                                + ", latitude: "
                                + json_data.getDouble("latitude"));
                // Get an output to the screen
                returnString += "\n\t" + jArray.getJSONObject(i);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return returnString;
    }

}

这是我的php代码

<?php

mysql_connect("localhost","root","sugi");
mysql_select_db("android");

$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");

while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(json_encode($output));

mysql_close();
?>

这是mysql查询

CREATE TABLE people (

  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,

  name VARCHAR( 100 ) NOT NULL ,

  sex BOOL NOT NULL DEFAULT '1',

  birthyear INT NOT NULL

  )

这是我在IE上输入“http://10.0.2.2/index.php”时显示的内容

enter image description here

3 个答案:

答案 0 :(得分:0)

尝试并打印从服务器获得的输出。似乎不清楚JSON会被返回。这部分

Value <br of type 

看起来某处有一个难以进入的地方。

答案 1 :(得分:0)

修复php警告,index.php的结果应该是有效的JSON响应。

未定义变量$_REQUEST['year'],可能是因为您未将其与请求一起发送。您的变量nameValuePairs永远不会添加到您的请求中...

答案 2 :(得分:0)

服务器可能会返回以

开头的错误
<BR />

您可以通过在此代码块中添加一行来验证这一点:

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

            /////////////////////////////////
            // ADD THIS
            Log.i("log_tag","Line reads: " + line);

        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

然后运行程序并检查您的日志。它将显示从服务器收到的信息。

例如,如果您的PHP配置不包含JSON库,则会出现错误。您可能正在使用旧版本的PHP。如果您使用的是托管服务器,如1and1或GoDaddy,您可能只需要编辑.htaccess文件,以便您的站点使用PHP5。