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

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

相关文章

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

关于数据埋点,你需要了解这些基本知识

产品汪每天都在和数据打交道,你知道数据来自哪里吗? 移动app端内的用户行为数据大多来自埋点,了解一些埋点知识,能和数据分析师、技术侃大山,参与到前期的数据采集,更重要是让最终的埋点数据能为我所用,否则可怜巴巴等上几个月是常有的事。   埋点类型 根据埋点方式,可以区分为: 手动埋点半自动埋点全自动埋点 秉承“任何事物都有两面性”的道理:自动程度高的,能解决通用统计,便于统一化管理,但个性化定

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

异构存储(冷热数据分离)

异构存储主要解决不同的数据,存储在不同类型的硬盘中,达到最佳性能的问题。 异构存储Shell操作 (1)查看当前有哪些存储策略可以用 [lytfly@hadoop102 hadoop-3.1.4]$ hdfs storagepolicies -listPolicies (2)为指定路径(数据存储目录)设置指定的存储策略 hdfs storagepolicies -setStoragePo

Hadoop集群数据均衡之磁盘间数据均衡

生产环境,由于硬盘空间不足,往往需要增加一块硬盘。刚加载的硬盘没有数据时,可以执行磁盘数据均衡命令。(Hadoop3.x新特性) plan后面带的节点的名字必须是已经存在的,并且是需要均衡的节点。 如果节点不存在,会报如下错误: 如果节点只有一个硬盘的话,不会创建均衡计划: (1)生成均衡计划 hdfs diskbalancer -plan hadoop102 (2)执行均衡计划 hd

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

高效录音转文字:2024年四大工具精选!

在快节奏的工作生活中,能够快速将录音转换成文字是一项非常实用的能力。特别是在需要记录会议纪要、讲座内容或者是采访素材的时候,一款优秀的在线录音转文字工具能派上大用场。以下推荐几个好用的录音转文字工具! 365在线转文字 直达链接:https://www.pdf365.cn/ 365在线转文字是一款提供在线录音转文字服务的工具,它以其高效、便捷的特点受到用户的青睐。用户无需下载安装任何软件,只

烟火目标检测数据集 7800张 烟火检测 带标注 voc yolo

一个包含7800张带标注图像的数据集,专门用于烟火目标检测,是一个非常有价值的资源,尤其对于那些致力于公共安全、事件管理和烟花表演监控等领域的人士而言。下面是对此数据集的一个详细介绍: 数据集名称:烟火目标检测数据集 数据集规模: 图片数量:7800张类别:主要包含烟火类目标,可能还包括其他相关类别,如烟火发射装置、背景等。格式:图像文件通常为JPEG或PNG格式;标注文件可能为X