编写一个“新闻客户端”展示AsyncHttpClient和SmartImageView的综合应用
SmartImageView的使用
在使用SmartImageView之前,需要在网站(http://github.com/loopj/android-smart-image-view)上下载SmartImageView的源代码,然后将SmartImageView的源代码引入到自己的项目中(复制到libs文件中,然后右键Add as library)。开源SmartImageView的出现主要是为了加速从网络上加载图片,它继承自ImageView类,支持根据URL地址加载图片、支持异步加载图片、支持图片缓存等。
AsyncHttpClient的使用
在Android开发中,发送、处理Http请求十分常见,如果每次与服务器进行数据交互都需要去开启一个子线程,这样是非常麻烦的。为了解决这个问题,一些开发者开发出了开源项目——AsyncHttpClient,需要在网站(http://github.com/loopj/android-async-http)下载,和上述方法相同。AsyncHttpClient是对HttpClient的再次包装,AsyncHttpClient的特点有发送异步Http请求、Http请求发生在UI线程之外、内部采用了线程池来处理并发送请求,而且它使用起来比HttpClient更方便。
此外还需要导入一个包httpcore-4.4.4
实验效果图:
1、创建程序
在activity_main.xml布局文件中创建程序的主界面,主要包含了提示用户数据正在加载中的ProgressBar、TextView以及用于展示新闻信息的ListView,具体代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cn.edu.bzu.anew.MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/loading"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="invisible">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="正在加载信息..." />
</LinearLayout>
<ListView
android:id="@+id/lv_news"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</RelativeLayout>
2、创建ListView Item的布局
在layout文件夹下创建ListView 的Item布局文件news_item.xml,布局中使用到了自定义控件SmartImageView和三个分别用于展示新闻标题、新闻内容以及新闻评论数的TextView。其中指定了SmartImageView的一个属性android:scaleType,用来控制图片来匹配View的大小的。具体代码如下:
<?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="65dp">
<com.loopj.android.image.SmartImageView
android:id="@+id/siv_icon"
android:layout_width="80dp"
android:layout_height="60dp"
android:scaleType="centerCrop"
android:src="@mipmap/ic_launcher"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"></com.loopj.android.image.SmartImageView>
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="@id/siv_icon"
android:ellipsize="end"
android:maxLength="20"
android:singleLine="true"
android:text="我是标题"
android:textColor="#000000"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_title"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@id/siv_icon"
android:ellipsize="end"
android:maxLength="16"
android:maxLines="1"
android:text="我是描述"
android:textColor="#99000000"
android:textSize="14sp" />
<TextView
android:id="@+id/tv_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="10dp"
android:text="评论"
android:textColor="#99000000"
android:textSize="12sp" />
</RelativeLayout>
3、界面逻辑代码的设计与实现
在MainActivity中编写界面交互代码,具体代码如下:
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.UnsupportedEncodingException;
import java.util.List;
import cn.edu.bzu.anew.Tools.JsonParse;
import cn.edu.bzu.anew.adapter.NewsAdapter;
import cn.edu.bzu.anew.entity.NewsInfo;
public class MainActivity extends AppCompatActivity {
private ListView lvNews;
private List<NewsInfo> newsInfos;
private LinearLayout loading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvNews=(ListView)findViewById(R.id.lv_news);
loading=(LinearLayout)findViewById(R.id.loading);
fillData();
}
//使用AsyncHttpClient访问网络
private void fillData(){
//创建AsyncHttpClient的实例
AsyncHttpClient client =new AsyncHttpClient();
//使用get方式请求
client.get("http://10.61.20.106:8080/NewsInfo.json",new AsyncHttpResponseHandler(){
@Override
//请求成功
public void onSuccess(int i, org.apache.http.Header[] headers, byte[] bytes) {
try{
String json=new String(bytes,"utf-8");
newsInfos= JsonParse.getNewsInfo(json);
if(newsInfos==null){
Toast.makeText(MainActivity.this,"解析失败", Toast.LENGTH_LONG).show();
}else{
//更新界面
loading .setVisibility(View.INVISIBLE);
lvNews.setAdapter(new NewsAdapter(MainActivity.this,newsInfos));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int i, org.apache.http.Header[] headers, byte[] bytes, Throwable throwable) {
}
} );
}
}
4、配置Tomcat服务器
http://tomcate.apache.org/下载并通过startup.bat启动服务器。在webapps/Root文件夹下放入JSON文件和所需的图片素材images文件夹
5、创建JSON文件
通过http://www.qqe2.com/json在线编辑器,其中代码如下:
[
{
"icon": "http://10.61.20.106:8080/images/a.jpg",
"title": "科技温暖世界",
"content": "进入一个更有爱的领域",
"type": "1",
"comment": "69"
},
{
"icon": "http://10.61.20.106:8080/images/b.jpg",
"title": "《神武》",
"content": "新美术资源盘点,视觉新体验",
"type": "2",
"comment": "35"
},
{
"icon": "http://10.61.20.106:8080/images/c.jpg",
"title": "南北车正式公布合并",
"content": "南北车将于今日正式公布合并",
"type": "3",
"comment": "2"
},
{
"icon": "http://10.61.20.106:8080/images/d.jpg",
"title": "萌呆了!汪星人抱玩偶酣睡",
"content": "汪星人抱玩偶酣睡,萌翻网友",
"type": "1",
"comment": "25"
},
{
"icon": "http://10.61.20.106:8080/images/e.jpg",
"title": "风力发电进校园",
"content": "风力发电普进校园",
"type": "2",
"comment": "26"
},
{
"icon": "http://10.61.20.106:8080/images/f.jpg",
"title": "地球一小时",
"content": "地球熄灯一小时",
"type": "1",
"comment": "23"
},
{
"icon": "http://10.61.20.106:8080/images/g.jpg",
"title": "最美公路",
"content": "最美公路,难以想象",
"type": "1",
"comment": "23"
}
]
6、创建实体类
在entity包下创建实体类NewsInfo,其中代码如下:
public class NewsInfo {
private String icon;
private String title;
private String description;
private int type;
private long comment;
public NewsInfo(String icon, String title, String description, int type, long comment) {
this.icon = icon;
this.title = title;
this.description = description;
this.type = type;
this.comment = comment;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public long getComment() {
return comment;
}
public void setComment(long comment) {
this.comment = comment;
}
}
7、创建工具类
在tools包下创建工具类JsonParse,负责解析JSON数据,其中代码如下:
package cn.edu.bzu.anew.Tools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import cn.edu.bzu.anew.entity.NewsInfo;
/**
* Created by Administrator on 2017/5/18.
*/
public class JsonParse {
public static List<NewsInfo>getNewsInfo(String json){
//使用gson库解析JSON数据
Gson gson =new Gson();
//创建一个TypeToken的匿名子类对象,并调用对象的getType()方法
Type listType=new TypeToken<List<NewsInfo>> (){
}.getType();
//把获取到的信息集合存到newsInfos中
List<NewsInfo>newsInfos=gson.fromJson(json,listType);
return newsInfos;
}
}
8、创建适配器
在adapter包下创建NewsAdapter类,其中代码如下:
package cn.edu.bzu.anew.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.loopj.android.image.SmartImageView;
import java.util.List;
import cn.edu.bzu.anew.R;
import cn.edu.bzu.anew.entity.NewsInfo;
//ListView适配器
public class NewsAdapter extends ArrayAdapter<NewsInfo>{
public NewsAdapter(Context context, List<NewsInfo> objects) {
super(context, R.layout.news_item, objects);
}
@NonNull
@Override
//得到ListView的条目视图
public View getView(int position, View convertView, ViewGroup parent) {
NewsInfo newsinfo= getItem(position);//传递position,获取当前位置对应的newsinfo新闻信息
View view=null;
viewHolder viewHolder;
if(convertView==null){ //判断convertView中是否加载了布局,有没有缓存。为空说明没有缓存
view=LayoutInflater.from(getContext()).inflate(R.layout.news_item,null);
viewHolder=new viewHolder();
viewHolder.siv= (SmartImageView) view.findViewById(R.id.siv_icon);
viewHolder.tv_title= (TextView) view.findViewById(R.id.tv_title);
viewHolder.tv_description= (TextView) view.findViewById(R.id.tv_description);
viewHolder.tv_type= (TextView) view.findViewById(R.id.tv_type);
view.setTag(viewHolder); //保存
}else{
view=convertView;
viewHolder=(viewHolder) view.getTag();
}
viewHolder.siv.setImageUrl(newsinfo.getIcon());
viewHolder.tv_title.setText(newsinfo.getTitle());//传递题目
viewHolder.tv_description.setText(newsinfo.getDescription());
viewHolder.tv_type.setText(newsinfo.getType()+"");
return view;
}
class viewHolder{//添加类,封装需要查找的控件
TextView tv_title;
TextView tv_description;
TextView tv_type;
SmartImageView siv;
}
}