【问题标题】:Android ListView JSONObject QuestionAndroid ListView JSONObject 问题
【发布时间】:2011-05-02 18:20:13
【问题描述】:

最近我一直在尝试创建一个使用 JSON 对象在 listView 中显示 RSS 提要标题的 Android 应用程序。尽管我遇到的问题是每当触摸 listView 中的项目以显示 JSON 对象时监听器的实现,该对象具有存储在其中的 RSS 提要的描述格式。我一直在摆弄适配器,几乎没有成功。希望有人能帮帮我。

这是我制作的 RSSActivity 类:

import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;




public class RSSActivity extends ListActivity {

    private RSSListAdapter adapter;
    private int Title = 0;
    private int Description = 1;
    private List<JSONObject> titles = new ArrayList<JSONObject>();
    private List<JSONObject> descriptions = new ArrayList<JSONObject>();



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        try {
            titles = RSSReader.getLatestRssFeed(Title);
            descriptions = RSSReader.getLatestRssFeed(Description);

        } catch (Exception e) {
            Log.e("RSS ERROR", "Error loading RSS Feed Stream >> " + e.getMessage() + " //" + e.toString());
        }

        adapter = new RSSListAdapter(this,titles);
        setListAdapter(adapter);


    }



    public void makeInfo(Integer pos) {
        Log.i("assetInfo", "=" + pos);

    }



}

这是我的 RSSListAdapter:

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class RSSListAdapter extends ArrayAdapter<JSONObject>{

    private TextView textView;
    private LayoutInflater inflater = null;
    private int resource;
    private Activity activity;
    public RSSListAdapter(Activity _activity, List<JSONObject> _item) {
        super(_activity, 0, _item);
        inflater = (LayoutInflater) _activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        activity = _activity;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final Activity activity = (Activity) getContext();

        ViewHolder holder;

        // Inflate the views from XML
        View rowView = inflater.inflate(R.layout.image_text_layout, null);


        //////////////////////////////////////////////////////////////////////////////////////////////////////
        //The next section we update at runtime the text - as provided by the JSON from our REST call
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        if(convertView == null)
        {
            holder = new ViewHolder();
            holder.title = (TextView) rowView.findViewById(R.id.listTitle);
            holder.description = (TextView) rowView.findViewById(R.id.description);
            rowView.setTag(holder);

        }
        else
        {
            holder = (ViewHolder) rowView.getTag();
        }


        JSONObject item = getItem(position);

        holder.title.setText(item.getJSONObject());

        final OnClickListener titleListener = new OnClickListener() {
            @Override
            public void onClick(View v)
            {
                LinearLayout ll = (LinearLayout)v.getParent();
                TextView tv = (TextView)ll.getChildAt(0);
                Integer pos = (Integer) tv.getTag();
                ((RSSActivity)activity).makeInfo(pos);
            }
        };



        return rowView;

    }

    public static class ViewHolder {
        TextView title;
        TextView description;
    }


}

这是我的 RSSReader 类,我在其中为 RSS 的标题和 RSS 的描述构建了两个单独的 JSONObjects。

import java.util.List;


import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.Html;
import android.util.Log;


public class RSSReader {

    private final static String BOLD_OPEN = "<B>";
    private final static String BOLD_CLOSE = "</B>";
    private final static String BREAK = "<BR>";
    private final static String ITALIC_OPEN = "<I>";
    private final static String ITALIC_CLOSE = "</I>";
    private final static String SMALL_OPEN = "<SMALL>";
    private final static String SMALL_CLOSE = "</SMALL>";
    private final static int Title = 0;
    private final static int Description = 1;

    /**
     * This method defines a feed URL and then calls our SAX Handler to read the article list
     * from the stream
     * 
     * @return List<JSONObject> - suitable for the List View activity
     */
    public static List<JSONObject> getLatestRssFeed(int value){
        String feed = "http://feeds.feedburner.com/gate6?format=xml";
        int num = value;
        RSSHandler rh = new RSSHandler();
        List<Article> articles =  rh.getLatestArticles(feed);
        Log.e("RSS ERROR", "Number of articles " + articles.size());
        return fillData(articles, num);
    }





    /**
     * This method takes a list of Article objects and converts them in to the 
     * correct JSON format so the info can be processed by our list view
     * 
     * @param articles - list<Article>
     * @return List<JSONObject> - suitable for the List View activity
     * @throws JSONException 
     */
    private static List<JSONObject> fillData(List<Article> articles, int value)  {

        List<JSONObject> items = new ArrayList<JSONObject>();

        for (Article article : articles) {
            JSONObject currentItem = new JSONObject();
            try {
                if(value == 0)
                {
                    buildJSONObject(article, currentItem, Title);

                }
                else
                {
                    buildJSONObject(article, currentItem, Description);
                }
            } catch (JSONException e) {
                Log.e("RSS ERROR", "Error creating JSON Object from RSS feed");
            }
            items.add(currentItem);
        }
        return items;

    }


    /**
     * This method takes a single Article Object and converts it in to a single JSON object
     * including some additional HTML formating so they can be displayed nicely
     * 
     * @param article
     * @param current
     * @throws JSONException
     */


    private static void buildJSONObject(Article article, JSONObject current, int value) throws JSONException {

        String text = "";
        String text2 = "";
        if(value == 0)
        {
            text = article.getTitle();
            current.put("text", Html.fromHtml(buildTitle(text).toString()));

        }
        else
        {
            text = article.getDescription();
            text2 = article.getPubDate();
            current.put("text", Html.fromHtml(buildDescription(text, text2).toString()));
        }


    }


    private static StringBuffer buildTitle(String title)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(BOLD_OPEN).append(title).append(BOLD_CLOSE);
        return sb;

    }

    private static StringBuffer buildDescription(String description, String date)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(BREAK);
        sb.append(description);
        sb.append(BREAK);
        sb.append(SMALL_OPEN).append(ITALIC_OPEN).append(date).append(ITALIC_CLOSE).append(SMALL_CLOSE);

        return sb;
    }

}

希望有人能给我指出一个好的方向,这将不胜感激,因为这是我第一次做 android 开发。如果我需要从我的代码中演示其他内容,请告诉我。

【问题讨论】:

    标签: java android json listview adapter


    【解决方案1】:

    从风格上看,读取 XML RSS 提要然后转换为 JSON 似乎是不必要的麻烦。 JSON 是一种交换和存储格式,就像 XML 一样。我通常对 XML 使用轻量级的前向阅读器(SAX 阅读器)并将数据加载到由适配器读取的普通自定义 Java 对象(PO​​JO)中。

    【讨论】:

    • 是的,我刚刚看到一个教程,似乎 SAX 会是一个更好的选择。我将废弃我的大部分代码并以这种方式重建它。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多