1

我尝试了这个连接数据库的例子,我有简单的数据库,这是 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" 中的“”之间的内容。我无法从我的数据库中获取任何数据。我的问题是,为什么它总是写在我的应用程序上..?提前致谢。这就是我得到的: 在此处输入图像描述

好的,这就是我在 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'
4

3 回答 3

2
  1. 您不能NETWORK在同一个线程上运行您的活动(来自较新版本的 Android SDK)。
  2. 为此,请继续实施Asynctask. 即使考虑到内存,它也会处理您的所有任务。
  3. 也有Runnable线程,但要通过AsyncTask.
  4. 获取输入流。制作一个while loop阅读流并append使用String.
  5. 现在,如果您有 XML,则按Document对象解析 XML。为此,通过DocumentBuilderFactory. (xml 的示例)。
  6. 现在,从Document(对象文档中的实例)对象获取数据doc.getElementByTagName("yourxmltaghere")
  7. 但是,如果您使用 JSON,请保留您的JSON. 如果它有子对象,则for循环直到mArray.length然后一一获取您的数据。

上面,您说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 链接

于 2012-04-11T17:54:55.713 回答
1

再次检查实际收到的 HTTP 消息:似乎您得到的是 XML 而不是 JSON。

于 2012-04-11T17:34:53.373 回答
1

查阅 LogCat 输出。想一想,您会在那里看到有关异常的消息。

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

根据这条线

Error in http connection android.os.NetworkOnMainThreadException

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

于 2012-04-11T16:14:07.210 回答