17-07-31 android 方法 如何引用链接获取json数据(改进版)
2016-07-31 14:04
477 查看
07-29写的方法今回头一看太烂了,今天对代码进行了改进,当然还需要后续进一步的完善。
MyThread.java
HomePageInfo.java
CategoryInfo.java
LinearItemView.java 用来定义linearItemView_xml 元素,简化了ui的代码
GridItemView.java 同上
activity_main.xml 对比后比原来简洁多了,可读性也高了
Linear_item.xml 是上面定义的include元素,
在activity_main中使用时要保证属性都一样,不一样的属性放到外层单独定义
注意下面最外层的使用方法:包名 + 类名
grid_item.xml 同上
<com.example.juren.GridItemView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="7dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="7dp"
android:background="@drawable/background"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="@+id/tIcon"
android:layout_width="58dp"
android:layout_height="58dp"
android:layout_marginLeft="19dp"
android:layout_marginRight="19dp"
android:layout_marginTop="19dp"
android:src="@drawable/xxhl" />
<TextView
android:id="@+id/tTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="19dp"
android:layout_marginTop="14dp"
android:text="@string/hello6"
android:textColor="#333333"
android:textSize="14dp" >
</TextView>
</com.example.juren.GridItemView>
改良后的代码如上,还需要完善继续改进...
MainActivity 的方法部分改进了
package com.example.juren; import java.io.InputStream; import java.net.HttpURLConnection; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.example.juren.MyThread.ResponseInfo; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; /* { "categorys": [ { "id": "1", "name": "综合", "icon": "http://114.55.116.95:8080/shusheng/images/zhonghe.png", "short_desc": "十八般武器样样精通", "desc": "NULL" }, { "id": "2", "name": "地理", "icon": "http://114.55.116.95:8080/shusheng/images/dili.png", "short_desc": "坐地日行八万里,巡天遥看一千河", "desc": "NULL" }, { "id": "3", "name": "文学", "icon": "http://114.55.116.95:8080/shusheng/images/wenxue.png", "short_desc": "NULL", "desc": "NULL" }, { "id": "4", "name": "体育", "icon": "http://114.55.116.95:8080/shusheng/images/tiyu.png", "short_desc": "NULL", "desc": "NULL" }, { "id": "5", "name": "生活", "icon": "http://114.55.116.95:8080/shusheng/images/shenghuo.png", "short_desc": "NULL", "desc": "NULL" }, { "id": "6", "name": "生物", "icon": "http://114.55.116.95:8080/shusheng/images/shengwu.png", "short_desc": "NULL", "desc": "NULL" }, { "id": "7", "name": "军事", "icon": "http://114.55.116.95:8080/shusheng/images/junshi.png", "short_desc": "NULL", "desc": "NULL" }, { "id": "8", "name": "历史", "icon": "http://114.55.116.95:8080/shusheng/images/lishi.png", "short_desc": "NULL", "desc": "NULL" } ], "status": "success" } */ public class MainActivity extends Activity { public static final String URL = "http://114.55.116.95:8080/shusheng/home_page"; private Handler mHandler = new MyHandler(); public LinearItemView mItem1; public LinearItemView mItem2; public GridItemView tItem1; public GridItemView tItem2; public GridItemView tItem3; public GridItemView tItem4; public GridItemView tItem5; public GridItemView tItem6; private Map<String, Bitmap> mCache = new HashMap<String, Bitmap>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mItem1 = (LinearItemView) findViewById(R.id.include1); mItem2 = (LinearItemView) findViewById(R.id.include2); tItem1 = (GridItemView) findViewById(R.id.include_1); tItem2 = (GridItemView) findViewById(R.id.include_2); tItem3 = (GridItemView) findViewById(R.id.include_3); tItem4 = (GridItemView) findViewById(R.id.include_4); tItem5 = (GridItemView) findViewById(R.id.include_5); tItem6 = (GridItemView) findViewById(R.id.include_6); MyThread thread = new MyThread(URL, mHandler); thread.start(); } public class MyHandler extends Handler { public void handleMessage(Message msg) { if (msg.what == 1) { ResponseInfo response = (ResponseInfo) msg.obj; if (response.status.equals(MyThread.STATUS_FAILED)) { setfailedUIDatas(response); } else { HomePageInfo homePageInfo = parseHomePageInfo(response); setSuccessUIDatas(homePageInfo); // TODO 下载相关图片 loadImages(homePageInfo); } } else if (msg.what == 1000) { Bitmap bmp = mCache.get(msg.obj); if(msg.arg1 == 1) { mItem1.setIcons(bmp); } if(msg.arg1 == 2) { mItem2.setIcons(bmp); } if(msg.arg1 == 3) { tItem1.setIcons(bmp); } if(msg.arg1 == 4) { tItem2.setIcons(bmp); } if(msg.arg1 == 5) { tItem3.setIcons(bmp); } if(msg.arg1 == 6) { tItem4.setIcons(bmp); } if(msg.arg1 == 7) { tItem5.setIcons(bmp); } if(msg.arg1 == 8) { tItem6.setIcons(bmp); } } } } public void setfailedUIDatas(ResponseInfo response) { } public void loadImages(final HomePageInfo homePageInfo) { new Thread() { public void run() { //匿名内部类方法中,想要使用方法参数,需要把参数声明为final类型 for(int i = 0; i < homePageInfo.categorys.size(); i ++) { CategoryInfo item = homePageInfo.categorys.get(i); String url = item.icon; Bitmap bm1 = getHttpBitmap(url); mCache.put(url,bm1); Message msg = new Message(); msg.obj = url;//在HandlMessage中用于找到对应的Bitmap msg.what = 1000; msg.arg1 = i+1;//在HandlMessage中找到对应的 ImageView mHandler.sendMessage(msg); } } }.start(); } public void setSuccessUIDatas(HomePageInfo homePageInfo) { // TODO Auto-generated method stub Log.i("aaa", "size = " + homePageInfo.categorys.size()); for (int i = 0; i < homePageInfo.categorys.size(); i++) { CategoryInfo catInfo = homePageInfo.categorys.get(i); if (i == 0) { mItem1.setDatas(catInfo.name, catInfo.short_desc, catInfo.desc); } if (i == 1) { mItem2.setDatas(catInfo.name, catInfo.short_desc, catInfo.desc); } if (i == 2) { tItem1.setDatas(catInfo.name); } if (i == 3) { tItem2.setDatas(catInfo.name); } if (i == 4) { tItem3.setDatas(catInfo.name); } if (i == 5) { tItem4.setDatas(catInfo.name); } if (i == 6) { tItem5.setDatas(catInfo.name); } if (i == 7) { tItem6.setDatas(catInfo.name); } } } public HomePageInfo parseHomePageInfo(ResponseInfo response) { HomePageInfo homePageInfo = new HomePageInfo(); // TODO Auto-generated method stub JSONObject root = null; try { root = new JSONObject(response.responseString); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONArray categorysJSONArray = root.optJSONArray("categorys"); for (int i = 0; i < categorysJSONArray.length(); i++) { CategoryInfo catInfo = new CategoryInfo(); JSONObject item = (JSONObject) categorysJSONArray.opt(i); catInfo.id = item.optString("id"); catInfo.name = item.optString("name"); catInfo.icon = item.optString("icon"); catInfo.short_desc = item.optString("short_desc"); catInfo.desc = item.optString("desc"); homePageInfo.categorys.add(catInfo); } return homePageInfo; } public static Bitmap getHttpBitmap(String url) { java.net.URL myFileURL; Bitmap bitmap = null; try { myFileURL = new java.net.URL(url); // 获得连接 HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection(); // 设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制 conn.setConnectTimeout(6000); // 连接设置获得数据流 conn.setDoInput(true); // 不使用缓存 conn.setUseCaches(false); // 这句可有可无,没有影响 // conn.connect(); // 得到数据流 InputStream is = conn.getInputStream(); // 解析得到图片 bitmap = BitmapFactory.decodeStream(is); // 关闭数据流 is.close(); } catch (Exception e) { e.printStackTrace(); } return bitmap; } }
MyThread.java
package com.example.juren; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import org.json.JSONObject; import android.os.Handler; import android.os.Message; public class MyThread extends Thread { public Handler mHandler; public String requrl; public static final String STATUS_SUCCESS = "success"; public static final String STATUS_FAILED = "failed"; public MyThread(String url, Handler handler) { this.requrl = url; mHandler = handler; } public void run() { ResponseInfo dat 4000 a = request(requrl); Message msg = new Message(); msg.what = 1; msg.obj = data; mHandler.sendMessage(msg); } private ResponseInfo request(String requrl) { ResponseInfo responseData = new ResponseInfo(); URLConnection conn; URL url = null; HttpURLConnection httpConn = null; int response = -1; try { InputStream is = null; url = new URL(requrl); conn = url.openConnection();// 打开一个链接 conn.setConnectTimeout(10000);// 设置链接超时时间 conn.setReadTimeout(10000);// 设置读取超时时间 httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET");// 使用http的Get方法 httpConn.connect();// 开始连接 response = httpConn.getResponseCode();// 每次连接都会有一个response code if (response == HttpURLConnection.HTTP_OK) { // 通过这次连接获取数据 is = httpConn.getInputStream(); String jsonString = convertStreamToString(is); responseData.responseString = jsonString; JSONObject object = new JSONObject(jsonString);// 如何使用一个字符串创建一个JSONObject对象 responseData.status = object.optString("status");// 根据一个JSONObject对象中的key来找到value if (responseData.status.equals(STATUS_SUCCESS)) { return responseData; } // 连接成功了,但服务器返回了无效的数据 responseData.status = STATUS_FAILED; responseData.exceptionString = "获取数据失败"; return responseData; } else { responseData.status = STATUS_FAILED; responseData.exceptionString = "获取数据失败"; return responseData; } } catch (Exception e) { responseData.status = STATUS_FAILED; responseData.exceptionString = "获取数据失败!"; } finally { if (httpConn != null) { httpConn.disconnect(); } } return responseData; } // 把输入流数据转换成字符串数据 public static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static class ResponseInfo { // 获取是否成功,failed 或 success public String status; // 如果获取成功了返回的数据信息 public String responseString; // 如果失败了连接失败的错误信息 public String exceptionString; } }
HomePageInfo.java
package com.example.juren; import java.util.ArrayList; public class HomePageInfo { public ArrayList<CategoryInfo> categorys = new ArrayList<CategoryInfo>(); public String status; }
CategoryInfo.java
package com.example.juren; /* * *"id": "1", "name": "综合", "icon": "http://114.55.116.95:8080/shusheng/images/zhonghe.png", "short_desc": "十八般武器样样精通", "desc": "NULL" */ public class CategoryInfo { public String id; public String name; public String icon; public String short_desc; public String desc; }
LinearItemView.java 用来定义linearItemView_xml 元素,简化了ui的代码
package com.example.juren; import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.util.Log; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; /* * *子类必须要实现父类的至少一个构造器,系统默认一个无参的构造器 */ public class LinearItemView extends RelativeLayout { public ImageView mImageView; public TextView mTitle_one; public TextView mTitle_two; public TextView mTitle_three; public LinearItemView(Context context, AttributeSet attrs) { super(context, attrs); Log.i("item", "这是第二个构造器"); } @Override protected void onFinishInflate() { super.onFinishInflate(); mImageView = (ImageView) findViewById(R.id.image3); mTitle_one = (TextView) findViewById(R.id.title); mTitle_two = (TextView) findViewById(R.id.subhead); mTitle_three = (TextView) findViewById(R.id.detal); } public void setDatas(String one,String two,String three) { mTitle_one.setText(one); mTitle_two.setText(two); mTitle_three.setText(three); } public void setIcons(Bitmap bmp) { mImageView.setImageBitmap(bmp); } }
GridItemView.java 同上
<pre class="java" name="code">package com.example.juren; import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class GridItemView extends LinearLayout { public ImageView tImage; public TextView tTitle; public GridItemView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } @Override protected void onFinishInflate() { super.onFinishInflate(); tImage = (ImageView) findViewById(R.id.tIcon); tTitle = (TextView) findViewById(R.id.tTitle); } public void setDatas(String one) { tTitle.setText(one); } public void setIcons(Bitmap bmp) { tImage.setImageBitmap(bmp); } }
activity_main.xml 对比后比原来简洁多了,可读性也高了
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#EFEFF4" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:gravity="center" android:paddingBottom="14dp" android:paddingTop="14dp" android:text="@string/hello_world" android:textColor="#666666" android:textSize="17sp" /> <TextView android:layout_width="match_parent" android:layout_height="1dp" /> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:overScrollMode="never" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:paddingBottom="7dp" android:paddingTop="7dp" > <include android:id="@+id/include1" layout="@layout/linear_item" /> <include android:id="@+id/include2" layout="@layout/linear_item" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="11dp" android:layout_marginRight="11dp" android:orientation="horizontal" > <include android:id="@+id/include_1" layout="@layout/grid_item" /> <include android:id="@+id/include_2" layout="@layout/grid_item" /> <include android:id="@+id/include_3" layout="@layout/grid_item" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="11dp" android:layout_marginRight="11dp" android:orientation="horizontal" > <include android:id="@+id/include_4" layout="@layout/grid_item" /> <include android:id="@+id/include_5" layout="@layout/grid_item" /> <include android:id="@+id/include_6" layout="@layout/grid_item" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="11dp" android:layout_marginRight="11dp" android:orientation="horizontal" > <include android:id="@+id/include_7" layout="@layout/grid_item" /> <include android:id="@+id/include_8" layout="@layout/grid_item" /> <include android:id="@+id/include_9" layout="@layout/grid_item" /> </LinearLayout> </LinearLayout> </ScrollView> <TextView android:layout_width="match_parent" android:layout_height="1dp" /> </LinearLayout>
Linear_item.xml 是上面定义的include元素,
在activity_main中使用时要保证属性都一样,不一样的属性放到外层单独定义
注意下面最外层的使用方法:包名 + 类名
<com.example.juren.LinearItemView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="19dp" android:layout_marginRight="19dp" android:layout_marginTop="7dp" android:layout_marginBottom="7dp" android:background="@drawable/background" > <ImageView android:id="@+id/image3" android:layout_width="58dp" android:layout_height="58dp" android:layout_alignParentLeft="true" android:layout_margin="19dp" android:src="@drawable/xxhl" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toLeftOf="@+id/image4" android:layout_toRightOf="@id/image3" android:orientation="vertical" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" android:text="@string/hello" android:textColor="#222222" android:textSize="16sp" /> <TextView android:id="@+id/subhead" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="left" android:singleLine="true" android:text="@string/hello1" android:textColor="#cccccc" android:textSize="12sp" /> <TextView android:id="@+id/detal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" android:text="@string/hello2" android:textColor="#cccccc" android:textSize="12sp" /> </LinearLayout> <ImageView android:id="@+id/image4" android:layout_width="21dp" android:layout_height="21dp" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginLeft="19dp" android:layout_marginRight="19dp" android:src="@drawable/xxhr" /> </com.example.juren.LinearItemView>
grid_item.xml 同上
<com.example.juren.GridItemView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="7dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="7dp"
android:background="@drawable/background"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="@+id/tIcon"
android:layout_width="58dp"
android:layout_height="58dp"
android:layout_marginLeft="19dp"
android:layout_marginRight="19dp"
android:layout_marginTop="19dp"
android:src="@drawable/xxhl" />
<TextView
android:id="@+id/tTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="19dp"
android:layout_marginTop="14dp"
android:text="@string/hello6"
android:textColor="#333333"
android:textSize="14dp" >
</TextView>
</com.example.juren.GridItemView>
改良后的代码如上,还需要完善继续改进...
相关文章推荐
- 16-07-29 android 方法 如何引用链接获取json数据
- Android 获取通讯录所有的联系人的方法 json打印的就是这些数据
- Android网络开发中如何使用JSON进行网络通信---Android_JSON数据通讯方法解析
- 【Android应用开发】-(17)获取Google天气预报通过Xml和JSON解析数据
- 如何将JSON数据通过Get方法获取数据
- Android上访问Java做的WebService获取JSON数据的方法及org.xmlpull.v1.XmlPullParserException异常处理
- Android网络开发中如何使用JSON进行网络通信---Android JSON数据通讯方法解析
- Android通过Get方法获取Json数据
- 免费PM2.5数据如何获取之PM25.in网站API调用JSON数据处理方法
- Android网络开发中如何使用JSON进行网络通信---Android JSON数据通讯方法解析
- (六)Net Core项目使用Controller之一 c# log4net 不输出日志 .NET Standard库引用导致的FileNotFoundException探究 获取json串里的某个属性值 common.js 如何调用common.js js 筛选数据 Join 具体用法
- Android编程实现根据经纬度查询地址并对获取的json数据进行解析的方法
- 获取服务端页面JSON数据的JQUERY ajax方法定义
- Android 获取Google Weather API 并通过Xml和JSON解析数据
- JQuery以POST方法从ASP.NET服务器获取Json数据完整示例
- jqGrid获取json数据方法
- *关于如何获取指定表的指定字段的数据类型的方法
- 【Android】JSON数据的读写方法
- JQuery以POST方法从ASP.NET服务器获取Json数据完整示例
- 如何构建JSON数据,JSON数据的格式,JSON数据的获取