Android 實時加載網絡新聞

實現效果:在Spinner中加載一個下拉列表,顯示出所有類型新聞。

                   點擊每一種類型的新聞,在佈局的TestView中顯示出具體內容。

首先寫兩個實體類,分別是從網絡獲取新聞的實體類和獲取新聞接口的實體類。然後在activity中調用。

1.HttpUtil代碼

package com.example.administrator.jreduch09.Class;

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.URL;

public class HttpUtil {
    public static String GetHttp(String params){
        BufferedReader reader=null;
        HttpURLConnection con = null;
        InputStream is = null;
        StringBuilder sbd = new StringBuilder();
        String str="";
        try {
            URL url = new URL(params);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("apikey","5b46143955a4b1ff1b470a94315625cd");
            con.setConnectTimeout(5 * 1000);
            con.setReadTimeout(5 * 1000);
            if (con.getResponseCode() == 200) {
                is = con.getInputStream();
                reader=new BufferedReader(new InputStreamReader(is,"UTF-8"));
                while ((str=reader.readLine())!=null){
                    sbd.append(str);
                    sbd.append("\r\n");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                con.disconnect();
            }
        }
        return sbd.toString();
    }
}
2.UrlUtil代碼:

package com.example.administrator.jreduch09.Class;

public class UrlUtil {

    //獲取 頻道的網絡接口
    public  static String channelUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";
    /*獲取 頻道對應新聞的網絡接口
      get 請求參數:
       channelId    : 新聞頻道id,必須精確匹配
       channelName  :新聞頻道名稱,可模糊匹配
       title        :新聞標題,模糊匹配
       page         :頁數,默認1。每頁最多20條記
       needContent  : 是否需要返回正文,1爲需要
       needHtml     :是否需要返回正文的html格式,1爲需要
     */
    public  static String newsUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news";

}
主佈局:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.administrator.jreduch09.HttpJsonActivity">
       <Spinner
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:id="@+id/channel">
       </Spinner>
       <ScrollView
         android:layout_width="match_parent"
         android:layout_height="match_parent"
          android:layout_below="@+id/channel">
         <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/show"/>
       </ScrollView>
</RelativeLayout>
代碼:

package com.example.administrator.jreduch09;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.jreduch09.Class.HttpUtil;
import com.example.administrator.jreduch09.Class.UrlUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpJsonActivity extends AppCompatActivity {
    private TextView show;
    private Spinner channel;
    private SimpleAdapter sa;
    private List<Map<String,String>> channelList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_json);
        channel= (Spinner) findViewById(R.id.channel);
        show= (TextView) findViewById(R.id.show);
        channelList=new ArrayList<>();
        sa=new SimpleAdapter(this,channelList,android.R.layout.simple_spinner_item
        ,new String[]{"name"},new int[]{android.R.id.text1});
        channel.setAdapter(sa);
        new GetChannel().execute();
        channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
              Map map=channelList.get(position);
                map.get("name");
                String  channelName = (String) map.get("name");
                String channelId = (String) map.get(channelName);
                String url=UrlUtil.newsUrl+"?channelId="
                        +channelId+"&channelName="+channelName+"&needContent=1"
                        +"needHtml=1";
                new GetNews().execute(url);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }
    public class GetChannel extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.GetHttp(UrlUtil.channelUrl);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("")){
                Toast.makeText(getBaseContext(),"網絡加載異常",Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject obj=new JSONObject(s);
                JSONObject obj1= obj.getJSONObject("showapi_res_body");
                JSONArray ja=obj1.getJSONArray("channelList");
                for(int i=0;i<ja.length();i++){
                    JSONObject channelObj= (JSONObject) ja.get(i);
                    String name=channelObj.getString("name");
                    String id=channelObj.getString("channelId");
                    Map map=new HashMap();
                    map.put("name",name);
                    map.put(name,id);
                    channelList.add(map);
                }
                sa.notifyDataSetChanged();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    public  class GetNews extends  AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.GetHttp(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            show.setText(s);
            if(s.equals("")){
                show.setText("沒有數據");
                return;
            }else {
                show.setText(s);
            }
        }
    }
}
完成效果:






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章