查了很多文档终于搞明白了,SimpleAdapter中的from参数是hashmap,但value不一定非要是int 型的id才行,是bitmap也行,只不过后面再处理一下即可,移动端::手机和电脑连接同一个wifi
package com.example.listview_8; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.SimpleAdapter.ViewBinder; import android.widget.Toast; public class MainActivity extends Activity { private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时10秒钟 private static final int SO_TIMEOUT = 10 * 60 * 1000; // 设置请求超时时间10秒钟 private static final int LOGIN_OK = 1; private Handler handler ; private ListView lv1; private int COUNT=5;//////COUNT=10时图片显示会乱序,有待改进 private Bitmap[] imagesId=new Bitmap[COUNT]; // private String[] names={"短毛猫"}; // private String[] mark={"可爱"}; // private String[] names={"短毛猫1","猴子2","兔子3","老鼠4","斑马5","短毛猫6","猴子7","兔子8","老鼠9","斑马10"}; // private String[] mark={"可爱1","顽皮2","温顺3","伶俐4","强壮5","可爱6","顽皮7","温顺8","伶俐9","强壮10"}; private String[] names={"短毛猫1","猴子1","兔子1","老鼠1","斑马1"}; private String[] mark={"可爱1","顽皮1","温顺1","伶俐1","强壮1"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv1 = (ListView) findViewById(R.id.listView1); final List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>(); for(int i=1;i<=COUNT;i++){ fun_HttpPost(i); } handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO 自动生成的方法存根 ///super.handleMessage(msg); if((Bitmap)msg.obj!=null){ Log.i("==========================Bitmap)msg.obj==null===================", "Bitmap)msg.obj==null"); } int num=msg.what-1; imagesId[num]=(Bitmap)msg.obj; // for(int i=msg.what-1;i<names.length;i++){ // Map<String,Object> listItem = new HashMap<String,Object>(); // listItem.put("face", imagesId[i]); // listItem.put("name", names[i]); // listItem.put("mark", mark[i]); // listItems.add(listItem); // } Map<String,Object> listItem = new HashMap<String,Object>(); listItem.put("face", imagesId[num]); listItem.put("name", names[num]); listItem.put("mark", mark[num]); listItems.add(listItem); SimpleAdapter simleAdapter = new SimpleAdapter(MainActivity.this, listItems, R.layout.custom_list ,new String[]{"face","name","mark"}, new int[]{R.id.face,R.id.name,R.id.mark}); simleAdapter.setViewBinder(new ViewBinder() { public boolean setViewValue(View view, Object data, String textRepresentation) { // 判断是否为我们要处理的对象 if (view instanceof ImageView && data instanceof Bitmap) { ImageView iv = (ImageView) view; iv.setImageBitmap((Bitmap) data); return true; } else return false; } }); lv1.setAdapter(simleAdapter); }////handleMessage };////handler = new Handler() lv1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO 自动生成的方法存根 Toast.makeText(MainActivity.this, "点击的是第"+position+"个条目", Toast.LENGTH_SHORT).show(); } }); // Bitmap catBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.cat); // Bitmap monkeyBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.monkey); // Bitmap rabbitBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.rabbit); // Bitmap ratBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.rat); // Bitmap imagesId[]={catBitmap,monkeyBitmap,rabbitBitmap,ratBitmap}; }///onCreate public void fun_HttpPost(final int i) {// //生成faceBitmap[] new Thread(new Runnable() {// //在子线程中传递msg,主线程中接收msg;;要是用fun_HttpPost()的返回值会失败 @Override public void run() { // TODO 自动生成的方法存根 String urlStr = "http://192.168.0.101:8080/download/servlet/download"; HttpPost request = new HttpPost(urlStr); // 如果传递参数多的话,可以对传递的参数进行封装 List<NameValuePair> params = new ArrayList<NameValuePair>(); // 设置要下载的头像名称 params.add(new BasicNameValuePair("picN", String .valueOf(i))); // params.add(new BasicNameValuePair("pic2","2")); // params.add(new BasicNameValuePair("pic3","3")); // params.add(new BasicNameValuePair("password", // passwordString)); // params.add(new BasicNameValuePair("nickname", // nicknameString)); try { HttpClient client = getHttpClient(); request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 执行请求返回相应 HttpResponse response = client.execute(request); // 判断是否请求成功 if (response.getStatusLine().getStatusCode() == 200) { // 获得响应信息 String responseMessage = EntityUtils .toString(response.getEntity()); Log.i("responseMessage", responseMessage + ",长度:" + responseMessage.length()); Bitmap bitmap = GenerateImage(responseMessage);// //生成Bitmap Message msg = new Message(); msg.what = i; // Log.i("------------------- msg.what=i---------------", String.valueOf(i - 1)); // msg.obj = bitmap;// //传递msg handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } }// //run() }).start(); }// /fun_register() // base64字符串转化成图片 public static Bitmap GenerateImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片 if (imgStr == null) // 图像数据为空 { Log.i("imgStr == null", "imgStr == null"); return setNullBitmapImage(); } Decoder.BASE64Decoder decoder = new Decoder.BASE64Decoder(); try { // Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 调整异常数据 b[i] += 256; } } InputStream ins = new ByteArrayInputStream(b); Bitmap bitmap = new BitmapFactory().decodeStream(ins); return bitmap; } catch (Exception e) { Log.i("imgStr == null,catch (Exception e)", "imgStr == null,catch (Exception e)"); return setNullBitmapImage(); } }// /GenerateImage private static Bitmap setNullBitmapImage() { String filePath = "/sdcard/1spray/11.jpg"; File file = new File(filePath); Bitmap bitmap = null; try { InputStream is = new FileInputStream(file); bitmap = new BitmapFactory().decodeStream(is); Log.i("setNullBitmapImage()", "setNullBitmapImage()"); // /imageView1.setImageBitmap(bitmap); } catch (FileNotFoundException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return bitmap; }///setNullBitmapImage // 初始化HttpClient,并设置超时 public HttpClient getHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); HttpClient client = new DefaultHttpClient(httpParams); return client; }// /public HttpClient getHttpClient() }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/face" android:layout_width="100dp" android:layout_height="100dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="57dp" android:layout_marginTop="20dp" android:layout_toRightOf="@+id/face" android:paddingLeft="20dp" android:text="TextView" android:textSize="20sp" /> <TextView android:id="@+id/mark" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/name" android:layout_below="@+id/name" android:layout_marginTop="10dp" android:textSize="15sp" android:text="mark" /> </RelativeLayout>
</pre><pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.listview_8" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="16" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.READ_LOGS" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
</pre><pre name="code" class="html">
服务器端::
package com; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import sun.misc.BASE64Encoder; public class download extends HttpServlet { /** * Constructor of the object. */ public download() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); // request.setCharacterEncoding("utf-8");////这句至关重要,不然中文的文件名称显示乱码 PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String picN = request.getParameter("picN"); //String pic2 = request.getParameter("pic2"); // String password = request.getParameter("password"); // String nickname = request.getParameter("nickname"); // String faceImageString = request.getParameter("faceImage"); out.print(GetImageStr(picN));// /输出文件的字符串 out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException * if an error occurs */ public void init() throws ServletException { // Put your code here } public static String GetImageStr(String picName) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 // String imgFile = // "d://test.jpg";//待处理的图片 String imgFile = "F://upload//"+picName+".jpg";// //可以 // String imgFile = "F://upload//软工大作业.ppt";// //可以 // String imgFile="F://upload//爱的勇气.mp3";//可以 // String imgFile="F://upload//upload.rar";//可以 InputStream in = null; byte[] data = null; // 读取图片字节数组 try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);// 返回Base64编码过的字节数组字符串 } // /GetImageStr }
时间: 2024-10-23 18:59:43