【问题标题】:JSON Android ListViewJSON Android 列表视图
【发布时间】:2012-07-03 20:34:08
【问题描述】:

我在 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。 这几天我压力很大。 提前致谢。

【问题讨论】:

  • 您能告知发生了哪种错误吗?根据您的代码,我可以猜测:据我所知,JSONObjects 始终是对值,并且 [{"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": "ThirdCategory"}] 我已经编辑过了。
  • 嗯...好的,所以你的错误不是来自 json 问题。您能否提供有关您的错误(类型、logcat、异常等)的更多信息?您可以发布您的列表适配器代码吗? :)
  • 我不知道如何提供有关错误的信息,抱歉。唯一可以肯定的是,当我尝试运行它时,eclipse 会显示一个对话框来打开透视图,然后强制关闭。而且我认为,这可能是 JSON 问题,因为我不知道如何使用它并将其解析为数组,我编写的代码只是在尝试,适配器就在那里。感谢您的关心 mthama。

标签: android json web-services android-listview


【解决方案1】:

好的。试试下面的代码。它对我来说功能齐全。您应该在注释行中实现 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>

结果,它会生成以下视图:

当然,您可以自定义它来创建您想要的列表,只需解析 jsons! 希望我在某种程度上有所帮助...

【讨论】:

  • 谢谢mthana,我试过了,效果很好。但是我怎么能只想使用“类别”来列出呢?
  • 我已经解决了我的问题,谢谢.. 我尝试将适配器更改为 ArrayList,然后循环 jsonarray 并从活动中添加。
  • 你能解释一下循环是如何停止的吗?
  • Austin,如果您提到 Looper.loop,我想说它本身并不是“循环”功能(例如 for/while/foreach)。 Looper 是一种让 Android 在不同线程中更改 UI 的机制。 Android 使用他的主线程来显示视图,但我们在后台使用 JSON。通常,我使用上述这些行(与线程耦合的静态处理程序)来加载/重新加载内容,而用户不会遇到延迟和/或 ANR(应用程序无响应)。如果我们不使用它,我们会得到一个 CalledFromWrongThreadException。 =]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多