gpt4 book ai didi

java - 将android应用程序与sql数据库连接?

转载 作者:行者123 更新时间:2023-11-29 04:52:32 25 4
gpt4 key购买 nike

我试过这个连接数据库的例子,我有一个简单的数据库,这是 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'

最佳答案

  1. 你不能运行你的 NETWORK同一线程上的 Activity (来自较新版本的 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然后一项一项地获取您的数据。

上面,你说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

关于java - 将android应用程序与sql数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10109739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com