JSON Android列表视图

JSON Android列表视图,android,json,web-services,android-listview,Android,Json,Web Services,Android Listview,我在netbeans上构建了这个Web服务 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

我在netbeans上构建了这个Web服务

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();
            }
        });
SoapObject请求=新的SoapObject(名称空间、方法名称);
SoapSerializationEnvelope=新的SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(请求);
HttpTransportSE-transportSE=新的HttpTransportSE(URL);
试一试{
传输呼叫(SOAP_动作、信封);
SoapPrimitive响应=(SoapPrimitive)信封.getResponse();
结果=response.toString();
}捕获(例外e){
e、 printStackTrace();
}
字符串jsonAN=“{\'kat\”:“+result+”}”//试着构建成这样{“kat”:[{blajson}]}
字符串kategoriJSONList[][]=新字符串[99][2];
字符串列表[]=新字符串[99]//tobe显示在listview上,源自上面的二维数组。
试一试{
jsonObject=新的jsonObject(jsonAN);
jsonArray=jsonObject.getJSONArray(“kat”);
for(int i=0;i
需要关于如何使用返回的JSONValue的帮助,该值将如上所示显示为ListView。 这几天我压力很大。
提前谢谢。

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

//适配器
公共类ListViewAdapter扩展了BaseAdapter{
私有上下文=null;
私有列表字段=null;
公共ListViewAdapter(上下文,JSONArray arr){
this.context=上下文;
this.fields=new ArrayList();

对于(int i=0;您能告诉我发生了哪种错误吗?根据您的代码,我可以猜测一下:据我所知,JSON对象总是成对的值,[{“var1”、“var2”、“var3”,…,“varn”}]的语法对我来说有些奇怪,应该像[{label1:value1,label2:value2,label3:value3,…,labeln:valuen}]对不起,我的错,打字错误。[{“idPrimary_key”:“21ye21”,“kategori”:“FirstCategory”},{“idPrimary_key”:“89oy89”,“kategori”:“SecondCategory”},{“idPrimary_key”:“34ew34”,“kategori”:“ThirdCategori”}我已经编辑过了。嗯……好的,所以你的错误不是来自json问题。你能提供更多关于你的错误信息吗(类型、logcat、异常等)?您可以发布您的列表适配器代码吗?:)对不起,我不知道如何提供有关错误的信息。唯一可以确定的是,当我尝试运行此程序时,eclipse会显示一个对话框来打开透视图,然后强制关闭。我想,这可能是一个JSON问题,因为我不知道如何使用它并将其解析为数组,我编写的代码只是在尝试,适配器就在那里。谢谢谢谢你的关心,mthana。谢谢mthana,我试过了,效果很好。但是我怎么能只想用“kategori”呢要列出?我已经解决了我的问题,谢谢..我尝试将适配器更改为ArrayList,然后从活动中循环jsonarray和add。您能解释一下循环是如何停止的吗?Austin,如果您指的是Looper.loop,我想说它不是“循环”功能(例如for/while/foreach)Looper本身是一种机制,它允许Android在不同线程内更改UI。Android使用其主线程显示视图,但我们在后台使用JSON。通常,我使用上述行(静态处理程序与线程耦合)加载/重新加载内容,而用户不会遇到延迟和/或ANR(应用程序无响应)。如果不使用此选项,则可以获取CalledFromErrorThreadException。=]
// 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 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>