连接Android应用程序与SQL数据库?

时间:2012-04-11 16:08:04

标签: java php android mysql

我试过这个例子用于连接数据库,我有简单的数据库,这是java类:

package com.cvele.android.sqlconn;
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.entity.UrlEncodedFormEntity;
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 SqlconnActivity extends Activity {
    /** Called when the activity is first created. */

    TextView txt;
    @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);  
        txt.setText("Connecting..."); 
        txt.setText(getServerData(LINK_PHP)); 
    }
    public static final String LINK_PHP = "http://10.0.2.2/sajt.php"; 

    private String getServerData(String returnString) {

        InputStream is = null;
        String result = "";
        ArrayList<NameValuePair>nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year","1970"));

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(LINK_PHP);
            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());
        }

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

        try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                Log.i("log_tag","id: "+json_data.getInt("id")+
                    ", name: "+json_data.getString("name")+
                    ", sex: "+json_data.getString("sex")+
                    ", birthyear: "+json_data.getInt("birthyear")
                    );

                returnString += "\n\t" + jArray.getJSONObject(i); 
            }
        }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
        }
        return returnString; 
    }
}

这是php:

<?

$databasehost = "127.0.0.1";
$databasename = "peopledata";
$databaseusername ="nikola";
$databasepassword = "nikola";

$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = mysql_query("SELECT * FROM people WHERE birthyear >'".$_REQUEST['year']."'");


if (mysql_errno()) { 
    header("HTTP/1.1 500 Internal Server Error");
    echo $query.'\n';
    echo mysql_error(); 
}
else
{
    $rows = array();
    while($r = mysql_fetch_assoc($query)) {
        $rows[] = $r;
    }
    print json_encode($rows);
}
?>

因此,当我构建它时,它总是在字符串LINK_PHP =“http://10.0.2.2/sajt.php”中写出“”之间的内容。我无法从我的数据库中获取任何数据。我的问题是,为什么总是写在我的应用程序上?提前致谢。 这就是我得到的: enter image description here

好的,这是我在LogCat中得到的:

04-11 16:02:33.064: I/dalvikvm(811): threadid=3: reacting to signal 3
04-11 16:02:33.256: I/dalvikvm(811): Wrote stack traces to '/data/anr/traces.txt'
04-11 16:02:33.544: I/dalvikvm(811): threadid=3: reacting to signal 3
04-11 16:02:33.604: I/dalvikvm(811): Wrote stack traces to '/data/anr/traces.txt'
04-11 16:02:33.724: E/log_tag(811): Error in http connection android.os.NetworkOnMainThreadException
04-11 16:02:33.724: E/log_tag(811): Error converting result java.lang.NullPointerException
04-11 16:02:33.744: E/log_tag(811): Error parsing data org.json.JSONException: End of input at character 0 of 
04-11 16:02:33.944: D/gralloc_goldfish(811): Emulator without GPU emulation detected.
04-11 16:02:34.044: I/dalvikvm(811): threadid=3: reacting to signal 3
04-11 16:02:34.104: I/dalvikvm(811): Wrote stack traces to '/data/anr/traces.txt'

3 个答案:

答案 0 :(得分:2)

  1. 您无法在同一个帖子上运行NETWORK活动(来自较新版本的Android SDK)。
  2. 为此,请执行Asynctask。即使考虑到记忆,它也会处理你的所有任务。
  3. 还有Runnable个帖子,但是通过AsyncTask
  4. 获取输入流。制作while loop来阅读流,append使用String
  5. 现在,如果您是XML,那么请通过Document对象解析XML。为此,请浏览DocumentBuilderFactory。 (xml的例子)。
  6. 现在,从Document(对象 doc 中的实例)对象获取您的数据doc.getElementByTagName("yourxmltaghere");
  7. 但是,如果您使用JSON,请按住JSON。如果它有子对象,则将for循环到mArray.length,然后逐个获取数据。
  8. 上面,您说Value <?xml of type java.lang.String cannot be converted to JSONArray,这意味着您正在尝试将XML转换为JSON。所以,我在这里没有CASTING代码。但是,我通过以下方式做到了这一点。

    InputStream is = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = 
    while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
    } 
    
    
    
    String xml = sb.toString();                         
    JSONObject baseObject = XML.toJSONObject(xml);
    
    JSONObject todo_items = baseObject.getJSONObject("todo-items");
    JSONArray todo_item = todo_items.getJSONArray("todo-item");
    tempItems = GenerateVO(todo_item);
    

    这里,XML是我加载的类。我没有找到任何其他如此使用过的。我从org.json提供的JSON包中获得了这个课程。通过谷歌获得它或从这里获得。 XML LINK

答案 1 :(得分:1)

参考LogCat输出。想一想,你会在那里看到关于异常的消息。

使用Eclipse,您可以使用Window&gt; Show View&gt; LogCat打开LogCat输出。

根据这条线

Error in http connection android.os.NetworkOnMainThreadException

您已将应用定位到Honeycomb或更高版本。抛出exception是因为您正在从主(GUI)线程执行网络操作,这是强烈禁止的:) 尝试将您的应用程序定位到API级别10(Gingerbread),只是为了尝试您的代码。但是进一步将您的网络运营转移到AsyncTask

答案 2 :(得分:1)

再次,检查实际收到的HTTP消息:好像你得到的是XML而不是JSON。