【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 ...
随机推荐
- apache pk nginx pk Lighttpd
apache: 历史: APACHE:于1994年发布,是apache软件基金会的一个开放源码的网页服务器,可以在多平台下运行,由于其多平台和安全性被广泛使用,是最流行的web服务器端软件之一:特点是 ...
- uri 和 url 的区别
uri 统一资源标识符,值是唯一标识资源的任意字符,比如guid url 统一资源定位符,值是标识资源的字符串,但是包含定位信息,比如http://localhost/index.html
- org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session
出错原因很简单:数据库服务没开,自然就打不开Session了.
- Java 中 静态方法与非静态方法的区别
静态方法和实例方法的区别主要体现在两个方面: 在外部调用静态方法时,可以使用"类名.方法名"的方式,也可以使用"对象名.方法名"的方式.而实例方法只有后面这种方 ...
- [整理]DLL延时加载 && 设置进程私有环境变量
DLL延时加载鉴于静态和动态加载之间,即无需在代码中显示加载但它内队依然是动态加载的方式只是系统帮处理了.这样做好处是: 1. 可以加快启动时间(因为它是动态加载在需要的时间加载), 2. 减小编写L ...
- cookie记录用户的浏览商品的路径
在电子商务的网站中,经常要记录用户的浏览路径,以判断用户到底对哪些商品感兴趣,或者哪些商品之间存在关联. 下面将使用cookie记录用户的浏览过的历史页面.该网站将每个页面的标题保存在该页面的$TIT ...
- jenkins 配置安全邮件
Jenkins网页设置界面只支持SSL协议 ,对于STARTTLS协议,需要修改jenkins的配置文件去支持基于TLS的SMTP认证 1.修改jenkins配置文件 打开jenkins配置文件/et ...
- Linux中的网络
在windows 中表示一张网卡用本地连接1,本地连接2这种方式来表示:而在linux 中用的是etho,eth1 等等这样的东西来表示的.
- 如何彻底卸载sql server 2012
好不容易装上了sql server 2012数据库,可是却不能连接本地的数据库,后来发现缺少一些服务,于是决定重新安装,但是卸载却很麻烦,如果卸载不干净的话,重新安装会出问题,所以下面就总结一些方法: ...
- Telnet RFC
http://tools.ietf.org/html/rfc857 http://www.faqs.org/rfcs/rfc854.html 不错: http://blog.csdn.net/chao ...