Android 实时加载网络新闻
2016-08-17 20:35
309 查看
[b]实现效果:在Spinner中加载一个下拉列表,显示出所有类型新闻。[/b]
点击每一种类型的新闻,在布局的TestView中显示出具体内容。
首先写两个实体类,分别是从网络获取新闻的实体类和获取新闻接口的实体类。然后在activity中调用。
1.HttpUtil代码
点击每一种类型的新闻,在布局的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( 4000 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); } } } }完成效果:
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件