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

2024-04-03 22:32

本文主要是介绍图文混排,从服务端取得数据先加载文字后加载图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

只记录了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);}
}


这篇关于图文混排,从服务端取得数据先加载文字后加载图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/874149

相关文章

关于Spring @Bean 相同加载顺序不同结果不同的问题记录

《关于Spring@Bean相同加载顺序不同结果不同的问题记录》本文主要探讨了在Spring5.1.3.RELEASE版本下,当有两个全注解类定义相同类型的Bean时,由于加载顺序不同,最终生成的... 目录问题说明测试输出1测试输出2@Bean注解的BeanDefiChina编程nition加入时机总结问题说明

Python利用PIL进行图片压缩

《Python利用PIL进行图片压缩》有时在发送一些文件如PPT、Word时,由于文件中的图片太大,导致文件也太大,无法发送,所以本文为大家介绍了Python中图片压缩的方法,需要的可以参考下... 有时在发送一些文件如PPT、Word时,由于文件中的图片太大,导致文件也太大,无法发送,所有可以对文件中的图

Redis的数据过期策略和数据淘汰策略

《Redis的数据过期策略和数据淘汰策略》本文主要介绍了Redis的数据过期策略和数据淘汰策略,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录一、数据过期策略1、惰性删除2、定期删除二、数据淘汰策略1、数据淘汰策略概念2、8种数据淘汰策略

轻松上手MYSQL之JSON函数实现高效数据查询与操作

《轻松上手MYSQL之JSON函数实现高效数据查询与操作》:本文主要介绍轻松上手MYSQL之JSON函数实现高效数据查询与操作的相关资料,MySQL提供了多个JSON函数,用于处理和查询JSON数... 目录一、jsON_EXTRACT 提取指定数据二、JSON_UNQUOTE 取消双引号三、JSON_KE

java获取图片的大小、宽度、高度方式

《java获取图片的大小、宽度、高度方式》文章介绍了如何将File对象转换为MultipartFile对象的过程,并分享了个人经验,希望能为读者提供参考... 目China编程录Java获取图片的大小、宽度、高度File对象(该对象里面是图片)MultipartFile对象(该对象里面是图片)总结java获取图片

Python给Excel写入数据的四种方法小结

《Python给Excel写入数据的四种方法小结》本文主要介绍了Python给Excel写入数据的四种方法小结,包含openpyxl库、xlsxwriter库、pandas库和win32com库,具有... 目录1. 使用 openpyxl 库2. 使用 xlsxwriter 库3. 使用 pandas 库

Java实战之自助进行多张图片合成拼接

《Java实战之自助进行多张图片合成拼接》在当今数字化时代,图像处理技术在各个领域都发挥着至关重要的作用,本文为大家详细介绍了如何使用Java实现多张图片合成拼接,需要的可以了解下... 目录前言一、图片合成需求描述二、图片合成设计与实现1、编程语言2、基础数据准备3、图片合成流程4、图片合成实现三、总结前

SpringBoot定制JSON响应数据的实现

《SpringBoot定制JSON响应数据的实现》本文主要介绍了SpringBoot定制JSON响应数据的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们... 目录前言一、如何使用@jsonView这个注解?二、应用场景三、实战案例注解方式编程方式总结 前言

使用Python在Excel中创建和取消数据分组

《使用Python在Excel中创建和取消数据分组》Excel中的分组是一种通过添加层级结构将相邻行或列组织在一起的功能,当分组完成后,用户可以通过折叠或展开数据组来简化数据视图,这篇博客将介绍如何使... 目录引言使用工具python在Excel中创建行和列分组Python在Excel中创建嵌套分组Pyt

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑