• 最蛋疼的bug:读取图片缩略图(一定要在相冊查看下形成缓存)


    近期的一个连接服务端的应用。须要读取图片,一般供用户公布商品选择上传图片。初始的图片列表应该是缩略图。仅仅有确定了,才上传原图,OK不多说上代码

    package edu.buaa.erhuo;


    import java.io.File;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;


    import org.json.JSONArray;
    import org.json.JSONObject;


    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.app.Activity;
    import android.app.AlertDialog.Builder;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;
    import edu.buaa.erhuo.R;
    import edu.buaa.erhuo.Utils.NetworkUtils;


    public class PubActivity extends Activity {
    private EditText et_title,et_des;
    private Button btn_choose,btn_addSubmit;
    private Spinner spinner_typeId;
    private ArrayAdapter<String> adapter;
    private List<String> allValues = new ArrayList<String>();
    private List<Integer> allTypeIds = new ArrayList<Integer>();
    private Handler handler;
    private ImageView photoImg;


    private String filePath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pub);
    et_title=(EditText)findViewById(R.id.et_title);
    et_des=(EditText)findViewById(R.id.et_description);
    btn_choose=(Button)findViewById(R.id.btn_choose_photo);
    btn_addSubmit=(Button)findViewById(R.id.btn_add_submit);
    spinner_typeId=(Spinner)findViewById(R.id.spinner_type);
    photoImg=(ImageView)findViewById(R.id.img_photo);

    handler=new Handler(){
    public void handleMessage(Message msg) {
    if (msg.what==0) {//有网络且读取到数据
    adapter=new ArrayAdapter<String>(PubActivity.this, android.R.layout.simple_spinner_item,allValues);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner_typeId.setAdapter(adapter);
    }
    else if (msg.what==1) {//提交到后台成功
    Toast.makeText(PubActivity.this,"加入成功",Toast.LENGTH_SHORT).show();
    et_title.setText("");
    et_des.setText("");
    spinner_typeId.setSelection(0);
    photoImg.setImageURI(null);
    filePath=null;
    }
    else if (msg.what==2) {
    //提交到后台失败
    Toast.makeText(PubActivity.this,"加入失败",Toast.LENGTH_SHORT).show();
    }
    }
    };
    // 调用工具类。 查询全部的商品分类数据
    Thread t=new Thread(){
    public void run() {
    try {
    JSONArray array=NetworkUtils.getJSONArrayByUrl(NetworkUtils.GET_ALL_PRODUCT_TYPE_URL);
    System.out.println(array+"kane...........");
    // 循环查询到的数据。保存到List集合里
    for (int i = 0; i < array.length(); i++) {
    JSONObject obj = array.getJSONObject(i);
    allValues.add(obj.getString("type_name"));
    allTypeIds.add(obj.getInt("type_id"));
    }
    handler.sendEmptyMessage(0);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    };
    t.start();

    btn_addSubmit.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
    final ProgressDialog dialog=new ProgressDialog(PubActivity.this);
    dialog.setTitle("提示");
    dialog.setMessage("正在提交数据.........");
    dialog.show();
    Thread t=new Thread(){
    public void run() {
    Map<String,String> params=new HashMap<String, String>();
    params.put("product.product_name",et_title.getText().toString());
    params.put("product.description",et_des.getText().toString());
    params.put("product.type_id", allTypeIds.get(spinner_typeId.getSelectedItemPosition()).toString());
    if (filePath==null) {
    try {
    String result=NetworkUtils.postDataByUrl(NetworkUtils.PRODUCT_INSERT_URL, params);
    if (result.equals("ok")) {
    handler.sendEmptyMessage(1);
    }
    else {
    handler.sendEmptyMessage(2);
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    handler.sendEmptyMessage(2);
    }

    }
    else {
    try {
    String result = NetworkUtils.postFileByUrl(
    NetworkUtils.PRODUCT_INSERT_URL, params,
    filePath);
    if (result.equals("ok")) {
    handler.sendEmptyMessage(1);
    } else {
    handler.sendEmptyMessage(2);
    }
    } catch (Exception e) {
    e.printStackTrace();
    handler.sendEmptyMessage(2);
    }
    }
    dialog.dismiss();
    }
    };
    t.start();

    }
    });

    btn_choose.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
    Builder builder=new Builder(PubActivity.this);
    builder.setTitle("请选择");
    builder.setItems(new String[]{"拍照","从相冊选择"}, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialogInterface, int which) {
    switch (which) {
    case 0:
    Intent intent=new Intent(PubActivity.this,CameraActivity.class);
    startActivity(intent);
    break;


    case 1:
    Intent in = new Intent(
    PubActivity.this,
    SelectImageActivity.class);
    startActivityForResult(in, 1);



    break;
    }
    }
    });
    builder.setPositiveButton("取消",new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialogInterface, int which) {
    // TODO Auto-generated method stub

    }
    });
    builder.create().show();
    }
    });
    }
    //请求的activity返回一个结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
    filePath = data.getStringExtra("filePath");
    photoImg.setImageURI(Uri.fromFile(new File(filePath)));
    }
    }

    }

    package edu.buaa.erhuo;


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


    import edu.buaa.erhuo.adapter.PhotoImageAdapter;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.provider.MediaStore.Images;
    import android.provider.MediaStore.Images.Media;
    import android.provider.MediaStore.Images.Thumbnails;
    import android.app.Activity;
    import android.app.AlertDialog.Builder;
    import android.content.DialogInterface;
    import android.content.DialogInterface.OnClickListener;
    import android.content.Intent;
    import android.database.Cursor;
    import android.view.Menu;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ImageView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.GridView;


    public class SelectImageActivity extends Activity {
    private GridView gridView;
    private PhotoImageAdapter adapter;
    private List<Map<String, Object>> allValues=new ArrayList<Map<String,Object>>();
      @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select_image);
    gridView=(GridView)findViewById(R.id.grid);
    //取得数据,Thumbnails缩略图,必须先相冊查看形成缓存,不然没有缩略图
    Cursor c=getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, null,
    null,null,null);

    c.moveToFirst();
    while (!c.isAfterLast()) {
    Map<String,Object> map=new HashMap<String, Object>();
    //相应原图的ID
    map.put("imageId",c.getLong(c.getColumnIndex(Thumbnails.IMAGE_ID)));
    //DATA就是路径名
    map.put("filepath",c.getString(c.getColumnIndex(Thumbnails.DATA)));


    allValues.add(map);
    c.moveToNext();
    }
    c.close();


    adapter=new PhotoImageAdapter(allValues, this);
    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new OnItemClickListener() {


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
    long arg3) {
    final Map<String,Object> map=allValues.get(position);
    Builder builder=new Builder(SelectImageActivity.this);
    builder.setTitle("确定使用这张好照片吗?");
    ImageView img=new ImageView(SelectImageActivity.this);
    img.setImageURI(Uri.fromFile(new File(map.get("filepath").toString())));
    builder.setView(img);
    builder.setPositiveButton("确定", new OnClickListener() {

    @Override
    public void onClick(DialogInterface arg0, int arg1) {
    //获取图片原始位置
    //须要关联查询
    Cursor c=getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI,null,Media._ID+"= ?

    ", new String[]{map.get("imageId").toString()}, null);
    String realPath=null;
    if (c.moveToFirst()) {
    realPath=c.getString(c.getColumnIndex(Media.DATA));
    }
    c.close();
    Intent in=new Intent();
    in.putExtra("filepath",realPath);
    setResult(RESULT_OK,in);//给调用此activity的源头发给回馈信息
    finish();
    }
    });
    builder.setNegativeButton("取消",new OnClickListener() {

    @Override
    public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub

    }
    });
    builder.create().show();
    }
    });
    }
    }

    须要用到的adapter

    package edu.buaa.erhuo.adapter;


    import java.io.File;
    import java.util.List;
    import java.util.Map;


    import android.content.Context;
    import android.net.Uri;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AbsListView.LayoutParams;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import edu.buaa.erhuo.R;
    import edu.buaa.erhuo.Utils.Globals;


    public class PhotoImageAdapter extends BaseAdapter {


    private List<Map<String, Object>> allValues;
    private Context ctx;


    public PhotoImageAdapter(List<Map<String, Object>> allValues, Context ctx) {
    this.allValues = allValues;
    this.ctx = ctx;
    }


    @Override
    public int getCount() {
    return allValues.size();
    }


    @Override
    public Object getItem(int position) {
    return allValues.get(position);
    }


    @Override
    public long getItemId(int position) {
    return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
    convertView = LayoutInflater.from(ctx).inflate(
    R.layout.grid_image_line, null);
    convertView.setLayoutParams(new LayoutParams(
    LayoutParams.MATCH_PARENT, Globals.SCREEN_HEIGHT / 6));
    }


    Map<String, Object> map = allValues.get(position);


    ImageView img = (ImageView) convertView
    .findViewById(R.id.photo_img_line);


    img.setImageURI(Uri.fromFile(new File(map.get("filePath").toString())));


    return convertView;
    }


    }

  • 相关阅读:
    纯CSS绘制三角形(各种角度)
    富文本编辑器Quill(二)上传图片与视频
    富文本编辑器Quill(一)简单介绍
    Vue中使用Cropper.js裁剪图片
    Python使用LDAP做用户认证
    concurrent.futures进行并发编程
    Selenium及Headless Chrome抓取动态HTML页面
    七夕节快到了,做个图钉画以及学习下Pillow吧
    Python socket
    Python爬取视频(其实是一篇福利)
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5287369.html
Copyright © 2020-2023  润新知