图文混排,从服务端取得数据先加载文字后加载图片

来源:互联网 发布:国内云计算市场规模 编辑:程序博客网 时间:2024/05/06 02:37

只记录了android端的,数据库就是一张产品表,记录产品信息。服务端从数据库把数据取出来封装成json,然后客户端发送请求时返回产品数据!

目录结构:Product.java  记录产品的javabean

package com.example.domain;public class Product {private int id;private String name;private String address;private double price;private String img;/** * @return the id */public int getId() {return id;}/** * @param id *            the id to set */public void setId(int id) {this.id = id;}/** * @return the name */public String getName() {return name;}/** * @param name *            the name to set */public void setName(String name) {this.name = name;}/** * @return the address */public String getAddress() {return address;}/** * @param address *            the address to set */public void setAddress(String address) {this.address = address;}/** * @return the price */public double getPrice() {return price;}/** * @param price *            the price to set */public void setPrice(double price) {this.price = price;}/** * @return the img */public String getImg() {return img;}/** * @param img *            the img to set */public void setImg(String img) {this.img = img;}}

HttpUtils.java

package com.example.http;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.util.Log;public class HttpUtils {public HttpUtils() {// TODO Auto-generated constructor stub}public static InputStream getInputStreamFromPath(String path)throws IOException {InputStream inputStream = null;Log.i("Main", "1");String string = null;try {HttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(path);HttpResponse httpResponse = httpClient.execute(httpGet);int httpResponseCode = httpResponse.getStatusLine().getStatusCode();if (httpResponseCode == 200) {inputStream = httpResponse.getEntity().getContent();}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}/* * HttpURLConnection httpURLConnection = null; try { URL url=new * URL(path); httpURLConnection = (HttpURLConnection) * url.openConnection(); } catch (IOException e) { // TODO * Auto-generated catch block e.printStackTrace(); } * httpURLConnection.setDoInput(true); try { * httpURLConnection.setRequestMethod("GET"); * httpURLConnection.setConnectTimeout(3000); int * code=httpURLConnection.getResponseCode(); if(code==200){ * inputStream=httpURLConnection.getInputStream(); } } catch * (ProtocolException e) { // TODO Auto-generated catch block * e.printStackTrace(); } */return inputStream;}public static String changeInputStreamToString(InputStream inputStream) {ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;try {while ((len = inputStream.read(data)) != -1) {byteArrayOutputStream.write(data, 0, len);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}String string = new String(byteArrayOutputStream.toByteArray());Log.i("Main", "changeInputStreamToString++" + string);return string;}}
JsonUtils.java

package com.example.parsejson;import java.util.ArrayList;import java.util.List;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.util.Log;import com.example.domain.Product;public class JsonUtils {static List<Product> list = null;public JsonUtils() {// TODO Auto-generated constructor stub}public static List<Product> parseJsonToProduct(String string) {Log.i("Main", string);list = new ArrayList<Product>();try {JSONObject jsonObject = new JSONObject(string);JSONArray jsonArray = jsonObject.getJSONArray("persons");int lenth = jsonArray.length();for (int i = 0; i < lenth; i++) {JSONObject jsonObject2 = jsonArray.getJSONObject(i);Product product = new Product();product.setId(jsonObject2.getInt("id"));product.setAddress(jsonObject2.getString("address"));product.setImg(jsonObject2.getString("img"));product.setName(jsonObject2.getString("name"));product.setPrice(jsonObject2.getDouble("price"));list.add(product);}} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}return list;}}

MainActivity.java

package com.example.android_picandtext;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.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import org.json.JSONArray;import org.json.JSONObject;import com.example.android_picandtext.DownLoadImage.ImageCallBack;import android.app.Activity;import android.app.ProgressDialog;import android.content.Context;import android.graphics.drawable.Drawable;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;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 Activity {private ListView listView;private ProgressDialog dialog;private MyAdapter adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) findViewById(R.id.listView1);dialog = new ProgressDialog(this);dialog.setTitle("提示");dialog.setMessage("下载数据中。。。。");adapter = new MyAdapter(this);new MyTask().execute(CommonUrl.url);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}public class MyAdapter extends BaseAdapter {private List<Map<String, Object>> list = null;private Context context;private LayoutInflater layoutInflater;public MyAdapter(Context context) {this.context = context;layoutInflater = LayoutInflater.from(context);}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}public void setData(List<Map<String, Object>> list) {this.list = list;}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn list.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup viewGroup) {// TODO Auto-generated method stubView view = null;if (convertView == null) {view = layoutInflater.inflate(R.layout.item, null);} else {view = convertView;}TextView name = (TextView) view.findViewById(R.id.textView1);TextView address = (TextView) view.findViewById(R.id.textView2);TextView price = (TextView) view.findViewById(R.id.textView3);address.setText(list.get(position).get("name").toString());name.setText(list.get(position).get("address").toString());price.setText(list.get(position).get("price").toString());final ImageView imageView = (ImageView)view.findViewById(R.id.imageView1);Log.i("Main", list.get(position).get("img").toString());String imagePath = CommonUrl.img_url+ list.get(position).get("img").toString();Log.i("Main", "imagePath+" + imagePath);DownLoadImage downLoadImage = new DownLoadImage(imagePath);downLoadImage.loadImage(new ImageCallBack() { @Overridepublic void getDrawable(Drawable draw) { Log.i("Main", "这里是loadImage" );imageView.setImageDrawable(draw);}});return view;}}public class MyTask extendsAsyncTask<String, Void, List<Map<String, Object>>> {@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();dialog.show();}@Overrideprotected void onPostExecute(List<Map<String, Object>> result) {// TODO Auto-generated method stubsuper.onPostExecute(result);adapter.setData(result);listView.setAdapter(adapter);adapter.notifyDataSetChanged();dialog.dismiss();}@Overrideprotected void onProgressUpdate(Void... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);}@Overrideprotected List<Map<String, Object>> doInBackground(String... params) {// TODO Auto-generated method stubList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();try {HttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(params[0]);HttpResponse httpResponse = httpClient.execute(httpPost);int code = httpResponse.getStatusLine().getStatusCode();if (code == 200) {String jsonString = EntityUtils.toString(httpResponse.getEntity());JSONObject jsonObject = new JSONObject(jsonString);JSONArray jsonArray = jsonObject.getJSONArray("persons");for (int i = 0; i < jsonArray.length(); i++) {JSONObject jsonObject2 = jsonArray.getJSONObject(i);Map<String, Object> map = new HashMap<String, Object>();Iterator<String> iterator = jsonObject2.keys();while (iterator.hasNext()) {String key = iterator.next();Object value = jsonObject2.get(key);map.put(key, value);}list.add(map);}}} catch (Exception e) {// TODO: handle exception}return list;}}}

CommonUrl.java

package com.example.android_picandtext;public class CommonUrl {public CommonUrl() {// TODO Auto-generated constructor stub}public static String url = "http://192.168.0.9:8080/xianfengProject/servlet/JsonAction?action_flag=persons";public static String img_url = "http://192.168.0.9:8080/xianfengProject/upload/";}


DownLoadImage.java

package com.example.android_picandtext;import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;import android.graphics.drawable.Drawable;import android.os.Handler;import android.os.Message;import android.util.Log;public class DownLoadImage {private String image_path;public DownLoadImage(String image_path) {// 保存图片的下载地址this.image_path = image_path;}public void loadImage(final ImageCallBack callback) {final Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);// 接受到消息后,调用接口回调的方法Log.i("Main", "handleMessage1" );callback.getDrawable((Drawable) msg.obj);Log.i("Main", "handleMessage2" );}};// 开启一个新线程用于访问图片数据new Thread(new Runnable() {@Overridepublic void run() {try {// 下载图片为Drawable对象Drawable drawable = Drawable.createFromStream(new URL(image_path).openStream(), "");// 把图片对象包装成一个消息发送给HandlerMessage message = Message.obtain();Log.i("Main", "这里是new Thread" );message.obj = drawable;handler.sendMessage(message);} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}).start();}// 定义一个公开的接口,用于执行回调操作public interface ImageCallBack {public void getDrawable(Drawable draw);}}


0 0
原创粉丝点击