【Android】Handler的应用(一):从服务器端加载JSON数据
最终目的
Activity文件
package com.app.test02; import java.util.Map; import com.app.util.MyApplication; import android.app.Activity;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView; public class HanderTest_Text extends Activity {
private Button button;
private TextView textView;
private Handler handler;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hander_text); button = (Button) findViewById(R.id.button1);
textView = (TextView) findViewById(R.id.textView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1); button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressBar.setVisibility(View.VISIBLE);
button.setText("加载中...");
new MyThread().start();
}
}); handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
textView.setText(msg.obj.toString());
progressBar.setVisibility(View.GONE);
button.setText("加载完成");
button.setEnabled(false);
}
};
} class MyThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
String result = ApplicationDemo.handleGet("http://10.0.2.2:8888/android/");
Map map = ApplicationDemo.getMap(result); Message message = handler.obtainMessage();
message.obj = map.get("book");
try {
sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(message);
}
}
}
XML布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fff" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"> <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加载文本" /> </LinearLayout> <ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000"/> </LinearLayout>
</ScrollView> <ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" /> </LinearLayout>
ApplicationDemo
package com.app.util; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject; import android.app.Application; public class ApplicationDemo extends Application {
/** 发送GET请求并获取服务器端返回值 */
public static String handleGet(String strUrl) {
String result = null;
HttpGet request = new HttpGet(strUrl);//实例化get请求
DefaultHttpClient client = new DefaultHttpClient();//实例化客户端
try {
HttpResponse response = client.execute(request);//执行该请求,得到服务器端的响应内容
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());//把响应结果转成String
} else {
result = response.getStatusLine().toString();
}
} catch (Exception e) {
return e.getMessage();
}
return result;
}
/** 将JSON字符串转换为Map */
public static Map<String, Object> getMap(String jsonString) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(jsonString);
@SuppressWarnings("unchecked")
Iterator<String> keyIter = jsonObject.keys();
String key;
Object value;
Map<String, Object> valueMap = new HashMap<String, Object>();
while (keyIter.hasNext()) {
key = keyIter.next();
value = jsonObject.get(key);
valueMap.put(key, value);
}
return valueMap;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
服务器端
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" import="java.io.*"%>
<%
response.setContentType("text/html;charset=utf-8");
%>
<% BufferedReader bReader = null;
String line = null;
StringBuffer buffer = new StringBuffer();
try {
// bReader =new BufferedReader(new FileReader(new File("D:\\Program File\\apache-tomcat-7.0.20\\webapps\\android\\index.jsp")));
bReader =new BufferedReader(new FileReader(new File("E:\\文字\\金庸\\TXT\\新修版\\天龙八部(新修版).txt")));
while ((line = bReader.readLine())!=null) {
buffer.append(line).append("\n");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
out.print("{\"book\":\"" + buffer.toString() + "\"}"); %>
完成后,打开tomcat服务器,在浏览器中输入路径,尝试访问该JSP文件。
加入权限
<uses-permission android:name="android.permission.INTERNET"/>
最终效果
加载前
加载过程中
加载完成后
【Android】Handler的应用(一):从服务器端加载JSON数据的更多相关文章
- hive加载json数据解决方案
hive官方并不支持json格式的数据加载,默认支持csv格式文件加载,如何在不依赖外部jar包的情况下实现json数据格式解析,本编博客着重介绍此问题解决方案 首先创建元数据表: create EX ...
- dojo 加载Json数据
1.今天研究了dojo datagrid加载WebService后台传上来的数据.研究来研究去发现他不是很难.用谷歌多调试一下就好了. 2.看很多例子,这个例子能够更好的帮我解决问题:https:// ...
- 扩展JQUERY 表单加载JSON数据
$.fn.extend({ //表单加载json对象数据 setForm : function (jsonValue) { var obj = this; $.each(jsonValue, func ...
- BootStrap的表格加载json数据,并且可以搜索,选择
2018.4.11日更新,8号的时候我推荐去官网下载,但是那个版本不知道为什么我无法使用 $table.bootstrapTable('getSelections'); 无论如何...然后我尝试着更换 ...
- PHP+MySQL+Easyui tree菜单从后台加载json数据(一)
实现功能:从数据库加载出所有的数据库名,相应的数据库加载对应的数据库表名 原理:(首先看一下参考手册的内容) 异步加载Tree tree 支持内置的异步加载模式,用户创建一个空的tree,然后定义一个 ...
- JQuery和原生JS跨域加载JSON数据或HTML。
前提:有时候需要在网页上,加载另一个网站上的数据.或者加载另一个网站上的一个页面.Js的Ajax请求不具备跨域功能,可以使用JQuery来实现. 网页端JS代码: $(function () { $. ...
- vue通过ajax加载json数据
HTML <ul id="Hanapp"> <li class="styVue" v-for="item in actList&qu ...
- EasyUI datagrid动态加载json数据
最近做一个项目,要求是两张张表可能查找出10多种不同的结果集. 如果想只用一个表格就把全部的结果不同的显示出来那么就肯定不同使用固定的字段名字,要通过动态加载后台返回来的数据把它显示出来就必须动态加载 ...
- MVC4中EasyUI Tree异步加载JSON数据生成树
1,首先构造tree接受的格式化数据结构MODEL /// <summary> /// 定义EasyUI树的相关数据,方便控制器生成Json数据进行传递 /// </summar ...
随机推荐
- Repeater获取某一行TextBox值
TextBox tb = (TextBox)e.Item.FindControl("TextBoxID");
- 后台生成textbox并设置多行属性,自动换行
Table tb = new Table(); TableRow row1 = new TableRow(); TableCell tc1 = new TableCell(); TableCell t ...
- 通过url给action传中文参数乱码解决方案
比如: http://localhost:8080/projectName/dutyCondition.action?admitstate=0¤tStep=我的博客 传到后台的时候 ...
- [转]Java虚拟机类加载机制浅谈
Java语言是一种编译后再经过解释器执行的过程, 解释器主要就是如何处理解释Class文件的二进制字节流.JVM主要包含三大核心部分:运行时数据区,类加载器和执行引擎. 虚拟机将描述类的数据从Clas ...
- 关于debug和release 以及new 和delete
题目:给出一组字符串 输入:"ate","eat","Eat","new","ENW",“wha” ...
- 简单的BFS学习笔记
什么是BFS传送门. 今天学习BFS,加油! 先定义个数组: struct Node{ int a=0; int b=0; int step=0; }; int map[5][4]={//地图 0,0 ...
- C++ 虚函数机制学习
致谢 本文是基于对<Inside the c++ object model>的阅读和gdb的使用而完成的.在此感谢Lippman对cfront中对象模型的解析,这些解析帮助读者拨开迷雾.此 ...
- eclipse序列化生成serialVersionUID
serialVersionUID作用: 序列化时为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性. 如果你修改代码重新部署后出现序列化错误,可以考虑给相应的类增加serialVersio ...
- Ubuntu各种软件的安装
普通的例如g++.deadbeef等源中有的软件,可以用apt-get安装 sudo apt-get install XXX 还有很多直接在software center搜索下载 对于下载来源代码需要 ...
- ASP.NET MVC3使用Unity2.0实现依赖注入(转载和扩展)
http://note.youdao.com/share/?id=53252d0f897e0e109aadd296a1682354&type=note