Недавно я пытался создать приложение для Android, которое использует JSON Objects для отображения заголовка RSS-канала в listView.Хотя у меня возникают проблемы с реализацией прослушивателя при каждом касании элемента в 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класс, в котором я создаю два своих отдельных объекта JSONObject для заголовка RSS и описания 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;
}
}
Надеюсь, что кто-то может указать мне правильное направление, это будет высоко оценено, так как это мой первый раззанимаюсь разработкой android.Дайте мне знать, если мне нужно продемонстрировать что-то еще из моего кода.