0

我是 android 的新手,我正在尝试在我的应用程序中创建一个动态列表视图。我通过从数组创建列表取得了成功。现在我需要从 JSON 对象创建一个列表。我的代码看起来像

package com.apli.listtest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final String [] str = {"ONE","TWO","THREE","Four"};
        final ListView lv = (ListView) findViewById(R.id.listView1);
        final TextView tv = (TextView)findViewById(R.id.tv1);
        lv.setAdapter(new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_list_item_1, str));



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<TextView
        android:id="@+id/tv1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#333"
        android:text="" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:textColor="#333"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

我的 JSON 看起来像

[{"name":"Name 1","number":"num 1"},{"name":"Name 1","number":"num 1"},{"name":"Name 1","number":"num 1"},{"name":"Name 1","number":"num 1"},{"name":"Name 1","number":"num 1"},{"name":"Name 1","number":"num 1"}]

现在我想从上面的json而不是数组创建一个列表视图

请帮助提前谢谢

4

1 回答 1

3

免责声明这是来自记忆,但应该可以工作。

try {
    JSONArray array = new JSONArray(src); // your string
    String[] listValues = new String[array.length()];
    for (int i = 0; i < array.length(); i++) {
        listValues[i] = array.getJSONObject(i).getString("name");
    }
    lv.setAdapter(new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_list_item_1, listValues));
} catch (JSONException e) {
    e.printStackTrace();
}
于 2013-05-06T15:57:44.843 回答