3秒后自动更新头条

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TextView text_toutiao;
    private ListView listView;

    private int index = 0;

    //写一个集合记录所有的头条数据
    private List<String> list = new ArrayList<>();

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0){
                String json = (String) msg.obj;

                Log.i("json---",json);

                //解析...android中json格式的数据只有两种,,一种是{}对应的,解析出来是对象;;;一种是[]对应的,这种是数组或者集合
                //1.集合或者数据在json原生解析,使用的JSONArray这个类...{}对应的在原声解析里面是JSONObject

                //2.使用gson解析数组格式的json字符串
                Gson gson = new Gson();
                Type type = new TypeToken<List<String>>() {}.getType();

                List<String> jsonList = gson.fromJson(json,type);

                Log.i("----",jsonList.size()+"长度");

                try {
                    JSONArray jsonArray = new JSONArray(json);

                    //遍历这个json格式的数组
                    for (int i=0;i<jsonArray.length();i++){

                        String string = jsonArray.getString(i);
                        //添加到集合里面去
                        list.add(string);
                    }

                    //设置第一条数据的显示
                    text_toutiao.setText(list.get(index));
                    //发送一个延时的消息
                    handler.sendEmptyMessageDelayed(1,3000);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else  if (msg.what == 1){
                //接收到延时消息
                index ++;

                //取余
                index = index%list.size();

                text_toutiao.setText(list.get(index));

                //发送一个延时的消息
                handler.sendEmptyMessageDelayed(1,3000);
            }
        }
    };

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

        text_toutiao = (TextView) findViewById(R.id.text_toutiao);
        listView = (ListView) findViewById(R.id.list_view);

        //网络上获取头条的数据....HttpUrlConnection+Handler请求,接口地址http://www.toutiao.com/hot_words/
        getTouTiao();

        //展示listView的数据
        getListViewData();

    }

    private void getListViewData() {

        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {

                try {
                    SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());

                    HttpClient client = new DefaultHttpClient();

                    HttpGet httpGet = new HttpGet("https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1");

                    HttpResponse httpResponse = client.execute(httpGet);

                    int statusCode = httpResponse.getStatusLine().getStatusCode();

                    if (statusCode == 200){
                        InputStream inputStream = httpResponse.getEntity().getContent();

                        String json = streamToString(inputStream,"utf-8");

                        return json;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                Gson gson = new Gson();


                DataDataBean dataDataBean = gson.fromJson(s, DataDataBean.class);

                List<DataDataBean.NewslistBean> newslist = dataDataBean.getNewslist();

                //设置适配器
                MyAdapter myAdapter = new MyAdapter(newslist, MainActivity.this);

                listView.setAdapter(myAdapter);

            }
        };

        asyncTask.execute();

    }

    /**
     * 网络上获取头条的数据
     */
    private void getTouTiao() {
        new Thread(){
            @Override
            public void run() {
                try {
                    URL url = new URL("http://www.toutiao.com/hot_words/");

                    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");

                        //字符串发送到主线程解析
                        Message message = Message.obtain();
                        message.what = 0;
                        message.obj = json;
                        handler.sendMessage(message);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();

    }

    /**
     * 将字节流转为字符串
     * @param inputStream
     * @param charset 指定编码格式
     * @return
     */
    private String streamToString(InputStream inputStream, String charset) {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String s;
            StringBuilder builder = new StringBuilder();
            while ((s=bufferedReader.readLine()) != null){
                builder.append(s);
            }

            //关
            bufferedReader.close();


            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

发布了8 篇原创文章 · 获赞 0 · 访问量 2347
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览