一定要在相冊查看下形成緩存
最近的一個連接服務端的應用,需要讀取圖片,一般供用戶發布商品選擇上傳圖片,初始的圖片列表應該是縮略圖,只有確定了,才上傳原圖,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; } }