我正在尝试运行此活动以查询数据库以填充表。我试图按照我在网上找到的一个片段,唯一的问题是,无论如何,我都会收到“connectionandroid.os.NetworkOnMainThreadException”错误。
正如许多论坛中所建议的那样,我尝试使用 AsyncTask 并在后台执行处理程序,但仍然没有。我知道将长查询发送到数据库时会出现错误,但此查询可能需要 0.1 秒。我在本地有数据库,尽管使用公共 IP 访问它,并且数据库非常小。
这是我的PHP代码:
<?php
$hostname_localhost ="localhost";
$database_localhost ="DB";
$username_localhost ="root";
$password_localhost ="pwd";
mysql_connect($hostname_localhost,$username_localhost,$password_localhost);
mysql_select_db($database_localhost);
$sql=mysql_query("select * from friendlist where Id1 = 1");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
代码有效,就好像我转到页面一样,我看到显示的结果(我目前只有 3 行)。
这是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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MySQLAndroidActivity extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
HttpResponse response;
HttpEntity entity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://X.X.X.X/test.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
System.exit(1);
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
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());
}
//parsing data
String idfriend;
String id1;
String id2;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
idfriend=json_data.getString("Idfriend");
id1=json_data.getString("Id1");
id2=json_data.getString("Id2");
System.out.println("id1: " + id1);
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Id found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
我也尝试使用简单的 Activity 而不是 ListActivity。
我有一个几乎相似的代码,但是那个使用了不同的方法。实际上,它并没有得到结果,在 php 上,它只是返回一个字符,无论检索到 0 行还是更多行。在这种情况下,我需要更高级别的东西,因为我需要获取某些特定字段的值。
编辑:
根据要求,堆栈跟踪:
Error in http connectionandroid.os.NetworkOnMainThreadException
04-17 06:44:17.921: W/System.err(24207): java.lang.Exception
04-17 06:44:17.921: W/System.err(24207): at com.mysql.android.MySQLAndroidActivity.onCreate(MySQLAndroidActivity.java:56)
04-17 06:44:17.921: W/System.err(24207): at android.app.Activity.performCreate(Activity.java:4465)
04-17 06:44:17.921: W/System.err(24207): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-17 06:44:17.921: W/System.err(24207): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
04-17 06:44:17.921: W/System.err(24207): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
04-17 06:44:17.921: W/System.err(24207): at android.app.ActivityThread.access$600(ActivityThread.java:123)
04-17 06:44:17.921: W/System.err(24207): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
04-17 06:44:17.921: W/System.err(24207): at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 06:44:17.921: W/System.err(24207): at android.os.Looper.loop(Looper.java:137)
04-17 06:44:17.931: W/System.err(24207): at android.app.ActivityThread.main(ActivityThread.java:4424)
04-17 06:44:17.931: W/System.err(24207): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 06:44:17.931: W/System.err(24207): at java.lang.reflect.Method.invoke(Method.java:511)
04-17 06:44:17.931: W/System.err(24207): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-17 06:44:17.931: W/System.err(24207): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-17 06:44:17.931: W/System.err(24207): at dalvik.system.NativeStart.main(Native Method)
编辑2:
这与我使用 AsyncTask 所做的版本非常相似(我是动态创建它,没有编译器,因此它可能并不完美;但它与我之前所做的非常相似):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LoadTask().execute();
}
private class LoadTask extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
synchronized (this) {
Looper.prepare();
doStuff() //this method basically contains what it is inside the onCreate.
}
return null;
}
}
}
- 我记得我被迫使用'Looper.prepare();'。所以我在 'doStuff();' 之前添加了它
编辑2:
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
public class MySQLAndroidActivity extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
HttpResponse response;
HttpEntity entity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LoadTask.execute();
}
private class LoadTask extends AsyncTask < Void, Integer, Void > {@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void...params) {
Looper.prepare();
doStuff();
return null;
}
}
public void doStuff() {
ArrayList < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > ();
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://X.X.X.X/test.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
System.exit(1);
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
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());
}
//parsing data
String idfriend;
String id1;
String id2;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
System.out.println("Length " + jArray.length());
Log.d("DB", "Length " + jArray.length());
for (int i = 0; i < jArray.length(); i++) {
System.out.println("counter " + i);
json_data = jArray.getJSONObject(i);
idfriend = json_data.getString("Idfriend");
id1 = json_data.getString("Id1");
id2 = json_data.getString("Id2");
System.out.println("id1: " + id1);
}
} catch (JSONException e1) {
Log.d("DB", "Error somewhere");
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
提前致谢,
N。