转载请注明出处:http://blog.csdn.net/joker_ya/article/details/40678429
OK!昨晚研究了一晚上了如何从后台传送数据到Android虚拟机的实现。皇天不负苦心人,终于在二十三点半时成功运行起来了。所以今天就迫不及待的想和大家分享一下。
首先说说本次实验所需要的一些jar包和工具:
1.gson.jar包--附上下载地址:http://download.csdn.net/detail/joker_ya/8107767
2.volley.jat包--附上下载地址:http://download.csdn.net/detail/joker_ya/8107771
3.MyEclipse8.5(作为后台)和Eclipse(做Android应用)
工具和jar包准备好后,接下来就是写后台了。我们打开MyEclipse并创建名为HouTai的Web Project项目。
(1)在项目的WebRoot-->WEB-INF-->lib目录下导入我们的gson.jar包;
(2)在WebRoot目录新建名为img的文件夹,并放入一些图片资源。
目录如下:
首先我们在com.joker.domain包下新建Girl类,表示一个对象,用于转换为json格式的数据:
- package com.joker.domain;
-
-
-
-
- public class Girl {
- private int id;
- private String name;
- private String image;
-
-
-
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getImage() {
- return image;
- }
-
- public void setImage(String image) {
- this.image = image;
- }
-
- @Override
- public String toString() {
- return "People [id=" + id + ", image=" + image + ", name=" + name + "]";
- }
-
- }
接下来在com.joker.servlet包下新建GetDataServlet的serlet,实现数据的转换:
- package com.joker.servlet;
-
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.google.gson.Gson;
- import com.joker.domain.Girl;
-
-
-
-
- public class GetDataServlet extends HttpServlet {
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- Gson gson = new Gson();
-
-
-
- List<Girl> girls = new ArrayList<Girl>();
- for (int i = 1; i <= 6; i++) {
- Girl girl = new Girl();
- girl.setId(i);
- girl.setName("girl" + i);
-
-
-
-
-
- girl.setImage(request.getContextPath() + "/img/girl" + i + ".jpg");
- girls.add(girl);
- }
-
- String str = gson.toJson(girls);
-
- request.setAttribute("data", "{\"data\":" + str + "}");
-
- request.getRequestDispatcher("/index.jsp").forward(request, response);
- }
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- }
-
- }
最后是index.jsp,该页面很简单,直接用el表达式输出request域中的数据:
- <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
-
- ${data}
好了,后台基本上就完成了。我们发布一下该工程,用浏览器访http://localhost:8080/HouTai/servlet/GetDataServlet看看效果吧:
然后我们再来看看该页面的源代码:
从上图中我们可以看到--第一行是空行,因此在编写Android应用中不要忘了对此做一些处理(去掉空格)。我们确实是把Girl对象转换为json格式并输出成功了。完美!
以上,后台我们基本上完成了。接下来就是写一个Android应用来测试一下后台传入的数据了。
打开Eclipse新建名为GetHouTaiDataDemo的Android应用,并在libs目录下导入volley.jat包。目录如下:
主界面就一个ListView,用于显示从后台传入的图片和数据。在此就不贴出来了。
主要的是MainActivity.Java:
- package com.example.gethoutaidatademo;
-
- import java.net.URI;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- import org.json.JSONArray;
- import org.json.JSONObject;
-
- import com.android.volley.RequestQueue;
- import com.android.volley.Response.ErrorListener;
- import com.android.volley.Response.Listener;
- import com.android.volley.VolleyError;
- import com.android.volley.toolbox.ImageRequest;
- import com.android.volley.toolbox.Volley;
-
- import android.support.v7.app.ActionBarActivity;
- import android.graphics.Bitmap;
- import android.graphics.Bitmap.Config;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.BaseAdapter;
- import android.widget.ImageView;
- import android.widget.ListView;
- import android.widget.TextView;
-
-
-
-
-
- public class MainActivity extends ActionBarActivity {
-
-
-
- private static final String BASEPATH = "http://222.17.106.37:8080";
- private static final String PATH = "http://222.17.106.37:8080/HouTai/servlet/GetDataServlet";
-
- private ListView mListView;
- private List<Map<String, String>> list = new ArrayList<Map<String, String>>();
- private Map<String, String> map;
- private RequestQueue queue;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- mListView = (ListView) findViewById(R.id.listview);
-
- queue = Volley.newRequestQueue(this);
- myAsyncTask task = new myAsyncTask();
- task.execute();
- MyAdapter adapter = new MyAdapter();
- mListView.setAdapter(adapter);
- }
-
-
-
-
- public class MyAdapter extends BaseAdapter {
-
- @Override
- public int getCount() {
-
- return list.size();
- }
-
- @Override
- public Object getItem(int position) {
-
- return list.get(position);
- }
-
- @Override
- public long getItemId(int position) {
-
- return position;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup arg2) {
-
- final Viewholder holder;
- if (convertView == null) {
- convertView = LayoutInflater.from(MainActivity.this).inflate(
- R.layout.items, null);
-
- holder = new Viewholder();
- holder.mImageView = (ImageView) convertView
- .findViewById(R.id.imageview);
- holder.mTextView = (TextView) convertView
- .findViewById(R.id.textview);
- convertView.setTag(holder);
- } else {
- holder = (Viewholder) convertView.getTag();
- }
-
- ImageRequest request = new ImageRequest(BASEPATH
- + list.get(position).get("image"), new Listener<Bitmap>() {
-
- @Override
- public void onResponse(Bitmap response) {
-
- holder.mImageView.setImageBitmap(response);
- }
- }, 0, 0, Config.ARGB_8888, new ErrorListener() {
-
- @Override
- public void onErrorResponse(VolleyError error) {
-
-
- }
- });
- queue.add(request);
- holder.mTextView.setText(list.get(position).get("name"));
- return convertView;
- }
-
- public class Viewholder {
- ImageView mImageView;
- TextView mTextView;
- }
- }
-
-
-
-
- public class myAsyncTask extends AsyncTask<Void, Void, String> {
-
-
-
- @Override
- protected String doInBackground(Void... arg0) {
-
- String result = "";
- try {
- HttpGet get = new HttpGet(new URI(PATH));
- HttpClient client = new DefaultHttpClient();
- HttpResponse response = client.execute(get);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- result = EntityUtils.toString(response.getEntity());
-
- result = result.trim();
- Log.v("++++++++++++", result);
- }
- } catch (Exception e) {
-
- e.printStackTrace();
- }
- return result;
- }
-
-
-
-
- @Override
- protected void onPostExecute(String result) {
-
- String name = "";
- try {
- JSONArray array = new JSONObject(result).getJSONArray("data");
- for (int i = 0; i < array.length(); i++) {
- JSONObject object = array.getJSONObject(i);
- Iterator<?> iterator = object.keys();
- map = new HashMap<String, String>();
- while (iterator.hasNext()) {
- name = iterator.next().toString();
- map.put(name, object.getString(name));
- }
- list.add(map);
- }
- } catch (Exception e) {
-
- e.printStackTrace();
- }
- super.onPostExecute(result);
- }
- }
- }
本来是用HttpClient来访问路径的,写到一半时突然发现要访问图片,这就有点麻烦了。自己又懒得去改,因此导入了volley.jar包来获得图片。其实访问后台数据也可以用volley.jar包中的jsonRequest来获得json数据的,无奈自己太懒,就用
HttpClient和volley结合来用了。有点不伦不类了。
items.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="horizontal" >
- <ImageView
- android:id="@+id/imageview"
- android:layout_width="50dip"
- android:layout_height="50dip"
- />
- <TextView
- android:id="@+id/textview"
- android:layout_width="0dip"
- android:layout_weight="1"
- android:layout_height="50dip"
- />
-
- </LinearLayout>
好了,Android端的应用我们也写好了。接下来就是测试看看效果了:
从图中可以看出我们确实是从后台中获得了资源并成功的显示了出来。到此,使用JavaWeb项目作为后台的实现大功告成。
最后的最后还是附上源码下载地址(包含HouTai的Web Project后台应用和GetHouTaiDataDemo的Android应用):
源码下载
所有评论(0)