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

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

相关文章

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

详解C#如何提取PDF文档中的图片

《详解C#如何提取PDF文档中的图片》提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使用,下面我们就来看看如何使用C#通过代码从PDF文档中提取图片吧... 当 PDF 文件中包含有价值的图片,如艺术画作、设计素材、报告图表等,提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("