我正在尝试将 json 数组加载到 ViewList 中,但由于操作出错,我无法加载应用程序,
JSONParser.java
package app.tabsample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
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.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class JSONParser extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactspage);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.personallist()));
}
public ArrayList<String> personallist() {
ArrayList<String> listItems = new ArrayList<String>();
try {
URL jsonurl = new URL("http://izra.co.il/z.php");
URLConnection transport = jsonurl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
transport.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONObject obj = new JSONObject(line);
JSONArray ja = obj.getJSONArray("users");
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("name"));
Log.v("got name",jo.getString("name"));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();// Catch URL Error
} catch (IOException e) {
e.printStackTrace();// Catch IO Exception Error
} catch (JSONException e) {
e.printStackTrace(); // Catch JSON Exception Error
}
return listItems;
}
}
联系页面.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
一些它是如何停留在这些行中的:
URLConnection transport = jsonurl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
transport.getInputStream()));
错误:
05-26 15:39:08.902: E/AndroidRuntime(2931): java.lang.RuntimeException: Unable to start activity ComponentInfo{app.tabsample/app.tabsample.JSONParser}: android.os.NetworkOnMainThreadException
希望有人能帮助我,我被打了......
多谢。