0

I am a new be to android and I am trying to create a dynamic list view in my application. I have successes by creating a list from an array. Now I need to create a list from JSON object. My code looks like

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>

My JSON looks like

[{"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"}]

Now I want to create a list view from the above json other than the array

Please help Thanks in advance

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 に答える