android - JSON Android ListView

标签 android json web-services android-listview

我在 netbeans 上构建这个网络服务,

package in.figures.on.mobile;

import db.koneksi.dbKoneksi;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.json.simple.JSONValue;

/**
 *
 * @author Setyadi
 */
@WebService()
public class AksesData {

    /**
     * Web service operation
     */
    @WebMethod(operationName = "Kategori")
    public String Kategori() {
        //TODO write your implementation code here:

        dbKoneksi con = new dbKoneksi();
        Statement statement;
        Properties properties;
        List list = new ArrayList();
        String sql = "SELECT idPrimary_key, kategori FROM kategori ";
        ResultSet hasil;
        String kategori = null;

        try{
            statement = con.getConnection().createStatement();
            hasil = statement.executeQuery(sql);
            while (hasil.next()) {
                properties = new Properties();
                properties.put("idPrimary_key", hasil.getString(1));
                properties.put("kategori", hasil.getString(2));
                list.add(properties);
            }
            kategori = JSONValue.toJSONString(list);
        }
        catch(Exception e){
        }

        return kategori;
    }


}

然后像这样返回一个 JSON

[{"idPrimary_key":"21ye21","kategori":"FirstCategory"},
{"idPrimary_key":"89oy89","kategori":"SecondCategory"},
{"idPrimary_key":"34ew34","kategori":"ThirdCategory"}]

然后我尝试像这样在 Android ListView 中消费,但仍然有错误,

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);  

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);

        HttpTransportSE transportSE = new HttpTransportSE(URL);

        try {
            transportSE.call(SOAP_ACTION, envelope);
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
            result = response.toString();

        } catch (Exception e) {
            e.printStackTrace();

        }

        String jsonAN = "{\"kat\":"+result+"}"; //try to build to be like this {"kat":[{blablablaJSON}]}
        String kategoriJSONList[][] = new String[99][2];
        String katList[] = new String[99]; //tobe shown on listview, derived from two dimensional array above.
        try {
            jsonObject = new JSONObject(jsonAN);
            jsonArray = jsonObject.getJSONArray("kat");

            for(int i=0; i < jsonArray.length() ; i++){
                kategoriJSONList[i][0] = jsonArray.getJSONObject(i).getString("idPrimary_key").toString();
                kategoriJSONList[i][1] = jsonArray.getJSONObject(i).getString("kategori").toString();
            }

            for(int i=0; i < jsonArray.length(); i++){
                katList[i] = kategoriJSONList[i][1];
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ListView list  = (ListView) findViewById(R.id.listKategori);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                WebServiceActivity.this, android.R.layout.simple_list_item_1,katList
                );

        list.setAdapter(adapter);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                final String kategori = (String) ((TextView)arg1).getText();
                Toast.makeText(WebServiceActivity.this, kategori,
                        Toast.LENGTH_LONG).show();
            }
        });

需要帮助如何使用如上所示返回的 JSONValue 以显示为 ListView。 这几天我压力很大。 提前致谢。

最佳答案

好的。试试下面的代码。它对我来说功能齐全。您应该在注释行中实现 HttpRequest。注意 JSON 数组是硬编码的。

// the Adapter
public class ListViewAdapter extends BaseAdapter {

    private Context context = null;
    private List<String> fields = null;

    public ListViewAdapter(Context context, JSONArray arr) {
        this.context = context;
        this.fields = new ArrayList<String>();
        for (int i=0; i<arr.length(); ++i) {
            try {
                fields.add(arr.getJSONObject(i).toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public int getCount() {
        return fields.size();
    }

    @Override
    public Object getItem(int position) {
        return fields.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.itemlist, null);
        TextView txt = (TextView) convertView.findViewById(R.id.ItemList_txt);
        txt.setText(fields.get(position));
        return convertView;
    }

}

// the activity
public class ListViewActivity extends Activity {

    public final String result = "[{\"idPrimary_key\":\"21ye21\",\"kategori\":\"FirstCategory\"},{\"idPrimary_key\":\"89oy89\",\"kategori\":\"SecondCategory\"},{\"idPrimary_key\":\"34ew34\",\"kategori\":\"ThirdCategory\"}]";
    public final String obj = "{\"kat\":"+result+"}";

    private ListViewAdapter adapter = null;
    private ListView myList = null;
    private JSONArray items = new JSONArray();

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) { // server returned null, try again
                loadFields();
            } else if(msg.what == 1) { // error in json
                // do something to treat it
            } else if (msg.what == 2) { // ready to roll the list
                adapter = new ListViewAdapter(ListViewActivity.this, items);
                myList.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        }
    };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myList = (ListView) findViewById(R.id.Lists_notificationsListview);
    loadFields();
}

private void loadFields() {
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            StringBuilder builder = new StringBuilder(obj);
            if (builder != null) {
                try {
                    // HERE, you should implement the HTTP request...
                    items = new JSONObject(obj).getJSONArray("kat");
                    handler.sendEmptyMessage(2);
                } catch (JSONException e) {
                    handler.sendEmptyMessage(1);
                }
            } else {
                handler.sendEmptyMessage(0);
            }
            Looper.loop();
        }
    }.start();
}

和 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:orientation="vertical"
        android:isScrollContainer="true">
        <ListView
            android:id="@+id/Lists_notificationsListview"
            android:layout_width="fill_parent" android:layout_height="match_parent">
        </ListView>
    </RelativeLayout>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <TextView
        android:id="@+id/ItemList_txt"
        android:layout_width="fill_parent" android:layout_height="wrap_content"/>
</LinearLayout>

结果,它生成以下 View :

enter image description here

当然,您可以自定义它来创建您想要的列表,只需解析 json! 希望我能以某种方式提供帮助...

关于android - JSON Android ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11318761/

相关文章:

java - 用java构建wsdl的框架或工具

android - 为什么自动完成在 android.support.v7.widget.CardView 标签中不起作用?

android - 如何通过包含依赖项的 gradle 制作 jar

javascript | json解析

javascript - JSON 元素是否可以以 - 开头并在 javascript 中被引用?

java - 从 Android 设备调用 .Net 网络服务

android - 获取 JSON 并对其进行操作

android - 如果您在一个 Activity 中,按下 Activity 主页按钮时会调用哪些生命周期方法?

javascript - Chrome扩展程序JSON值解析问题

ios - 在 iOS 中访问 RESTful Web 服务