获取解析聚合新闻数据,并显示到主界面上(简易新闻 二)
关于之前的功能实现可以从制作简易新闻App导航篇中查看
先上一下最终效果图:
关于界面的搭建请看上一篇
使用Fragment+ViewPager +TabLayout自制简易新闻 app主要框架(简易新闻 一)
准备事项
1. 需要在聚合数据上注册帐号,然后申请获取聚合数据新闻头条这个API,等到申请成功后,可以在我的接口中找到新闻头条API,并可以看到自己的AppKey,点击测试发送请求,将获取到的内容复制下来。
如下图:
2. 打开Android Studio ,点击左上角的file,在出现的选项中点击settings/Plugins中选择Browse,在在如下弹出的页面中选择搜索GsonFromat,然后选择安装 。
3. 在项目中新建一个 NewsBean.class,在打开的空白类中,右键选择Generate如图:
选择GsonFormat,然后将复制到的新闻json内容放入进去,点击ok,会自动生成聚合数据新闻头条API实体类。
聚合数据新闻头条json实体类NewsBean.class
package com.example.frametest.json;
import java.util.List;
public class NewsBean {
private String reason;
private ResultBean result;
private int error_code;
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public static class ResultBean {
private String stat;
private List<DataBean> data;
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String uniquekey;
private String title;
private String date;
private String category;
private String author_name;
private String url;
private String thumbnail_pic_s;
private String thumbnail_pic_s02;
private String thumbnail_pic_s03;
public String getUniquekey() {
return uniquekey;
}
public void setUniquekey(String uniquekey) {
this.uniquekey = uniquekey;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAuthor_name() {
return author_name;
}
public void setAuthor_name(String author_name) {
this.author_name = author_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnail_pic_s() {
return thumbnail_pic_s;
}
public void setThumbnail_pic_s(String thumbnail_pic_s) {
this.thumbnail_pic_s = thumbnail_pic_s;
}
public String getThumbnail_pic_s02() {
return thumbnail_pic_s02;
}
public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
this.thumbnail_pic_s02 = thumbnail_pic_s02;
}
public String getThumbnail_pic_s03() {
return thumbnail_pic_s03;
}
public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
this.thumbnail_pic_s03 = thumbnail_pic_s03;
}
}
}
}
项目结构图
第一步修改list_item.xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_vertical_align_top"
app:elevation="8dp" />
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
第二步修改NewsFragment.class类
package com.example.frametest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.frametest.json.NewsBean;
import com.example.frametest.TabAdapter.MyTabAdapter;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;
public class NewsFragment extends Fragment {
private FloatingActionButton fab;
private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
private List<NewsBean.ResultBean.DataBean> list;
private static final int UPNEWS_INSERT = 0;
@SuppressLint("HandlerLeak")
private Handler newsHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
String uniquekey,title,date, category,author_name,url,thumbnail_pic_s,thumbnail_pic_s02,thumbnail_pic_s03;
switch (msg.what){
case UPNEWS_INSERT:
list = ((NewsBean) msg.obj).getResult().getData();
MyTabAdapter adapter = new MyTabAdapter(getActivity(),list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
break;
}
}
};
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_item,container,false);
listView = (ListView) view.findViewById(R.id.listView);
fab = (FloatingActionButton) view.findViewById(R.id.fab);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
return view;
}
@SuppressLint("HandlerLeak")
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
onAttach(getActivity());
//获取传递的值
Bundle bundle = getArguments();
final String data = bundle.getString("name","top");
//置顶功能
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listView.smoothScrollToPosition(0);
}
});
//下拉刷新
swipeRefreshLayout.setColorSchemeResources(R.color.colorRed);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
// 下一步实现从数据库中读取数据刷新到listview适配器中
}
},1000);
}
});
//异步加载数据
getDataFromNet(data);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//获取点击条目的路径,传值显示webview页面
String url = list.get(position).getUrl();
String uniquekey = list.get(position).getUniquekey();
final NewsBean.ResultBean.DataBean dataBean = (NewsBean.ResultBean.DataBean) list.get(position);
Intent intent = new Intent(getActivity(),WebActivity.class);
intent.putExtra("url",url);
startActivity(intent);
}
});
}
private void getDataFromNet(final String data){
@SuppressLint("StaticFieldLeak") AsyncTask<Void,Void,String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String path = "http://v.juhe.cn/toutiao/index?type="+data+"&key=547ee75ef186fc55a8f015e38dcfdb9a";
URL url = null;
try {
url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == 200){
InputStream inputStream = connection.getInputStream();
String json = streamToString(inputStream,"utf-8");
return json;
} else {
System.out.println(responseCode);
return "已达到今日访问次数上限";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
protected void onPostExecute(final String result){
new Thread(new Runnable() {
@Override
public void run() {
NewsBean newsBean = new Gson().fromJson(result,NewsBean.class);
System.out.println(newsBean.getError_code());
if ("10012".equals(""+newsBean.getError_code())){
//下一篇将要实现从数据库加载数据
}
Message msg=newsHandler.obtainMessage();
msg.what=UPNEWS_INSERT;
msg.obj = newsBean;
newsHandler.sendMessage(msg);
}
}).start();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
};
task.execute();
}
private String streamToString(InputStream inputStream, String charset){
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String s = null;
StringBuilder builder = new StringBuilder();
while ((s = bufferedReader.readLine()) != null){
builder.append(s);
}
bufferedReader.close();
return builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
第三步添加加载图片与解析json的引用
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
其中图片加载使用的第三方库的github地址为:https://github.com/nostra13/Android-Universal-Image-Loader
第四步添加新闻图片格式文件
在res/layout中新建一个item_layout01.xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<ImageView
android:id="@+id/image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentRight="true"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_toLeftOf="@id/image"
android:layout_marginTop="8dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="8dp"
android:text="Title"
android:textSize="18sp"/>
<TextView
android:id="@+id/author_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/title"
android:layout_marginLeft="10dp"
android:layout_marginBottom="8dp"
android:text="Author"
android:textSize="13sp"/>
<!--<TextView
android:id="@+id/tvTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/ivPic"
android:layout_below="@id/tvTitle"
android:layout_marginRight="10dp"
android:text="Time"
android:textSize="15sp"/>-->
</RelativeLayout>
在res/layout中新建一个item_layout02.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textSize="18sp"
android:id="@+id/title"
android:textStyle="bold"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="horizontal"
android:layout_marginTop="18dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_weight="1"
android:layout_width="0dp"
android:id="@+id/image001"
android:layout_height="120dp" />
<ImageView
android:layout_weight="1"
android:layout_width="0dp"
android:id="@+id/image002"
android:layout_height="120dp"
android:layout_marginLeft="3dp"/>
<ImageView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_marginLeft="3dp"/>
</LinearLayout>
</LinearLayout>
在res/layout中新建一个item_layout03.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textSize="18sp"
android:id="@+id/title"
android:textStyle="bold"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="horizontal"
android:layout_marginTop="18dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_weight="1"
android:id="@+id/image01"
android:layout_width="0dp"
android:layout_height="120dp" />
<ImageView
android:layout_weight="1"
android:id="@+id/image02"
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_marginLeft="3dp"/>
<ImageView
android:layout_weight="1"
android:id="@+id/image03"
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_marginLeft="3dp"/>
</LinearLayout>
</LinearLayout>
第五步添加listview的适配器MyTabAdapter.class类
根据图片的数量可知有三种不同ViewType类型
package com.example.frametest.TabAdapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.frametest.R;
import com.example.frametest.json.NewsBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import java.util.List;
public class MyTabAdapter extends BaseAdapter {
private List<NewsBean.ResultBean.DataBean> list;
private Context context;
private int IMAGE_01 =0;
private int IMAGE_02 = 1;
private int IMAGE_03 = 2;
public MyTabAdapter(Context context, List<NewsBean.ResultBean.DataBean> list){
this.context = context;
this.list = list;
//配置lmageloader类
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context));
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public int getItemViewType(int position) {
if (list.get(position).getThumbnail_pic_s() != null &&
list.get(position).getThumbnail_pic_s02() !=null &&
list.get(position).getThumbnail_pic_s03() !=null){
return IMAGE_03;
}else if (list.get(position).getThumbnail_pic_s() !=null &&
list.get(position).getThumbnail_pic_s02() !=null){
return IMAGE_02;
}
return IMAGE_01;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == IMAGE_01){
Image01_ViewHolder holder;
if (convertView == null){
convertView =View.inflate(context, R.layout.item_layout01,null);
holder =new Image01_ViewHolder();
//查找控件
holder.author_name = (TextView) convertView.findViewById(R.id.author_name);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.image = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
}else {
holder = (Image01_ViewHolder) convertView.getTag();
}
//获取数据重新赋值
holder.title.setText(list.get(position).getTitle());
holder.author_name.setText(list.get(position).getAuthor_name());
ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(),holder.image,getOption());
}else if (getItemViewType(position) == IMAGE_02){
Image02_ViewHolder holder;
if (convertView == null){
convertView =View.inflate(context, R.layout.item_layout02,null);
holder =new Image02_ViewHolder();
//查找控件
holder.image002 = (ImageView) convertView.findViewById(R.id.image002);
holder.image001 = (ImageView) convertView.findViewById(R.id.image001);
holder.title = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
}else {
holder = (Image02_ViewHolder) convertView.getTag();
}
//获取数据重新赋值
holder.title.setText(list.get(position).getTitle());
ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(),holder.image001,getOption());
ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s02(),holder.image002,getOption());
} else {
Image03_ViewHolder holder;
if (convertView == null){
convertView =View.inflate(context, R.layout.item_layout03,null);
holder =new Image03_ViewHolder();
//查找控件
holder.image01 = (ImageView) convertView.findViewById(R.id.image01);
holder.image02 = (ImageView) convertView.findViewById(R.id.image02);
holder.image03 = (ImageView) convertView.findViewById(R.id.image03);
holder.title = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
}else {
holder = (Image03_ViewHolder) convertView.getTag();
}
//获取数据重新赋值
holder.title.setText(list.get(position).getTitle());
ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(),holder.image01,getOption());
ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s02(),holder.image02,getOption());
ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s03(),holder.image03,getOption());
}
return convertView;
}
//配置图片加载失败和加载中显示的Android小机器人logo
public static DisplayImageOptions getOption() {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
.showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
.showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
.resetViewBeforeLoading(true) // default 设置图片在加载前是否重置、复位
.delayBeforeLoading(1000) // 下载前的延迟时间
.cacheInMemory(true) // default 设置下载的图片是否缓存在内存中
.cacheOnDisk(true) // default 设置下载的图片是否缓存在SD卡中
.imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示
.bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型
.build();
return options;
}
static class Image01_ViewHolder{
TextView title,author_name;
ImageView image;
}
static class Image02_ViewHolder{
TextView title;
ImageView image001,image002;
}
static class Image03_ViewHolder{
TextView title;
ImageView image01,image02,image03;
}
}
第六步添加网络权限
在AndroidManifest.xml文件中添加权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
好了,本篇到此结束,总体来说还是比较容易实现的,下篇将会实现连接数据库,并实现用户交互的的一些功能(注册,个人收藏以及下拉刷新等等)。
连接数据库,实现下拉刷新(简易新闻 三)
项目源码GitHub地址为:https://github.com/ziruiliu1/MyBlog
新做出的改动,去掉listView的间隔线
修改list_item.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@color/colorWhite"
android:scrollbars="none">
//对listview进行添加divider属性修改间隔线为透明白色
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_vertical_align_top"
app:elevation="8dp" />
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
修改后的效果图:
本人博客地址:www.tobey-r1.top