我只想在某个物理设备上的mysql数据库上加载的某个日期在android设备上阅读。
数据库和提取数据的php脚本都可以。
问题是android编码方面。
public class MainActivity extends Activity {
public HttpResponse response;
public String str;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("/*phpAddressIsCorrect*/");
try {
response = httpclient.execute(httppost);
}
catch(IOException e) {
e.printStackTrace();
}
try {
str = EntityUtils.toString(response.getEntity());
} catch(IOException e){
e.printStackTrace();
}
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
}
}
main.xml
只是一个RelativeLayout
。拥有互联网的android许可,应用在加载时崩溃。我想那是因为IOException,不是吗?
最佳答案
联网总是需要在另一个线程(而不是UiThread)中完成。
new Thread() {
public void run() {
HttpURLConnection con = (HttpURLConnection) new URL("http://xyz").openConnection();
String response = StreamToString(con.getInputStream());
// ...
}
}.start();
public static String StreamToString(java.io.InputStream is) {
java.util.Scanner scanner = new java.util.Scanner(is);
scanner.useDelimiter("\\A");
String ret = scanner.hasNext() ? scanner.next() : "";
scanner.close();
return ret;
}