Android ListView JSONObject 问题

发布于 2024-11-04 06:46:03 字数 7902 浏览 0 评论 0原文

最近我一直在尝试创建一个 Android 应用程序,它使用 JSON 对象在 listView 中显示 RSS 提要的标题。尽管我遇到的问题是每当触摸 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 描述构建了两个单独的 JSONObject。

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 开发。如果我需要从我的代码中演示其他内容,请告诉我。

recently I been trying to create an android app that uses JSON Objects to display the title of an RSS feed in a listView. Though what I'm having issues with is the implementation of an listener whenever an item in the listView is touched to display the JSON Object that has the format for the description of the RSS feed stored in it. I have been fiddling with the adapter and had little to no success. Hope someone can help me out.

Here is my RSSActivity class that I made:

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);

    }



}

Here is my 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;
    }


}

and here is my RSSReader class where I build my two separate JSONObjects for the Title of the RSS and the Description of the RSS.

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;
    }

}

Hope someone can point me into a good direction this will be greatly appreciated since this is my first time doing android development. Let me know if I need to demonstrate something else from my code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁对谁错谁最难过 2024-11-11 06:46:03

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

Stylistically it seems an unnecessary hassle to read in XML RSS feeds and then convert to JSON. JSON is an interchange and storage format, just like XML. I generally use a lightweight forward-reader (SAX reader) for the XML and load the data into plain custom Java objects (POJOs) which are read by the adapter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文