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

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

相关文章

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Python中图片与PDF识别文本(OCR)的全面指南

《Python中图片与PDF识别文本(OCR)的全面指南》在数据爆炸时代,80%的企业数据以非结构化形式存在,其中PDF和图像是最主要的载体,本文将深入探索Python中OCR技术如何将这些数字纸张转... 目录一、OCR技术核心原理二、python图像识别四大工具库1. Pytesseract - 经典O

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

使用SpringBoot整合Sharding Sphere实现数据脱敏的示例

《使用SpringBoot整合ShardingSphere实现数据脱敏的示例》ApacheShardingSphere数据脱敏模块,通过SQL拦截与改写实现敏感信息加密存储,解决手动处理繁琐及系统改... 目录痛点一:痛点二:脱敏配置Quick Start——Spring 显示配置:1.引入依赖2.创建脱敏

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

springboot加载不到nacos配置中心的配置问题处理

《springboot加载不到nacos配置中心的配置问题处理》:本文主要介绍springboot加载不到nacos配置中心的配置问题处理,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录springboot加载不到nacos配置中心的配置两种可能Spring Boot 版本Nacos