我正在尝试学习如何将 JSON 数据填充到 android ListView
My JSON URL::
http://54.218.73.244:7000/
我正在尝试解析来自服务器的数据并获取 JSON 并解析它以将数据填充到 listView。
难以完成要求的任务
有任何想法吗
ListAdapter.java
public class ListAdapter extends ArrayAdapter<Item> {
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tt = null;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.RestaurantNameID);
}
Item p = items.get(position);
if (p != null) {
if (tt != null) {
tt.setText(""+p.getName());
}
}
return v;
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
项目.java
public class Item{
private String Name;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7000/";
List<Item> yourData = new ArrayList<Item>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
yourListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 0)
{
//code specific to first list item
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee1.class);
startActivity(myIntent);
}else if(position == 1)
{
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee2.class);
startActivity(myIntent);
}
}
});
}
}
显现
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".AndroidJSONParsingActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Employee1"
android:label="@string/app_name" >
</activity>
<activity
android:name=".Employee2"
android:label="@string/app_name" >
</activity>
</application>
Employee1.java
public class Employee1 extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.employee1);
Button btn1=(Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent emp1=new Intent(Employee1.this,AndroidJSONParsingActivity.class);
startActivity(emp1);
}
});
}
}
itemlistrow.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">
<TableRow android:layout_width="fill_parent"
android:id="@+id/TableRow01"
android:layout_height="wrap_content">
<TextView
android:id="@+id/RestaurantNameID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="age" android:textStyle="bold"
android:gravity="left"
android:layout_weight="1"
android:typeface="monospace"
android:height="40sp"/>
</TableRow>
</TableLayout>
android_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="@+id/listViewID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</ListView>
</LinearLayout>
LogCat 输出
08-05 10:49:33.429: D/AndroidRuntime(449): Shutting down VM
08-05 10:49:33.429: W/dalvikvm(449): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-05 10:49:33.471: E/AndroidRuntime(449): FATAL EXCEPTION: main
08-05 10:49:33.471: E/AndroidRuntime(449): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coolnet2/com.example.coolnet2.MainActivity}: java.lang.ClassNotFoundException: com.example.coolnet2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.coolnet2-2.apk]
08-05 10:49:33.471: E/AndroidRuntime(449): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
08-05 10:49:33.471: E/AndroidRuntime(449): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-05 10:49:33.471: E/AndroidRuntime(449): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-05 10:49:33.471: E/AndroidRuntime(449): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-05 10:49:33.471: E/AndroidRuntime(449): at android.os.Handler.dispatchMessage(Handler.java:99)
08-05 10:49:33.471: E/AndroidRuntime(449): at android.os.Looper.loop(Looper.java:123)
08-05 10:49:33.471: E/AndroidRuntime(449): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-05 10:49:33.471: E/AndroidRuntime(449): at java.lang.reflect.Method.invokeNative(Native Method)
08-05 10:49:33.471: E/AndroidRuntime(449): at java.lang.reflect.Method.invoke(Method.java:507)
08-05 10:49:33.471: E/AndroidRuntime(449): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-05 10:49:33.471: E/AndroidRuntime(449): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-05 10:49:33.471: E/AndroidRuntime(449): at dalvik.system.NativeStart.main(Native Method)
08-05 10:49:33.471: E/AndroidRuntime(449): Caused by: java.lang.ClassNotFoundException: com.example.coolnet2.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.coolnet2-2.apk]
08-05 10:49:33.471: E/AndroidRuntime(449): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
08-05 10:49:33.471: E/AndroidRuntime(449): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
08-05 10:49:33.471: E/AndroidRuntime(449): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
08-05 10:49:33.471: E/AndroidRuntime(449): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
08-05 10:49:33.471: E/AndroidRuntime(449): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
08-05 10:49:33.471: E/AndroidRuntime(449): ... 11 more
谢谢,