android JSON upload images collection dose not work - android

I'm trying to upload some of images after selecting it from my UploadActivity.
public static int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
private static final int PICK_FROM_CAMERA = 1;
ArrayList<String> IPath = new ArrayList<String>();
public static Uri uri;
TextView msgLoading;
//ProgressBar pBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
msgLoading = (TextView) findViewById(R.id.msgLoading);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
final Cursor imagecursor = getImageCursor();
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
msgLoading.setVisibility(View.GONE);
}
},100);
final Button uploadBtn = (Button) findViewById(R.id.uploadDONE);
uploadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
for (int i = 0; i < len; i++) {
if (thumbnailsselection[i]) {
cnt++;
selectImages = arrPath[i];
IPath.add(selectImages);
}
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"You've selected Total " + cnt + " image(s).",
Toast.LENGTH_LONG).show();
Log.i("SelectedImages", String.valueOf(selectImages.toCharArray()));
Intent intentMessage = new Intent(UploadActivity.this,
ImagesForAds.class);
intentMessage.putStringArrayListExtra("IMAGE", IPath);
startActivity(intentMessage);
}
}
});
}
#NonNull
private Cursor getImageCursor() {
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
final Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
final int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
return imagecursor;
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView
.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id]) {
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]),
"image/*");
startActivity(intent);
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent i = new Intent(UploadActivity.this, ImagesForAds.class);
UploadActivity.this.finish();
startActivity(i);
super.onBackPressed();
}
and it's worked fine, I can back data to my main activity as below :
b = getIntent().getExtras();
if (b != null) {
ImgData = b.getStringArrayList("IMAGE");
for (int i = 0; i < ImgData.size(); i++) {
map.add(ImgData.get(i).toString());
}
}
now it's ok... I need to upload those Images that I selected, here is my asyncTask:
public class ImageUploadTask extends AsyncTask<String, Void, String> {
String sResponse = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(ImagesForAds.this, "Uploading",
"Please wait...", true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
String url = "myLink";
int i = Integer.parseInt(params[0]);
Bitmap bitmap = decodeFile(map.get(i));
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
entity = new MultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
//entity.addPart("user_id", new StringBody("199"));
//entity.addPart("club_id", new StringBody("10"));
entity.addPart("images", new ByteArrayBody(data,
"image/jpeg", params[1]));
Log.i(TAG, "array map: " + map.get(i));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
sResponse = EntityUtils.getContentCharSet(response.getEntity());
System.out.println("sResponse : " + sResponse);
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return sResponse;
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),
sResponse + " Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
count++;
if (count < map.size()) {
new ImageUploadTask().execute(count + "", "hm" + count
+ ".jpg");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
and here how I invoke it :
int count = 0;
new ImageUploadTask().execute(count + "", "pk" + count + ".jpg");
The issue with AsyncTask.. it's upload only 1 image, how I can upload all images I have selected ?

This is your flaw :
if (count < map.size()) {
new ImageUploadTask().execute(count + "", "hm" + count
+ ".jpg");
}
not a good idea to create a new ImageUploadTask inside ImageUploadTask.
move your for loop inside doInBackground() and for updating user use publishProgress() and catch that event inside onProgressUpdate.
Read more about AsyncTask : https://developer.android.com/reference/android/os/AsyncTask.html

Related

In custom gallery, On scrolling images repalcing

I have create a custom gallery for selecting multiple photos in android . I am using AsynTask to set bitmap. When i am scrolling my screen, images replacing with next images and the setting to previous location.
public class CustomGallery extends Activity implements View.OnClickListener{
/**
* Created by Ramesh on 04-Jan-16.
*/
private ImageAdapter imageAdapter;
private String[] arrPath;
private boolean[] thumbnailsSelection;
private int ids[];
private int count;
String imgDecode;
ArrayList<String> imageIdList = new ArrayList<String>();
final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_gallery);
System.out.println("MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE-->" + MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
if (Integer.valueOf(Build.VERSION.SDK_INT)>=23) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
Log.i("Permission Log", " Permission Granted----> if cond");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
} else {
// No explanation needed, we can request the permission.
Log.i("Permission Log", " Permission Granted----> else cond");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
else{
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
Log.i( MediaStore.Images.Media.DATA, "Media Store Images.Media.Data");
Log.i(MediaStore.Images.Media._ID, "Media Store Images.Media_id" );
final String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC" ;
Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null,
orderBy );
final int image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID);
imgDecode = imageCursor.getColumnName(image_column_index);
this.count = imageCursor.getCount();
this.arrPath = new String[this.count];
ids = new int[count];
this.thumbnailsSelection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imageCursor.moveToPosition(i);
ids[i] = imageCursor.getInt(image_column_index);
int dataColumnIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA);
arrPath[i] = imageCursor.getString(dataColumnIndex);
}
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imageCursor.close();
final Button selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(this);
Button cancelBtn = (Button) findViewById(R.id.cancelBtn);
cancelBtn.setOnClickListener(this);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
setResult(Activity.RESULT_CANCELED);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Log.i(" Permission Log", " Permission Granted");
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
Log.i( MediaStore.Images.Media.DATA, "Media Store Images.Media.Data");
Log.i(MediaStore.Images.Media._ID, "Media Store Images.Media_id" );
final String orderBy = MediaStore.Images.Media._ID;
Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
//final int image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID);
final int image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID );
imgDecode = imageCursor.getColumnName(image_column_index);
this.count = imageCursor.getCount();
this.arrPath = new String[this.count];
ids = new int[count];
this.thumbnailsSelection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imageCursor.moveToPosition(i);
ids[i] = imageCursor.getInt(image_column_index);
int dataColumnIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA);
arrPath[i] = imageCursor.getString(dataColumnIndex);
}
GridView image_grid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
image_grid.setAdapter(imageAdapter);
imageCursor.close();
final Button selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(this);
Button cancelBtn = (Button) findViewById(R.id.cancelBtn);
cancelBtn.setOnClickListener(this);
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Log.i("Permission Log", " else cond");
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
private void setBitmap(final ImageView iv, final int id) {
new AsyncTask<Void, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(Void... params) {
return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MINI_KIND, null);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
iv.setImageBitmap(result);
}
}.execute();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.selectBtn:
final int len = thumbnailsSelection.length;
String selectImages = "";
int cnt = 0;
for (int i = 0; i < len; i++) {
if (thumbnailsSelection[i]) {
cnt++;
Log.i("Custom Gallery", "Inside for loop----->");
selectImages = selectImages + arrPath[i];
System.out.println("Array Path--" + arrPath[i]);
imageIdList.add(arrPath[i]);
}
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
} else if (cnt > 5) {
Toast.makeText(getApplicationContext(), "You can select only 5 images", Toast.LENGTH_LONG).show();
} else {
// System.out.println("My ListItem -->>" + imageIdList);
/* Bundle bundel = new Bundle();
bundel.putStringArrayList("key", imageIdList);
Intent intent = new Intent(getApplicationContext(), AddVehicle.class);
intent.putExtras(bundel);
startActivity(intent);
finish();*/
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("image-list", imageIdList);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
break;
case R.id.cancelBtn:
onBackPressed();
break;
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
/*if (convertView == null) {*/
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.gallery_item, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
/* } else {
holder = (ViewHolder) convertView.getTag();
} */
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsSelection[id]) {
cb.setChecked(false);
System.out.println("if thumbnail selection");
thumbnailsSelection[id] = false;
} else {
System.out.println("else thumbnail selection");
cb.setChecked(true);
thumbnailsSelection[id] = true;
}
}
});
holder.imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int id = holder.checkbox.getId();
if (thumbnailsSelection[id]) {
Log.i("Custom Gallery", "if image click----->");
holder.checkbox.setChecked(false);
thumbnailsSelection[id] = false;
} else {
Log.i("Custom Gallery", "if image not clicked----->");
holder.checkbox.setChecked(true);
thumbnailsSelection[id] = true;
}
}
});
try {
setBitmap(holder.imageview, ids[position]);
} catch (Throwable e) {
Log.i(e.getMessage(), "Exception:");
}
holder.checkbox.setChecked(thumbnailsSelection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
}

android how to load images from internal memory in gridview

I follow this tutorial http://vikaskanani.wordpress.com/2011/07/20/android-custom-image-gallery-with-checkbox-in-grid-to-select-multiple/
below is my code which load images from application internal memory and display using simple adapter but now i want to ad checkbox i found this tutorial which llad images from gallery i want to customize this sample code to load image from file location what do i do how do i change this code to load image from file location or how to customize its adapter to load my files what do i do help plz
<!-----------------this is my code------>
GridView gridView;
SimpleAdapter simpleAdapter;
gridView =(GridView)findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int
position,long id) {
if(currentFiles[position].isDirectory())
{
root = new File("/data/data/com.myexample/files
/"+FileName(currentFilePath[position])+"/");
Log.e("Root first",root+ " ");
currentFiles = root.listFiles();
inflateListView(currentFiles);
}
else if(currentFiles[position].isFile())
{
inflateListView(currentFiles);
} } });
private void inflateListView(File[] files){
List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();
for(int i=0;i<files.length;i++)
{
Map<String, Object> listItem = new HashMap<String, Object>();
if(files[i].isDirectory())
{
listItem.put("icon", R.drawable.folder);
}
else
{
listItem.put("icon", files[i]);
}
listItem.put("fileName", files[i].getName());
listItems.add(listItem);
}
simpleAdapter=new SimpleAdapter(this,listItems,R.layout.line,new String[]
{"icon","fileName"},new int[]{R.id.icon,R.id.file_name});
gridView.setAdapter(simpleAdapter);
<!--------this is sample code which load images from Gallery--------->>>>>>
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class AndroidCustomGalleryActivity extends Activity {
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null,
null, orderBy);
int image_column_index =
imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex =
imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
final Button selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i]){
cnt++;
selectImages = selectImages + arrPath[i] +
"|";
}
}
if (cnt == 0){
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"You've selected Total " + cnt +
"
image(s).",
Toast.LENGTH_LONG).show();
Log.d("SelectedImages", selectImages);
}
}
});
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.galleryitem, null);
holder.imageview = (ImageView)
convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox)
convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id]){
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.imageview.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" +
arrPath[id]), "image/*");
startActivity(intent);
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
}
generally speaking you should create some collection of images files and than use BitmapFactory to load them like this:
public static Bitmap getBitmapFromFile(File bitmapFile, int sideSizeLimit){
if (bitmapFile==null || !bitmapFile.exists() || !bitmapFile.canRead())
return null;
int maxWidth = 0, maxHeight = 0;
if (sideSizeLimit>0){
maxWidth = sideSizeLimit;
maxHeight = sideSizeLimit;
}
try {
//decode image size
BitmapFactory.Options bmfOtions = new BitmapFactory.Options();
bmfOtions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(bitmapFile),null,bmfOtions);
//Find the correct scale value. It should be the power of 2.
//final int REQUIRED_SIZE=70;
int width_tmp=bmfOtions.outWidth, height_tmp=bmfOtions.outHeight;
int scale=1;
while(width_tmp > maxWidth || height_tmp > maxHeight){
width_tmp/=2;
height_tmp/=2;
scale++;
}
bmfOtions.inSampleSize = scale;
bmfOtions.inJustDecodeBounds = false;
//decode with inSampleSize
//BitmapFactory.Options o2 = new BitmapFactory.Options();
return BitmapFactory.decodeStream(new FileInputStream(bitmapFile), null, bmfOtions);
} catch (FileNotFoundException e) {}
return null;
}
also you should read this http://developer.android.com/training/displaying-bitmaps/index.html
ah, I found some example to start from (collecting files):
public static boolean clearImagesCache(){
// depends on isExternalStorageAvailable()
final File cacheDir= getCacheDir(); //new File(Environment.getExternalStorageDirectory() + SD_CACHE_PATH);
if( !cacheDir.exists() )
return false;
final File[] files = cacheDir.listFiles();
File file2delete;
for(int i=0; i<files.length; i++) {
file2delete = files[i];
if(!file2delete.isDirectory() && file2delete.canWrite())
file2delete.delete();
}
return true;
}
this code however deletes all of files in given directory but you have to collect them into some collection.

how to change default file path

my code is save images from gallery in default location /data/data/applicationname/files
if i change path in AppPhotos class to "/data/data/com.isummation.customgallery/files/";
this is not show any image in list what do ido?? plz help me
public class AndroidCustomGalleryActivity extends Activity {
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
Cursor imagecursor;
int image_column_index;
Button selectBtn;
ProgressDialog myProgressDialog = null;
DataBase db;
Handler handle = new Handler(){
public void handleMessage(Android.os.Message message) {
if (message.what == 1)
{
hideProgress();
GridView imagegrid = (GridView)
findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
}
else if (message.what == 3)
{
hideProgress();
AndroidCustomGalleryActivity.this.finish();
}
else if (message.what == 2)
{
hideProgress();
}
super.handleMessage(msg);
};
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
showProgress();
new Thread() {
public void run() {
try
{
SelecedtPhotos();
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 3;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
});
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem,
null);
holder.imageview = (ImageView)
convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox)
convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id])
{
cb.setChecked(false);
thumbnailsselection[id] = false;
}
else
{
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
/*holder.imageview.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" +
arrPath[id]), "image/*");
startActivity(intent);
}
});*/
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
public void loadFeed()
{
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns, null,null, orderBy);
image_column_index =
imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++)
{
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex =
imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] =
MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext()
.getContentResolver(), id,MediaStore.Images.Thumbnails.MICRO_KI ND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
imagecursor.close();
}
private void showProgress()
{
myProgressDialog =
ProgressDialog.show(AndroidCustomGalleryActivity.this,null, "Loading
Data...", true);
}
private void hideProgress()
{
if (myProgressDialog != null)
myProgressDialog.dismiss();
}
///////////////////// Get File Name from path ////////////////////////////
public String FileName(String path)
{
String f = " /";
boolean c = false;
for(int i=path.length()-1;i>0;i--)
{
if(c == false)
if(path.charAt(i) == f.charAt(1))
{
c = true;
return
path.substring(i+1,path.length());
}
}
return "";
}
///////////////////// Get Extension from path ////////////////////////////
public String fileExt(String audio)
{
String fileName = "";
String f = " .";
boolean c = false;
for(int I=audio.length()-1;I>0;I--)
{
if(c == false)
if(audio.charAt(I) == f.charAt(1))
{
fileName = audio.substring(I+1, audio.length());
c = true;
}
}
return fileName;
}
public void SelecedtPhotos()
{
final int len = thumbnailsselection.length;
// int cnt = 0;
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
//cnt++;
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(arrPath[i],
options);
try {
FileOutputStream outputStream =
openFileOutput(FileName(arrPath[i]), Context.MODE_PRIVATE);
outputStream.write(getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
db.insert_update("INSERT INTO Photos(name,ext,path)
VALUES ('"+FileName(arrPath[i])+"','"+fileExt(arrPath[i])+"','"+arrPath[i]+"')");
db.close();
File file = new File(arrPath[i]);
boolean t = file.delete();
}
}
}
}
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.database.DataBase;
import com.isummation.customgallery.R;
public class AppPhotos extends Activity{
ProgressDialog myProgressDialog = null;
ListView list;
Activity activity = AppPhotos.this;
List<AppPhotosData> picList;
DataBase db;
int position;
Handler handle = new Handler(){
public void handleMessage(Android.os.Message message) {
if (message.what == 1)
{
hideProgress();
list.setAdapter(new
AppPhotosAdapter(getApplicationContext(),activity,0,picList));
}
else if (message.what == 2)
{
hideProgress();
}
super.handleMessage(msg);
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photolist);
list = (ListView) findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
position = arg2;
AlertDialog.Builder builder = new
AlertDialog.Builder(AppPhotos.this);
builder.setTitle("Hidden Photos");
builder.setMessage("Are you sure you want to revert the
photo?");
builder.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
DialogBtn();
}
});
builder.setNegativeButton("No", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
private void showProgress()
{
myProgressDialog = ProgressDialog.show(AppPhotos.this,null, "Loading...",
true);
}
private void hideProgress()
{
if (myProgressDialog != null)
myProgressDialog.dismiss();
}
public void loadFeed()
{
String filePaths = "/data/data/com.isummation.customgallery/files/";
File outputFile1 = new File(filePaths);
File[] files1 = outputFile1.listFiles();
picList = new ArrayList<AppPhotosData>();
for(File f:files1)
{
AppPhotosData picObj = new AppPhotosData();
Bitmap bmDulicated4 = BitmapFactory.decodeFile(f.getAbsolutePath());;
picObj.setImage(bmDulicated4);
picObj.setName(f.getName());
picList.add(picObj);
}
}
public void DialogBtn()
{
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
Cursor DataC = db.selectQuery("SELECT path FROM Photos where name
='"+picList.get(position).getName()+"'");
if(DataC.getCount() > 0)
{
Bitmap bitmap = picList.get(position).getImage();
if(picList.get(position).getImage() != null)
{
try {
FileOutputStream outputStream = new
FileOutputStream(DataC.getString(DataC.getColumnIndex("path")));
outputStream.write(getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
File file = new File("/data/data/com.isummation.customgallery
/files/"+picList.get(position).getName());
file.delete();
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
}
db.close();
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
}
Manually create your app directory in sd card and then save image in that directory.
You can try following snippet.
String root=Environment.getExternalStorageDirectory().toString();
File myDir = new File(root+"/demo_image");
if(!myDir.exists())
{
myDir.mkdir();
}
String fname = "Image"+String.valueOf(System.currentTimeMillis())+".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
photo.compress(Bitmap.CompressFormat.JPEG,100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

add image to sdcard folder in android

I want to develop an android application that can select multiple images and save them in a folder of sdcard. I could select multiple files but when i want to save them in sdcard folder there is only images name. I have understood it when i tried to show those images using GridView there are no images. Here is my code.....
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.image_selection);
Bundle b=getIntent().getExtras();
directoryName=b.getString("key");
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
final Button selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
// TODO Auto-generated method stub
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
cnt++;
selectImages = selectImages + arrPath[i] + "|";
String sendString=extractString(arrPath[i]);
saveImageToSdCard(sendString,arrPath[i]);
Toast.makeText(getApplicationContext(),
sendString,
Toast.LENGTH_LONG).show();
}
}
}
});
}
public String extractString(String myString)
{
String finalString="";
int index = 0;
int count=0;
char newCharacter[]=new char[50];
char[] charArray = myString.toCharArray();
int length=myString.length();
for (int i = 0; i < length; i++)
{
char charString=charArray[i];
if(charString=='/')
{
index=i;
}
}
for (int i = index+1; i < length; i++)
{
newCharacter[count]=charArray[i];
count++;
}
finalString=String.valueOf(newCharacter);
return finalString;
}
public void saveImageToSdCard(String imageName, String fullPath)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root +"/"+directoryName);
String fname = imageName;
final File file = new File (myDir, fname);
if (file.exists ())file.delete();
try
{
final Bitmap myBitmap=BitmapFactory.decodeFile(fullPath);
new Thread() {
public void run()
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (myBitmap != null)
{
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
}
try {
if (file.createNewFile()) {
//
} else {
//
}
FileOutputStream fo;
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
// result.recycle();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
FileOutputStream stream=new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
stream.flush();
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id]){
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.imageview.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*");
startActivity(intent);
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder
{
ImageView imageview;
CheckBox checkbox;
int id;
}
how can i solve the problem.Thanks...
It seems there is a similar, already answered question:
How to get path by MediaStore.Images.Media
The solution is in the first comment of the answer.

Android gridview fail to refresh after image is removed

Below is my code modified from other sample.
Now my flow is user will select multiple images and when click on SELECT button, will have alertdialog pop up to ask "Remove the photo once upload successful"
so when finished upload it will call onActivityResult.
in onActivityResult, I will
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case UPLOAD_IMAGES:
if (resultCode == RESULT_OK){
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imagegrid.invalidateViews();
AndroidCustomGalleryActivity.this
.runOnUiThread(new Runnable() {
public void run() {
updateUI();
}
});
System.out.println("Updated UI");
}
}
}
But my gridview still fail to refresh, the removed image still show.
Full source code is here.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
imageAdapter = new ImageAdapter();
imageAdapter.initialize();
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imagegrid.setAdapter(imageAdapter);
AndroidCustomGalleryActivity.this
.runOnUiThread(new Runnable() {
public void run() {
updateUI();
}
});
final Button selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final int len = imageAdapter.images.size();
int cnt = 0;
String selectImages = "";
for (int i = 0; i < len; i++) {
if (imageAdapter.images.get(i).selection) {
cnt++;
selectImages = selectImages
+ imageAdapter.images.get(i).id + ",";
}
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else {
selectImages = selectImages.substring(0,selectImages.lastIndexOf(","));
AlertDialog.Builder helpBuilder = new AlertDialog.Builder(AndroidCustomGalleryActivity.this);
helpBuilder.setTitle("Photo upload");
helpBuilder.setMessage("Remove the photo once upload successful.");
UploadPhotoOnClickYes uploadPhotoOnClickYes = new UploadPhotoOnClickYes(AndroidCustomGalleryActivity.this,
UploadQueue.class, selectImages);
UploadPhotoOnClickNo uploadPhotoOnClickNo = new UploadPhotoOnClickNo(AndroidCustomGalleryActivity.this,
UploadQueue.class, selectImages);
helpBuilder.setPositiveButton("Yes",uploadPhotoOnClickYes);
helpBuilder.setNegativeButton("No", uploadPhotoOnClickNo);
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case UPLOAD_IMAGES:
if (resultCode == RESULT_OK){
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imagegrid.invalidateViews();
AndroidCustomGalleryActivity.this
.runOnUiThread(new Runnable() {
public void run() {
updateUI();
}
});
System.out.println("Updated UI");
}
}
}
public void updateUI() {
imageAdapter.checkForNewImages();
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ArrayList<ImageItem> images = new ArrayList<ImageItem>();
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void initialize() {
images.clear();
final String[] columns = { MediaStore.Images.Thumbnails._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns,
MediaStore.Images.Media.DATA + " like ? ",
new String[] {"%DVS%"},
orderBy);
if(imagecursor != null){
int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
imageItem.id = id;
lastId = id;
imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
images.add(imageItem);
}
imagecursor.close();
}
notifyDataSetChanged();
}
public void checkForNewImages(){
images.clear(); //new
//Here we'll only check for newer images
final String[] columns = { MediaStore.Images.Thumbnails._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns,
MediaStore.Images.Media.DATA + " like ? ",
new String[] {"%DVS%"},
orderBy); //new
int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
imageItem.id = id;
lastId = id;
imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
images.add(imageItem);
}
imagecursor.close();
notifyDataSetChanged();
}
public int getCount() {
return images.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView
.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ImageItem item = images.get(position);
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (images.get(id).selection) {
cb.setChecked(false);
images.get(id).selection = false;
} else {
cb.setChecked(true);
images.get(id).selection = true;
}
}
});
holder.imageview.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int id = v.getId();
ImageItem item = images.get(id);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
final String[] columns = { MediaStore.Images.Media.DATA };
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
MediaStore.Images.Media._ID + " = " + item.id, null, MediaStore.Images.Media._ID);
if (imagecursor != null && imagecursor.getCount() > 0){
imagecursor.moveToPosition(0);
String path = imagecursor.getString(imagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
File file = new File(path);
imagecursor.close();
intent.setDataAndType(
Uri.fromFile(file),
"image/*");
startActivityForResult(intent, VIEW_IMAGE);
}
}
});
holder.imageview.setImageBitmap(item.img);
holder.checkbox.setChecked(item.selection);
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
}
class ImageItem {
boolean selection;
int id;
Bitmap img;
}
I can't try your code right now, but try this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case UPLOAD_IMAGES:
if (resultCode == RESULT_OK){
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
AndroidCustomGalleryActivity.this
.runOnUiThread(new Runnable() {
public void run() {
updateUI();
imageAdapter.notifyDataSetChanged();
}
});
System.out.println("Updated UI");
}
}
}
I just moved the invalidation of the gridview after you remove the elements.
I found the answer by myself this is because I delete the image using file.delete. So it only remove the physical file but the removed image still cached.
So need to use this method to remove the file.
Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri itemUri = ContentUris.withAppendedId(contentUri, item.media_id);
getContentResolver().delete(itemUri, null, null);

Categories

Resources