最终目的
以JSON的形式,将数据存入服务器端。
在Android中,以Handler加载显示大批量文字。
在此以加载金庸小说《天龙八部(新修版)》为例(2580480 字节)。
以tomcat为服务器,在jsp中以I/O读取本机上的txt文件,写入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布局文件
activity_hander_text.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; } }
服务器端
在tomcat的webapps文件夹下新建android文件夹,在其中新建一个index.jsp,用来存放服务器端的JSON数据。
index.jsp:
<%@ 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(" "); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } out.print("{"book":"" + buffer.toString() + ""}"); %>
完成后,打开tomcat服务器,在浏览器中输入路径,尝试访问该JSP文件。
如能访问则说明服务器端没问题。
加入权限
由于要访问服务器网络,所以,必须在AndroidManifest.xml中加入网络访问权限:
<uses-permission android:name="android.permission.INTERNET"/>