我正在尝试连接到服务器上的数据库。我刚刚开始使用AsyncTask,因为它被推荐给我。在此之前,我在主UI线程上有HTTP请求,这当然意味着它不起作用。它现在工作得好一些,但我仍然遇到问题。如果我的服务器关闭,我会关闭一个力量。如果你看下面我的代码,我包括一个祝酒词,告诉我是否无法建立连接。然而,这并没有显示出来。
为了让它停止强制关闭并只显示吐司,我需要改变一些东西吗?
当我打开服务器并且数据库已启动时,我查看了logcat,我的Android应用程序确实检索了数据,但它在logcat中并没有显示在页面上。这些代码中的一部分来自教程和搜索谷歌所以我知道“// PARSING DATA”位只计算当前数据的长度,而不是其他任何内容。我认为这是我需要添加代码才能显示的地方。只是为了表明这对我来说是多么新鲜。
真的对这一切感到沮丧,这绝对没有帮助:(。
这是我的代码:
package com.android.history;
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.ParseException;
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.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CurrentSeasonDrivers extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentseason_drivers);
new HttpTask().execute();
}
private static class HttpTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
doStuff();
return null;
}
public static void doStuff() {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
HttpResponse response;
HttpEntity entity;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// HTTP POST REQUEST
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.13/testdatabase.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());
Toast.makeText(null, "Could not connect to server", Toast.LENGTH_LONG).show();
}
// 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;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result = sb.toString();
Log.i("json string", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// PARSING DATA
String drivername;
String drivesfor;
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);
drivername = json_data.getString("Driver_full_name");
drivesfor = json_data.getString("Drives_for");
System.out.println("Drives_for" + drivesfor);
}
} catch (JSONException e1) {
Log.d("DB", "Error somewhere");
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
}
以下是我的log_cat中的错误:
08-22 12:26:39.405: E/log_tag(14327): Error in http connectionorg.apache.http.conn.HttpHostConnectException: Connection to http://192.168.0.13 refused
08-22 12:26:39.405: W/dalvikvm(14327): threadid=13: thread exiting with uncaught exception (group=0x40a051f8)
08-22 12:26:39.455: E/AndroidRuntime(14327): FATAL EXCEPTION: AsyncTask #2
08-22 12:26:39.455: E/AndroidRuntime(14327): java.lang.RuntimeException: An error occured while executing doInBackground()
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.lang.Thread.run(Thread.java:856)
08-22 12:26:39.455: E/AndroidRuntime(14327): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.os.Handler.<init>(Handler.java:121)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.widget.Toast$TN.<init>(Toast.java:317)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.widget.Toast.<init>(Toast.java:91)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.widget.Toast.makeText(Toast.java:233)
08-22 12:26:39.455: E/AndroidRuntime(14327): at com.android.history.CurrentSeasonDrivers$HttpTask.doStuff(CurrentSeasonDrivers.java:74)
08-22 12:26:39.455: E/AndroidRuntime(14327): at com.android.history.CurrentSeasonDrivers$HttpTask.doInBackground(CurrentSeasonDrivers.java:44)
08-22 12:26:39.455: E/AndroidRuntime(14327): at com.android.history.CurrentSeasonDrivers$HttpTask.doInBackground(CurrentSeasonDrivers.java:1)
08-22 12:26:39.455: E/AndroidRuntime(14327): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-22 12:26:39.455: E/AndroidRuntime(14327): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-22 12:26:39.455: E/AndroidRuntime(14327): ... 5 more
答案 0 :(得分:1)
doInBackground在单独的线程上运行。您无法从子线程显示Toast。
在catch块中使用以下代码。
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(null, "Could not connect to server", Toast.LENGTH_LONG).show();
}
});
答案 1 :(得分:0)
Toast应该通过UI线程显示。 Android不允许从后台线程修改UI。正如Umesh所说。
还有一件事可能导致以下行崩溃
jArray = new JSONArray(result);
如果上面两个例外之后的那行上的代码comae然后result
将为空。
所以你应该在这一行上面添加一个空检查,如
if(null != result){
jArray = new JSONArray(result);
}
else{
//Do something else
}