安卓获取服务器返回的图片资源路径并下载图片

接之前一篇博客中介绍到服务器返回JSON数据给安卓客户端,本篇在此基础上增加了图片的下载和ListView显示的功能。首先添加一个ListView的简单布局如下,ListView中显示的内容为图片、名称和价格。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/vview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/listviewbackground"
    android:paddingBottom="5dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="5dp" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="80dp"
        android:layout_height="65dp"
        android:src="@drawable/image_loading" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/image"
        android:textColor="#000000"
        android:textSize="13dp"
        android:textStyle="italic" />

    <TextView
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_below="@id/title"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@id/image"
        android:textColor="#000000"
        android:textSize="11dp" />

</RelativeLayout>

接下来需要为ListView自定义一个适配器,自定义的这个适配器继承于ArrayAdapter<PictureBean>,在自定义适配器的构造方法中直接调用父类的构造方法将PictureBean对象部署到适配器中,然后重写其getView方法,为ListView中的控件添加显示内容。这部分的代码如下:

package com.example.restaurant;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.domain.PictureBean;

public class MyImageAndTextListAdapter extends ArrayAdapter<PictureBean> {

    public MyImageAndTextListAdapter(Context context, List<PictureBean> newsList) {
        super(context, 0, newsList);
    }

    private Map<Integer, View> viewMap = new HashMap<Integer, View>();

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = this.viewMap.get(position);
        if (rowView == null) {
            LayoutInflater inflater = ((Activity) this.getContext())
                    .getLayoutInflater();
            rowView = inflater.inflate(R.layout.item, null);
            PictureBean picture = this.getItem(position);

            TextView textView = (TextView) rowView.findViewById(R.id.title);
            textView.setText(picture.getName());

            TextView textView2 = (TextView) rowView.findViewById(R.id.time);
            textView2.setText("价格:" + picture.getPrice());

            ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
            String str = picture.getName() + "$" + picture.getPrice() + ".jpg";
            Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/restaurant/"
                    + str);
            imageView.setImageBitmap(bitmap);
            viewMap.put(position, rowView);
        }
        return rowView;
    }
}

添加完布局和适配器之后,接下来进行数据的读取和显示工作。在MainActivity的onCreate()方法中首先判断数据库中是否有数据,若数据库为空则从服务器端读取数据,若不为空则直接从数据库中读取数据。从服务器中获取数据的代码如下:

/**
     * 从服务器获取图片信息并将图片保存在SDCard上
     */
    private void updateFromServer() {

        showProgressDialog();
        getInfoThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 获得从服务器返回的图片信息和路径 JSON
                    Pictures = UptadePictureService.getJSONPictures();

                } catch (Exception e) {
                    // Toast.makeText(MainActivity.this, "连接服务器失败!",
                    // Toast.LENGTH_SHORT).show();
                } finally {
                    downOK = true;
                }
            }
        });
        getInfoThread.start();
        /**
         * 下载图片线程
         */
        getPictureThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 等待获取图片信息线程执行完毕
                    while (getInfoThread.getState() != Thread.State.TERMINATED) {

                    }
                    for (PictureBean picture : Pictures) {
                        /**
                         * 对传递进来的path进行处理
                         * 例如:E:\webTest\Restaurant\WebContent\Pictures
                         * \川菜\四喜丸子$22.jpg
                         * 将其转换成:Restaurant/Pictures/川菜/四喜丸子$22.jpg
                         */
                        String str = picture.getName() + "$"
                                + picture.getPrice() + ".jpg";
                        Bitmap bitmap = BitmapFactory
                                .decodeFile("/sdcard/restaurant/" + str);
                        if (bitmap == null) {
                            String url = picture.getPath();
                            String[] strList = url.split("\\\\");
                            url = strList[2] + "/" + strList[4] + "/"
                                    + strList[5] + "/" + strList[6];
                            // 下载图片并保存在SD卡中
                            down_file("http://192.168.1.103:8080/" + url,
                                    "/sdcard/restaurant/");
                        }
                    }

                    Message msg = new Message();
                    msgHandle.sendMessage(msg);
                } catch (Exception e) {
                    // Toast.makeText(MainActivity.this, "连接服务器失败!",
                    // Toast.LENGTH_SHORT).show();
                } finally {

                }

            }
        });
        getPictureThread.start();

    }

public void down_file(String url, String path) throws Exception {

        String filename = url.substring(url.lastIndexOf("/") + 1);
        /**
         * 处理中文路径 :由于URLEncoder.encode会对‘/‘和‘:‘进行转码,通过下面的代码可以避免这种错误
         */
        String[] strList = url.split("\\/");
        url = "";
        for (String mstr : strList) {
            if (mstr.contains(":")) {
                url = url + mstr + "/";
            } else {
                url = url + URLEncoder.encode(mstr, "utf-8") + ‘/‘;
            }
        }
        url = url.substring(0, url.length() - 1);
        Log.d("MainActivity", url);
        URL myURL = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            File file = new File(path);
            if (!file.exists()) {
                file.mkdir();
            }
            FileOutputStream out = new FileOutputStream(path + filename);
            // 把数据存入路径+文件名
            byte buf[] = new byte[1024];
            do {
                // 循环读取
                int numread = inputStream.read(buf);
                if (numread == -1) {
                    break;
                }
                out.write(buf, 0, numread);
            } while (true);
            inputStream.close();
        }

    }

接下来添加一个更新菜单按钮,该按钮可以从服务器获取最新的菜单信息。把应用部署到安卓模拟器上,基本的效果如下图所示:

时间: 2024-08-12 23:41:12

安卓获取服务器返回的图片资源路径并下载图片的相关文章

客户端的文件上传到服务器,服务器返回文件的路径

客户端的文件上传到服务器,服务器返回文件的路径 返回信息,客户端将文件保存 客户端: <?php header('content-type:text/html;charset=utf8'); $url = 'http://192.168.1.118/legcc/aaa.php';//访问的服务器的地址 $curl = curl_init(); $path = 'D:\www\ceshi\a02.jpeg';//客户端文件的绝对路径 $source = file_get_contents($pat

Java爬虫(一)利用GET和POST发送请求,获取服务器返回信息

本人所使用软件 eclipse fiddle UC浏览器 分析请求信息 以知乎(https://www.zhihu.com)为例,模拟登陆请求,获取登陆后首页,首先就是分析请求信息. 用UC浏览器F12,点击Network,按F5刷新.使用自己账号登陆知乎后,点www.zhihu.com网址后,出现以下界面  在General中,看到请求方式是GET,在fiddle里请求构造中,方法选定GET. 下拉后,看到Request Header,将里面所有的内容复制下来,粘贴到fiddle的请求构造里 

ASP.NET获取服务器文件的物理路径

如下: string fullpath = context.Server.MapPath("hello.htm"); //得到hello.htm的全路径 string content = System.IO.File.ReadAllText(); //读入文件内容 context.Response.Write(content); //将hello.htm的内容打出来 string username = context.Request["UserName"]; //获

http get请求获取服务器返回的应答数据

libcurl库中的参数CURLOPT_WRITEFUNCTION所设置的回调函数应该是这样的: size_t fun_cb( char *ptr, size_t size, size_t nmemb, void *userdata) 这个回调函数被调用的时机是有响应数据到达,这些数据由ptr指向,大小是size*nmemb.到这里为止还是文档上的说法.从socket的角度考虑,响应数据自然不一定会是以0结尾的字符串,而应当被认为是流数据.只要服务端没有关闭连接,只要服务端还在发送响应数据,这个

Ajax 学习之动态获取,返回服务器的值

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><h

HTTP基础与Android之(安卓与服务器通信)——使用HttpClient和HttpURLConnection

查看原文:http://blog.csdn.net/sinat_29912455/article/details/51122286 1客户端连接服务器实现内部的原理 GET方式和POST方式的差别 HTTP返回请求数据的三种方式 2使用HTTP协议访问网络 3HttpCient 简单来说用HttpClient发送请求接收响应都很简单只需要五大步骤即可要牢记 4DefaultHttpClient GET方式 POST方式 5Java中使用HTTPHttpURLConnection GET方式 PO

loadrunner中对服务器返回的数据选择性提交

在跟进项目的过程中,才体会到自己之前闷头看书再写小小的测试程序验证的学习方式很没有效率,知道动态关联,却也只是会参数化式的动态关联,这种关联是我们预先知道要提交的数据而进行的关联:更高一级的可能就是使用loadrunner自带的自动关联,对jsessionid和DSId进行关联,除此之外一无所知. 在项目中碰到的情况是:对输入框A进行参数化,假定当前参数数据为a1,参数化之后点击“查询”按钮,Server 返回a1的数据,选中a1进行提交.在这个过程中,根据参数不同Server返回的数据不同,且

Ajax 学习之获取服务器的值

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><h

在MVC中实现和网站不同服务器的批量文件下载以及NOPI下载数据到Excel的简单学习

嘿嘿,我来啦,最近忙啦几天,使用MVC把应该实现的一些功能实现了,说起来做项目,实属感觉蛮好的,即可以学习新的东西,又可以增加自己之前知道的知识的巩固,不得不说是双丰收啊,其实这周来就开始面对下载在挣扎啦,不知道从哪下手,而且自己针对一个文件下载的小小练习还是写过的,但是和项目中的下载完全就是两个世界,所以我只能抱着学习的心情查找资料啦,刚开始由于leader没有说怎么个下载的办法,我只能自己看些有关下载的资料啦,周一只是在猜测的学习,然后通过询问各路大神.就新学习了NOPI,当我看到Nopi下