我是Android的新手,我希望有人可以帮助我。我有一个活动教员和一个按钮。
这是我的XML布局browse_faculty:
<Button
android:onClick="searchFSTEHandler"
android:id="@+id/bFSTE"
android:layout_width="220dp"
android:layout_height="80dp"
android:layout_alignLeft="@+id/bFBE"
android:layout_below="@+id/bFBE"
android:layout_marginTop="20dp"
android:text="@string/fste" />
这是我的教师活动,显示按钮: 我使用Intent来查看ListView
public class Faculty extends Activity{
@Override
protected void onCreate(Bundle BrowseFaculty) {
// TODO Auto-generated method stub
super.onCreate(BrowseFaculty);
setContentView(R.layout.browse_faculty);
}
//on the XML,this is the "searchFSTEHandler" i want to use to show ListView
public void searchFSTEHandler(View target){
Intent courseList = new Intent(this, HttpActivity.class);
startActivity(courseList);
}
}
以下是“HttpActivity”类是显示我的ListView的类。这个类读取一个php文件,该文件从MySQL服务器获取数据并转换为JSON数据,然后将其解析为数组列表。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
public class HttpActivity extends ListActivity {
public String f1 = "FSTE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faculty_course);
new getHttp().execute();
getHttp test =new getHttp();
String strJsonData = test.doInBackground(f1);
// Convert String JSON data to Java class
ArrayList<Courses> arrayCourse= test.parseJsonData(strJsonData);
//Create an ArrayAdapter which shows the ArrayList data
this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse));
}
private class getHttp extends AsyncTask<String, Void, String> {
public getHttp() {
}
@Override
protected String doInBackground(String... faculty) {
InputStream is = null;
try {
URL url = new URL("http://10.0.2.2/sqlWebService.php?faculty=FSTE");
URLConnection con = url.openConnection();
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
is = con.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
try {
if (is != null)
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
//------------------------------------------------------
private ArrayList<Courses> parseJsonData(String strJson) {
ArrayList<Courses> Course = new ArrayList<Courses>();
try {
// Generate JSONArray object by JSON String data
JSONArray arr = new JSONArray(strJson);
//from the JSONArray, get one element (row) of JSONData
for (int i = 0; i < arr.length(); i++) {
//Get JSON Object which is one element of the array
JSONObject ob = arr.getJSONObject(i);
Courses exam = new Courses();
//get the value by key, and set to exam class
exam.setCode(ob.optString("code"));
//save exam class to exam array list
Course.add(exam);
}
} catch (JSONException e) {
e.printStackTrace();
}
return Course;
}
}
}
单击按钮后应用程序崩溃并出错: “android.os.NetworkOnMainThreadException”
请帮助!
答案 0 :(得分:1)
您遇到的问题是网络操作,就像您尝试做的那样,不能也不应该在主UI线程上执行。这样做会导致 ANR(Android无响应),这正是您刚刚获得的错误。您要执行的操作是将代码移至单独的主题或 AsyncTask
,以便使用 doInBackground()
在后台的其他主题上执行此操作方法,无法访问主UI线程上的视图。例如,
private class ExampleOperation extends AsyncTask<String, Void, String> {
public ExampleOperation() { //ctor }
@Override
protected void onPreExecute() {
//things that you want to initialize and maybe show dialog to user.
}
@Override
protected String doInBackground(String... params) {
//this is where you perform that network related operation.
}
@Override
protected void onPostExecute(String result) {
//this is where get the results from the network related task.
}
@Override
protected void onProgressUpdate(Void... values) {
//you can update your progressbar if any; otherwise omit method.
}
}
然后你要做的就是调用AsyncTask你想要使用它的地方:new ExampleOperation().execute();
答案 1 :(得分:0)
您不能在主线程中进行HTTP调用,它们需要太长时间并且会使UI无响应。您需要在AsyncTask中执行此操作。