Android与MySQL的连接

时间:2011-02-24 16:42:31

标签: android mysql

我正在开发一个最后一年的项目,我需要将Android模拟器与MySQL数据库连接以检索值。 Java文件:

public class connectivity extends Activity {
    /** Called when the activity is first created. */
    TextView txt;
    public static final String KEY_121 = "http://10.0.2.2/mysqlcon.php";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LinearLayout rootLayout = new LinearLayout(getApplicationContext());
        txt = new TextView(getApplicationContext());
        rootLayout.addView(txt);
        setContentView(rootLayout);
        // Set the text and call the connect function.
        txt.setText("Connecting...");
        // call the method to run the data retreival
        txt.setText(getServerData(KEY_121));
    }

    private String getServerData(String returnString) {
        InputStream is = null;
        String result = null;
        // the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year", "1970"));
        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            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 = "0";
            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);
            JSONObject json_data = null;
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                Log.i("log_tag", "id: " + json_data.getInt("id") + ", name: " + json_data.getString("name") + ", sex: " + json_data.getInt("sex") + ", birthyear: " + json_data.getInt("birthyear"));
                // 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;
    }
}

我还在Android清单文件中提供了互联网权限。但是在运行应用程序后,我在logcat中遇到以下错误:

  

错误分配数据org.json.JSONException:JSONArraytext必须以字符0处的'['开头

我认为这表明返回了一个空值。请帮助我,因为这是我的最后一年项目。我花了好几个小时试图找到解决方案,但它没有用。

我目前正在使用Android 2.2。 wamp服务器位于localhost上,因此我使用的地址为10.0.2.2,这是localhost(127.0.0.1)的特殊别名。任何帮助都将非常感激。

这是PHP代码:

<?php
mysql_connect("127.0.0.1","root","chetan");
mysql_select_db("db1");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output,JSON_FORCE_OBJECT));
mysql_close();

2 个答案:

答案 0 :(得分:0)

这实际上是我之前遇到过的一个问题。问题是您的服务器没有输出有效的JSON。它遗漏了一些标记。我建议你将响应的原始文本打印到Logcat并检查它。甚至可能将它传递给JSON validator。这也可以帮助你弄清楚它是否返回一个空值。如果它返回一个空值,那么你需要调试你的服务器...而不是你的客户......

此外,尝试从浏览器访问php页面,让它只显示JSON响应。这将允许您查看服务器正在编写的内容,并帮助您确定问题的确切位置。请注意,因为服务器期望POST最简单的测试方法可能是创建一个简单的html表单,以POST到该页面的测试数据。如果不这样做,让浏览器自行执行POST可能会很痛苦。

答案 1 :(得分:0)

你需要使用连接到PHP ???如果没有,你可以直接连接到mysql db来检索结果:

// Assume function to be :
public String customerData() {  
    String customerInfo = ""; //To store result
    try {
       Class.forName("com.mysql.jdbc.Driver"); 
       Connection con =
             DriverManager.getConnection(
                 "jdbc:mysql://10.0.2.2:3306/retailer","root","pswrd");
       PreparedStatement statement = con.prepareStatement("SELECT * FROM customers");
       ResultSet result = statement.executeQuery();
       while(result.next()) {
          customerInfo = customerInfo + result.getString("name") + "&" + 
                result.getString("C_ID") + "&" + result.getString("address") + 
                "&" + result.getString("email"); 
          // Here "&"s are added to the return string. This is help to split the
          // string in Android application
       } 
    } catch(Exception exc) {
       System.out.println(exc.getMessage());
    }
    return customerInfo;
}

但是你的项目库包括Mysql的连接器jar文件。