安卓 网络新闻列表

activity_main.xml源码

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="欢迎来到梧州新闻网"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity_news.xml源码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NewsActivity">

<ListView
android:id="@+id/news_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>

</LinearLayout>



news_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/new_img"
android:layout_width="58dp"
android:layout_height="58dp"
android:layout_margin="5dp" />

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="4"
android:layout_margin="15dp">
<TextView
android:id="@+id/news_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="14dp"
android:text="我是标题"/>
<TextView
android:id="@+id/news_content"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:singleLine="false"
android:textSize="11dp"
android:text="我是内容"/>
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:layout_marginTop="30dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/type_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:textColor="#4CAF50"
android:textSize="11dp"
android:text="类型:"/>
<TextView
android:id="@+id/type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#4CAF50"
android:layout_toLeftOf="@+id/type_title"
android:textSize="11dp"
android:layout_margin="3dp"
android:text="1"/>
</LinearLayout>

</RelativeLayout>

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/comment_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:textColor="#4CAF50"
android:textSize="11dp"
android:text="评论:"/>
<TextView
android:id="@+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:layout_toLeftOf="@+id/comment_title"
android:textColor="#4CAF50"
android:textSize="11dp"
android:text="100"/>
</LinearLayout>

</RelativeLayout>

</LinearLayout>

</LinearLayout>

2.后台源码
实体类:新闻类
package com.gxuwz.newslist.entity;

public class News {

private String icon;
private String title;
private String content;
private String type;
private String comment;

public News() {
}

public News(String icon, String title, String content, String type, String comment) {
this.icon = icon;
this.title = title;
this.content = content;
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 getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getComment() {
return comment;
}

public void setComment(String comment) {
this.comment = comment;
}

@Override
public String toString() {
return "News{" +
"icon='" + icon + '\'' +
", title='" + title + '\'' +
", content='" + content + '\'' +
", type='" + type + '\'' +
", comment='" + comment + '\'' +
'}';
}
}

Http请求类
package com.gxuwz.newslist.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {

public static int http(String httpUrl, String methodType, int timeout,Handler handler){
try {
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//请求方式
conn.setRequestMethod(methodType);
//默认是毫秒
conn.setConnectTimeout(timeout);
int code = conn.getResponseCode();
if(code == 200) {
//获取服务器返回的内容,而且通过输入流的方式得到
InputStream in = conn.getInputStream();
//判断输入流有多少可以读取的字节
//int i = in.available();
//定义字节数组接收回来的数据
//byte[] b = new byte[1281];
//将输入存入字节数组
//in.read(b);
//先把字节数组转换成字符串
String result = IOUtils.toString(in, "UTF-8");
Log.i("result====",result);
//吧子线程数据回传到主线程
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("result",result);
msg.setData(bundle);
msg.what = 1;
handler.sendMessage(msg);
}
conn.disconnect();
return 1;
} catch (MalformedURLException e) {
e.printStackTrace();
return 0;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}

public static Bitmap getInternetImage(String UrlPath,Handler handler) {
Bitmap bm = null;
String urlpath = UrlPath;
// 2、获取Uri
try {
URL uri = new URL(urlpath);

// 3、获取连接对象、此时还没有建立连接
HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
// 4、初始化连接对象
// 设置请求的方法,注意大写
connection.setRequestMethod("GET");
// 读取超时
connection.setReadTimeout(5000);
// 设置连接超时
connection.setConnectTimeout(5000);
// 5、建立连接
connection.connect();

// 6、获取成功判断,获取响应码
if (connection.getResponseCode() == 200) {
// 7、拿到服务器返回的流,客户端请求的数据,就保存在流当中
InputStream is = connection.getInputStream();
// 8、从流中读取数据,构造一个图片对象GoogleAPI
bm = BitmapFactory.decodeStream(is);
// 9、把图片设置到UI主线程
// ImageView中,获取网络资源是耗时操作需放在子线程中进行,通过创建消息发送消息给主线程刷新控件;

Log.i("", "网络请求成功");

} else {
Log.v("tag", "网络请求失败");
bm = null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
}

MainActivity.jave
package com.gxuwz.newslist;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(){
@Override
public void run() {
try {
sleep(1500);
Intent intent = new Intent(MainActivity.this,NewsActivity.class);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}

NewsActivity.jave

package com.gxuwz.newslist;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gxuwz.newslist.entity.News;
import com.gxuwz.newslist.util.HttpUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewsActivity extends AppCompatActivity {

//String[] newsTitleStr = new String[]{"腾讯新闻","QQ新闻","yy新闻","XX新闻"};
// String[] newsConStr = new String[]{"腾讯新闻腾讯新闻","QQ新闻QQ新闻","yy新闻yy新闻yy新闻","XX新闻XX新闻XX新闻"};
int[] imgs = new int[]{R.mipmap.scarf,R.mipmap.kiwifruit,R.mipmap.apple,R.mipmap.cake};

ListView newsListView;

List<News> dataList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);

newsListView = findViewById(R.id.news_list);

new Thread(new Runnable() {
@Override
public void run() {
HttpUtil.http("http://www.zhou.website:8080/work05.json","GET",5000,handler);
}
}).start();
}

Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if(msg.what==1){
Bundle bundle = msg.getData();
String result = bundle.getString("result");
Gson gson = new Gson();
Type listType = new TypeToken<List<News>>(){}.getType();
List<News> newsList = gson.fromJson(result,listType);
if(newsList != null) {
dataList = newsList;
MyBaseAdapter myBaseAdapter = new MyBaseAdapter();
newsListView.setAdapter(myBaseAdapter);
}
}
}
};


class MyBaseAdapter extends BaseAdapter{

@Override
public int getCount() {
return dataList.size();
}

@Override
public News getItem(int position) {
return dataList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = View.inflate(NewsActivity.this,R.layout.news_item,null);
final ImageView img = convertView.findViewById(R.id.new_img);
TextView title = convertView.findViewById(R.id.news_title);
TextView content = convertView.findViewById(R.id.news_content);
TextView type = convertView.findViewById(R.id.type);
TextView comment = convertView.findViewById(R.id.comment);
final News news = dataList.get(position);
final Handler handler1 = new Handler() {
public void handleMessage(android.os.Message msg) {
img.setImageBitmap((Bitmap) msg.obj);
};
};
//往控件中写入内容
new Thread(){
@Override
public void run() {
Bitmap bm = HttpUtil.getInternetImage(news.getIcon(),handler1);
Message msg = new Message();
// 把bm存入消息中,发送到主线程
msg.obj = bm;
handler1.sendMessage(msg);
}
}.start();

title.setText(news.getTitle());
content.setText(news.getContent());
type.setText(news.getType());
comment.setText(news.getComment());
//将处理好的视图返回给适配器
return convertView;
}
}
}
 
posted @ 2020-05-28 20:03  周千  阅读(438)  评论(0编辑  收藏  举报