简易新闻客户端android

1.创建app\src\main\res\xml\network_security_config.xml 

目的可以访问http请求




    

2.

修改AndroidManifest.xml

加:1.//网络权限

    2. android:networkSecurityConfig="@xml/network_security_config"> //可以访问http请求




    

    
        
            
                

                
            
        
    

3.

模型

package com.glsite.newsclient.domain;

/**
 * 新闻信息实体bean
 * @author glsite.com
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class NewsItem {

    // 新闻标题
    private String title;

    // 新闻描述
    private String desc;

    // 图片路径
    private String imagePath;

    // 新闻类型
    private String type;

    // 新闻的评论数
    private int commentCount;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

    public String getType() {
        return type;
    }

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

    public int getCommentCount() {
        return commentCount;
    }

    public void setCommentCount(int commentCount) {
        this.commentCount = commentCount;
    }

    @Override
    public String toString() {
        return "NewsItem{" +
                "title='" + title + '\'' +
                ", desc='" + desc + '\'' +
                ", imagePath='" + imagePath + '\'' +
                ", type='" + type + '\'' +
                ", commentCount=" + commentCount +
                '}';
    }
}

4.设置一个网络图片并显示到控件

package com.glsite.newsclient.domain;

/**
 * 新闻信息实体bean
 * @author glsite.com
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class NewsItem {

    // 新闻标题
    private String title;

    // 新闻描述
    private String desc;

    // 图片路径
    private String imagePath;

    // 新闻类型
    private String type;

    // 新闻的评论数
    private int commentCount;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

    public String getType() {
        return type;
    }

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

    public int getCommentCount() {
        return commentCount;
    }

    public void setCommentCount(int commentCount) {
        this.commentCount = commentCount;
    }

    @Override
    public String toString() {
        return "NewsItem{" +
                "title='" + title + '\'' +
                ", desc='" + desc + '\'' +
                ", imagePath='" + imagePath + '\'' +
                ", type='" + type + '\'' +
                ", commentCount=" + commentCount +
                '}';
    }
}

5.用来解析新闻的信息

package com.glsite.newsclient;

import android.text.TextUtils;
import android.util.Xml;

import com.glsite.newsclient.domain.NewsItem;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.InputStream;
import java.util.ArrayList;

/**
 * 用来解析新闻的信息
 *
 * @author glsite.com
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
class NewsInfoParser {

    public static ArrayList getAllNewsInfos(InputStream is) throws Exception {

        ArrayList newsItems = null;
        NewsItem newsItem = null;

        // 1.获取xml文件的解析器
        XmlPullParser parser = Xml.newPullParser();
        // 2.初始化xml文件解析器
        parser.setInput(is, "utf-8");

        // 3.解析xml文件
        int type = parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_TAG:
                    if ("channel".equals(parser.getName())) {
                        // 说明解析到了最根部的标签节点
                        newsItems = new ArrayList<>();
                    } else if ("item".equals(parser.getName())){
                        newsItem = new NewsItem();
                    } else if ("title".equals(parser.getName())){
                        newsItem.setTitle(parser.nextText());
                    } else if ("description".equals(parser.getName())){
                        newsItem.setDesc(parser.nextText());
                    } else if ("image".equals(parser.getName())){
                        newsItem.setImagePath(parser.nextText());
                    } else if ("type".equals(parser.getName())){
                        newsItem.setType(parser.nextText());
                    } else if ("comment".equals(parser.getName())){
                        String countstr = parser.nextText();
                        if (TextUtils.isDigitsOnly(countstr)) {//判断countstr是不是数字
                            newsItem.setCommentCount(Integer.parseInt(countstr));
                        }
                    }

                    break;
                case XmlPullParser.END_TAG:
                    // 如果是走到了一个item的结束标签,说明一个item的数据已经准备好了,要添加到集合当中
                    if ("item".equals(parser.getName())) {
                        newsItems.add(newsItem);
                    }
                    break;
            }
            // 千万注意记得写这一句,否则就会死循环
            type = parser.next();
        }

        return newsItems;
    }
}

6.入口

package com.glsite.newsclient;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.glsite.newsclient.domain.NewsItem;
import com.glsite.newsclient.view.SmartImageView;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final int SHOW_NEWS = 1;
    private static final int LOAD_ERROR = 2;
    private LinearLayout mLLoading;
    private ListView mLv;
    private ArrayList mNewsItems;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mLLoading.setVisibility(View.INVISIBLE);
            switch (msg.what) {
                case SHOW_NEWS:
                    Toast.makeText(MainActivity.this, "加载数据成功", Toast.LENGTH_SHORT).show();
                    mAdapter.notifyDataSetChanged();
                    break;
                case LOAD_ERROR:
                    Toast.makeText(MainActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;
            }
        }
    };
    private MyNewsAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 开发步骤
        // 1.初始化界面
        // 2.获取新闻信息
        // 3.解析新闻信息->解析为具体的实体对象
        // 4.将实体对象显示到界面
        initView();
        loadNewsInfo();
    }

    /**
     * 获取新闻信息
     */
    private void loadNewsInfo() {
        new Thread() {
            @Override
            public void run() {
                try {
                    //                    Thread.sleep(50000);
                    URL url = new URL("http://192.168.1.130:8080/Day10/news.xml");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    // 设置一个读取超时时间
                    conn.setReadTimeout(20000);

                    int code = conn.getResponseCode();
                    if (code == 200) {
                        // 请求成功
                        System.out.println("请求成功");
                        InputStream is = conn.getInputStream();

                        mNewsItems = NewsInfoParser.getAllNewsInfos(is);
                        //                        System.out.println(mNewsItems);

                        // 更新界面,把新闻显示到ui上
                        Message msg = Message.obtain();
                        msg.what = SHOW_NEWS;
                        mHandler.sendMessage(msg);
                    } else {
                        // 请求失败
                        System.out.println("请求失败");
                        Message msg = Message.obtain();
                        msg.what = LOAD_ERROR;
                        mHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = LOAD_ERROR;
                    mHandler.sendMessage(msg);
                }
            }
        }.start();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        setContentView(R.layout.activity_main);
        mLLoading = findViewById(R.id.ll_loading);
        mLv = findViewById(R.id.lv_news);
        mLLoading.setVisibility(View.VISIBLE);
        mNewsItems = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            NewsItem item = new NewsItem();
//            item.setTitle("苹果发布了新手机");
//            item.setDesc("今天库克发布了新手机,引起了粉丝轰动");
//            item.setImagePath("http://192.168.1.130:8080/Day10/img/a.jpg");
//            item.setCommentCount(200);
//            item.setType("3");
//            mNewsItems.add(item);
//        }
        mAdapter = new MyNewsAdapter();
        mLv.setAdapter(mAdapter);
    }

    private class MyNewsAdapter extends BaseAdapter {

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(MainActivity.this, R.layout.news_item, null);

            // 千万要注意 view. 不写会空指针,因为不写是表示当前MainActivity的布局,当前布局是没有这些控件id资源的
            SmartImageView iv = view.findViewById(R.id.iv_img);
            TextView tv_title = view.findViewById(R.id.tv_title);
            TextView tv_desc = view.findViewById(R.id.tv_desc);
            TextView tv_type = view.findViewById(R.id.tv_type);

            NewsItem item = getItem(position);

            tv_title.setText(item.getTitle());
            tv_desc.setText(item.getDesc());
            String type = item.getType();
            iv.setImageUrlAndShow(item.getImagePath());

            if ("1".equals(type)) {
                tv_type.setText("评论:" + item.getCommentCount());
                tv_type.setBackgroundColor(Color.TRANSPARENT);
                tv_type.setTextColor(Color.BLACK);
            } else if ("2".equals(type)) {
                tv_type.setText("专题");
                tv_type.setBackgroundColor(Color.RED);
                tv_type.setTextColor(Color.WHITE);
            } else if ("3".equals(type)) {
                tv_type.setText("直播");
                tv_type.setBackgroundColor(Color.BLUE);
                tv_type.setTextColor(Color.WHITE);
            }

            // 千万要注意!!! 不要返回null
            return view;
        }

        @Override
        public NewsItem getItem(int position) {
            return mNewsItems.get(position);
        }

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

========================================================================================

2.newClient

AndroidManifest.xml




    

    
        
            
                

                
            
        
    

app\src\main\res\xml\ network_security_config.xml




    


 activity_main.xml




    

        

        

    

    
    

 news_item.xml




    

    

    

    

 NewsClient\app\src\androidTest\java\com\glsite\newsclient\ExampleInstrumentedTest.java

package com.glsite.newsclient;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

/**
 * Instrumented test, which will execute on an Android device.
 *
 * @see Testing documentation
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals("com.glsite.newsclient", appContext.getPackageName());
    }
}

NewsClient\app\src\main\java\com\glsite\newsclient\domain\NewsItem.java

package com.glsite.newsclient.domain;

/**
 * 新闻信息实体bean
 * @author glsite.com
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class NewsItem {

    // 新闻标题
    private String title;

    // 新闻描述
    private String desc;

    // 图片路径
    private String imagePath;

    // 新闻类型
    private String type;

    // 新闻的评论数
    private int commentCount;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

    public String getType() {
        return type;
    }

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

    public int getCommentCount() {
        return commentCount;
    }

    public void setCommentCount(int commentCount) {
        this.commentCount = commentCount;
    }

    @Override
    public String toString() {
        return "NewsItem{" +
                "title='" + title + '\'' +
                ", desc='" + desc + '\'' +
                ", imagePath='" + imagePath + '\'' +
                ", type='" + type + '\'' +
                ", commentCount=" + commentCount +
                '}';
    }
}

NewsClient\app\src\main\java\com\glsite\newsclient\view\SmartImageView.java

package com.glsite.newsclient.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;

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

/**
 * @author glsite.com
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class SmartImageView extends android.support.v7.widget.AppCompatImageView {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bitmap bitmap = (Bitmap) msg.obj;
            setImageBitmap(bitmap);
        }
    };

    public SmartImageView(Context context) {
        super(context);
    }

    public SmartImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SmartImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 设置一个网络图片并显示到控件
     * @param imagePath
     */
    public void setImageUrlAndShow(final String imagePath) {
        new Thread(){
            @Override
            public void run() {
                try {
                    URL url = new URL(imagePath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    Message msg = Message.obtain();
                    msg.what = 0;
                    msg.obj = bitmap;
                    mHandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

MainActivity 

package com.glsite.newsclient;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.glsite.newsclient.domain.NewsItem;
import com.glsite.newsclient.view.SmartImageView;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final int SHOW_NEWS = 1;
    private static final int LOAD_ERROR = 2;
    private LinearLayout mLLoading;
    private ListView mLv;
    private ArrayList mNewsItems;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mLLoading.setVisibility(View.INVISIBLE);
            switch (msg.what) {
                case SHOW_NEWS:
                    Toast.makeText(MainActivity.this, "加载数据成功", Toast.LENGTH_SHORT).show();
                    mAdapter.notifyDataSetChanged();
                    break;
                case LOAD_ERROR:
                    Toast.makeText(MainActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;
            }
        }
    };
    private MyNewsAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 开发步骤
        // 1.初始化界面
        // 2.获取新闻信息
        // 3.解析新闻信息->解析为具体的实体对象
        // 4.将实体对象显示到界面
        initView();
        loadNewsInfo();
    }

    /**
     * 获取新闻信息
     */
    private void loadNewsInfo() {
        new Thread() {
            @Override
            public void run() {
                try {
                    //                    Thread.sleep(50000);
                    URL url = new URL("http://192.168.1.130:8080/Day10/news.xml");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    // 设置一个读取超时时间
                    conn.setReadTimeout(20000);

                    int code = conn.getResponseCode();
                    if (code == 200) {
                        // 请求成功
                        System.out.println("请求成功");
                        InputStream is = conn.getInputStream();

                        mNewsItems = NewsInfoParser.getAllNewsInfos(is);
                        //                        System.out.println(mNewsItems);

                        // 更新界面,把新闻显示到ui上
                        Message msg = Message.obtain();
                        msg.what = SHOW_NEWS;
                        mHandler.sendMessage(msg);
                    } else {
                        // 请求失败
                        System.out.println("请求失败");
                        Message msg = Message.obtain();
                        msg.what = LOAD_ERROR;
                        mHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = LOAD_ERROR;
                    mHandler.sendMessage(msg);
                }
            }
        }.start();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        setContentView(R.layout.activity_main);
        mLLoading = findViewById(R.id.ll_loading);
        mLv = findViewById(R.id.lv_news);
        mLLoading.setVisibility(View.VISIBLE);
        mNewsItems = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            NewsItem item = new NewsItem();
//            item.setTitle("苹果发布了新手机");
//            item.setDesc("今天库克发布了新手机,引起了粉丝轰动");
//            item.setImagePath("http://192.168.1.130:8080/Day10/img/a.jpg");
//            item.setCommentCount(200);
//            item.setType("3");
//            mNewsItems.add(item);
//        }
        mAdapter = new MyNewsAdapter();
        mLv.setAdapter(mAdapter);
    }

    private class MyNewsAdapter extends BaseAdapter {

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(MainActivity.this, R.layout.news_item, null);

            // 千万要注意 view. 不写会空指针,因为不写是表示当前MainActivity的布局,当前布局是没有这些控件id资源的
            SmartImageView iv = view.findViewById(R.id.iv_img);
            TextView tv_title = view.findViewById(R.id.tv_title);
            TextView tv_desc = view.findViewById(R.id.tv_desc);
            TextView tv_type = view.findViewById(R.id.tv_type);

            NewsItem item = getItem(position);

            tv_title.setText(item.getTitle());
            tv_desc.setText(item.getDesc());
            String type = item.getType();
            iv.setImageUrlAndShow(item.getImagePath());

            if ("1".equals(type)) {
                tv_type.setText("评论:" + item.getCommentCount());
                tv_type.setBackgroundColor(Color.TRANSPARENT);
                tv_type.setTextColor(Color.BLACK);
            } else if ("2".equals(type)) {
                tv_type.setText("专题");
                tv_type.setBackgroundColor(Color.RED);
                tv_type.setTextColor(Color.WHITE);
            } else if ("3".equals(type)) {
                tv_type.setText("直播");
                tv_type.setBackgroundColor(Color.BLUE);
                tv_type.setTextColor(Color.WHITE);
            }

            // 千万要注意!!! 不要返回null
            return view;
        }

        @Override
        public NewsItem getItem(int position) {
            return mNewsItems.get(position);
        }

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

NewsInfoParser

package com.glsite.newsclient;

import android.text.TextUtils;
import android.util.Xml;

import com.glsite.newsclient.domain.NewsItem;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.InputStream;
import java.util.ArrayList;

/**
 * 用来解析新闻的信息
 *
 * @author glsite.com
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
class NewsInfoParser {

    public static ArrayList getAllNewsInfos(InputStream is) throws Exception {

        ArrayList newsItems = null;
        NewsItem newsItem = null;

        // 1.获取xml文件的解析器
        XmlPullParser parser = Xml.newPullParser();
        // 2.初始化xml文件解析器
        parser.setInput(is, "utf-8");

        // 3.解析xml文件
        int type = parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_TAG:
                    if ("channel".equals(parser.getName())) {
                        // 说明解析到了最根部的标签节点
                        newsItems = new ArrayList<>();
                    } else if ("item".equals(parser.getName())){
                        newsItem = new NewsItem();
                    } else if ("title".equals(parser.getName())){
                        newsItem.setTitle(parser.nextText());
                    } else if ("description".equals(parser.getName())){
                        newsItem.setDesc(parser.nextText());
                    } else if ("image".equals(parser.getName())){
                        newsItem.setImagePath(parser.nextText());
                    } else if ("type".equals(parser.getName())){
                        newsItem.setType(parser.nextText());
                    } else if ("comment".equals(parser.getName())){
                        String countstr = parser.nextText();
                        if (TextUtils.isDigitsOnly(countstr)) {
                            newsItem.setCommentCount(Integer.parseInt(countstr));
                        }
                    }

                    break;
                case XmlPullParser.END_TAG:
                    // 如果是走到了一个item的结束标签,说明一个item的数据已经准备好了,要添加到集合当中
                    if ("item".equals(parser.getName())) {
                        newsItems.add(newsItem);
                    }
                    break;
            }
            // 千万注意记得写这一句,否则就会死循环
            type = parser.next();
        }

        return newsItems;
    }
}

 

 

你可能感兴趣的:(android)