我正在尝试从网址http://timesofindia.indiatimes.com/rssfeeds/1945062111.cms获取RSS新闻 但是我在显示此URL中的图像时遇到问题。仅显示标题和日期,但不显示图像。
In this image description have some tags, I don't to show them. Only content should display
我的第二个问题是如何编辑从RSS获取的描述,因为它显示了一些和标记。我不想在我的新闻中展示它们。只应显示数据。
请在此代码中告诉我应该在哪里编辑。
package com.tandon.mynewsapp.fragments;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.tandon.mynewsapp.R;
import com.tandon.mynewsapp.activity.DetailNewsActivity;
import com.tandon.mynewsapp.activity.MainActivity;
import com.tandon.mynewsapp.adapters.NewsListAdapters;
import com.tandon.mynewsapp.app.AppController;
import com.tandon.mynewsapp.models.News;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class LatestFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private ListView listView;
private ArrayList<News> newsdata = new ArrayList<News>();
private NewsListAdapters newsAdapter;
SwipeRefreshLayout swipeRefreshLayout;
private boolean IsLoading=false;
//private int totalPages=1;
//private int currentPage =1;
private String[] newsUrl;
@Override
public void onRefresh() {
}
private enum RSSXMLTag {
TITLE, DATE, LINK, CONTENT, GUID, IGNORETAG,DESCRIPTION,IMAGE;
}
public LatestFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
newsUrl=this.getResources().getStringArray(R.array.en_latest);
listView = (ListView) rootView.findViewById(R.id.newsList);
newsAdapter = new NewsListAdapters(getActivity(),newsdata);
listView.setAdapter(newsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
News news = newsdata.get(i);
Intent intent = new Intent(getActivity(), DetailNewsActivity.class);
intent.putExtra("title",news.title);
intent.putExtra("description",news.description);
intent.putExtra("image",news.image);
intent.putExtra("date",news.postDate);
startActivity(intent);
}
});
for(int i=0;i<newsUrl.length;i++)
{
getNewsPosts(false,newsUrl[i]);
}
swipeRefreshLayout=(SwipeRefreshLayout) rootView.findViewById(R.id.swipereferesh);
swipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
newsdata.clear();
for(int i=0;i<newsUrl.length;i++)
{
getNewsPosts(false,newsUrl[i]);
}
}
}
);
swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
// News news1 = new News();
// news1.setTitle("Title 1");
// news1.setDescription("This is Description of news title 1 to check in program");
// newsdata.add(news1);
//
// News news2 = new News();
// news2.setTitle("Title 2");
// news2.setDescription("Description 2 for title 2 goes here");
// newsdata.add(news2);
//getNewsPosts();
// Inflate the layout for this fragment
return rootView;
}
public void getNewsPosts(final boolean isRefresh,String url)
{
if(!isRefresh) {
((MainActivity) getActivity()).showPDialog();
}
// String url = "http://www.oneindia.com/rss/news-india-fb.xml";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("News_World",response);
((MainActivity)getActivity()).hidePDialog();
//newsdata.clear();
RSSXMLTag currentTag = null;
IsLoading = false;
if(isRefresh)
{
//newsdata.clear();
swipeRefreshLayout.setRefreshing(false);
//currentPage = 1;
}
else
{
((MainActivity)getActivity()).hidePDialog();
}
try{
// parse xml after getting the data
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
//Abhishek Tandon Here
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= Build.VERSION_CODES.KITKAT) {
InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));
xpp.setInput(stream, null);
}
else{
InputStream stream = new ByteArrayInputStream(response.getBytes(Charset.forName("UTF-8")));
xpp.setInput(stream, null);
}
int eventType = xpp.getEventType();
News newsItem = null;
//SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, DD MMM yyyy HH:mm:ss");
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("item")) {
newsItem = new News();
currentTag = RSSXMLTag.IGNORETAG;
} else if (xpp.getName().equals("title")) {
currentTag = RSSXMLTag.TITLE;
} else if (xpp.getName().equals("link")) {
currentTag = RSSXMLTag.LINK;
} else if (xpp.getName().equals("pubDate")) {
currentTag = RSSXMLTag.DATE;
}
else if(xpp.getName().equals("enclosure")||xpp.getName().equals("img")){
currentTag = RSSXMLTag.IMAGE;
newsItem.image=xpp.getAttributeValue(0);
}
else if(xpp.getName().equals("description")){
currentTag = RSSXMLTag.DESCRIPTION;
}
} else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equals("item")) {
// format the data here, otherwise format data in
// Adapter
// Date postDate = dateFormat.parse(newsItem.postDate);
// pdData.postDate = dateFormat.format(postDate);
newsdata.add(newsItem);
} else {
currentTag = RSSXMLTag.IGNORETAG;
}
} else if (eventType == XmlPullParser.TEXT) {
String content = xpp.getText();
content = content.trim();
Log.d("NEWS_WORLD","Content ="+ content);
//Log.d("NEWS_WORLD","date ="+ newsItem.postDate);
if (newsItem != null) {
switch (currentTag) {
case TITLE:
if (content.length() != 0) {
if (newsItem.getTitle() != null) {
newsItem.title += content;
} else {
newsItem.title = content;
}
}
break;
case DESCRIPTION:
if (content.length() != 0) {
if (newsItem.description != null) {
newsItem.description += content;
} else {
newsItem.description = content;
}
}
break;
case LINK:
if (content.length() != 0) {
if (newsItem.linkUrl != null) {
newsItem.linkUrl += content;
} else {
newsItem.linkUrl = content;
}
}
break;
case DATE:
if (content.length() != 0) {
if (newsItem.postDate != null) {
newsItem.postDate += content;
} else {
newsItem.postDate = content;
}
}
break;
default:
break;
}
}
}
eventType = xpp.next();
}
Log.v("tst", String.valueOf((newsdata.size())));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newsAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
((MainActivity)getActivity()).hidePDialog();
IsLoading = false;
swipeRefreshLayout.setRefreshing(false);
if (error instanceof TimeoutError) {
Toast.makeText(getActivity(), "Request Time out error. Your internet connection is too slow to work", Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
Toast.makeText(getActivity(),"Connection Server error", Toast.LENGTH_LONG).show();
} else if (error instanceof NetworkError || error instanceof NoConnectionError) {
Toast.makeText(getActivity(),"Network connection error! Check your internet Setting", Toast.LENGTH_LONG).show();
}else if (error instanceof ParseError){
Toast.makeText(getActivity(), "Parsing error", Toast.LENGTH_LONG).show();
}
}
});
AppController.getInstance().addToRequestQueue(request);
}
}
/*
public void getNewsPosts()
{
((MainActivity)getActivity()).showPDialog();
String url = "http://rss.jagran.com/local/uttarakhand/almora.xml";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("News_World",response);
((MainActivity)getActivity()).hidePDialog();
newsdata.clear();
RSSXMLTag currentTag = null;
try{
// parse xml after getting the data
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));
xpp.setInput(stream, null);
int eventType = xpp.getEventType();
News newsItem = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE, DD MMM yyyy HH:mm:ss");
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("item")) {
newsItem = new News();
currentTag = RSSXMLTag.IGNORETAG;
} else if (xpp.getName().equals("title")) {
currentTag = RSSXMLTag.TITLE;
} else if (xpp.getName().equals("link")) {
currentTag = RSSXMLTag.LINK;
} else if (xpp.getName().equals("pubDate")) {
currentTag = RSSXMLTag.DATE;
}
else if(xpp.getName().equals("img")){
currentTag = RSSXMLTag.IMAGE;
}
else if(xpp.getName().equals("description")){
currentTag = RSSXMLTag.DESCRIPTION;
}
} else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equals("item")) {
// format the data here, otherwise format data in
// Adapter
// Date postDate = dateFormat.parse(newsItem.postDate);
// pdData.postDate = dateFormat.format(postDate);
int start = newsItem.description.indexOf("http");
int end = newsItem.description.indexOf(">");
String img = newsItem.description.substring(start, end);
Log.d("Image", img);
newsItem.image=img;
end = newsItem.description.indexOf(">");
newsItem.description= newsItem.description.substring(end + 1);
newsdata.add(newsItem);
} else {
currentTag = RSSXMLTag.IGNORETAG;
}
} else if (eventType == XmlPullParser.TEXT) {
String content = xpp.getText();
content = content.trim();
Log.d("NEWS_WORLD","Content ="+ content);
if (newsItem != null) {
switch (currentTag) {
case TITLE:
if (content.length() != 0) {
if (newsItem.getTitle() != null) {
newsItem.title += content;
} else {
newsItem.title = content;
}
}
break;
case IMAGE:
if (content.length() != 0) {
if (newsItem.image != null) {
newsItem.image += content;
} else {
newsItem.image = content;
}
}
break;
case DESCRIPTION:
if (content.length() != 0) {
if (newsItem.description != null) {
newsItem.description += content;
} else {
newsItem.description = content;
}
}
break;
case LINK:
if (content.length() != 0) {
if (newsItem.linkUrl != null) {
newsItem.linkUrl += content;
} else {
newsItem.linkUrl = content;
}
}
break;
case DATE:
if (content.length() != 0) {
if (newsItem.postDate != null) {
newsItem.postDate += content;
} else {
newsItem.postDate = content;
}
}
break;
default:
break;
}
}
}
eventType = xpp.next();
}
Log.v("tst", String.valueOf((newsdata.size())));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newsAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
((MainActivity)getActivity()).hidePDialog();
if (error instanceof TimeoutError) {
Toast.makeText(getActivity(), "Request Time out error. Your internet connection is too slow to work", Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
Toast.makeText(getActivity(),"Connection Server error",Toast.LENGTH_LONG).show();
} else if (error instanceof NetworkError || error instanceof NoConnectionError) {
Toast.makeText(getActivity(),"Network connection error! Check your internet Setting",Toast.LENGTH_LONG).show();
}else if (error instanceof ParseError){
Toast.makeText(getActivity(),"Parsing error",Toast.LENGTH_LONG).show();
}
}
});
AppController.getInstance().addToRequestQueue(request);
}
}
*/
我也在写一个NewsListAdapter代码
package com.tandon.mynewsapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import com.tandon.mynewsapp.R;
import com.tandon.mynewsapp.app.AppController;
import com.tandon.mynewsapp.models.News;
import java.util.List;
/**
* Created by Abhishek Tandon on 09-07-2016.
*/
public class NewsListAdapters extends BaseAdapter {
private List<News> newsdata; // bring news list data with id, title and data
private Context context; //where to display
public NewsListAdapters(Context context, List<News> list){
this.context = context;
this.newsdata = list;
}
@Override
public int getCount() {
return newsdata.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.news_row, null);
}
else{
view = convertView;
}
News news = newsdata.get(position);
TextView title = (TextView) view.findViewById(R.id.title);
TextView description = (TextView) view.findViewById(R.id.pub_date_time);
NetworkImageView image = (NetworkImageView) view.findViewById(R.id.imgview);
//Log.d("NEWS_WORLD",news.image);
image.setImageUrl(news.getImage(), AppController.getInstance().getImageLoader());
title.setText(news.getTitle());
description.setText(news.postDate);
return view;
}
}
答案 0 :(得分:2)
我自己解决了这个问题,无需将任何图像下载到用户的设备上。虽然他们通过将二进制数据写入正文来渲染图像。但是我可以从字符串中获取图像URL。
public String getImage() {
if (description.startsWith("<a ")) {
String cleanUrl = description.substring(description.indexOf("src=") + 5, description.indexOf("/>") - 2);
return cleanUrl;
} else {
return image;
}
}
在此代码中,我只找到“src =”和结束标记“/&gt;”之间的图像的正确URL。并将此干净的图像返回给方法。
这解决了我的问题。 :)
答案 1 :(得分:-1)
嗨似乎他们通过将二进制数据写入正文来渲染图像。因此,首先尝试下载并将图像保存到本地文件夹,然后将其绑定到图像视图。以下是示例下载代码。
public void downloadFile(String uRl) {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/FolderName");
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/FolderNameFiles", "fileName.jpg");
mgr.enqueue(request);
}
希望它会有所帮助。
答案 2 :(得分:-2)
您的图片网址的类型为:http://timesofindia.indiatimes.com/photo/507610.cms。您必须在显示之前将 .cms 替换为 .jpeg