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;
}
}
Related
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
Actually I have made a Custom gallery. All the image are shown in my Custom gallery. But here is a problem. When delete the image using delete button, image files are deleted from the memory, but still show the image ( I mean thumbnails are remaining ) . how to clear the data and refresh the gallery instantly.
Here is my code below
MainActivity.java
public class MainActivity extends Activity {
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
File file = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show();
final Button selectBtn = (Button) findViewById(R.id.selectBtn);
final Button shareBtn = (Button) findViewById(R.id.btnShare);
//delete image.
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
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] +" | ";
file= new File(arrPath[i]);
if(file.exists())
{
file.delete();
Log.v("roni", selectImages);
//arrPath[i] = null;
//selectImages = null;
Log.v("roni", arrPath[i]);
}
}
}
if (cnt == 0){
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else
{
//thumbnails= null;
show();
Toast.makeText(getApplicationContext(),cnt +" Images Deleted ",Toast.LENGTH_LONG).show();
Log.v("SelectedImages", selectImages);
}
}
});
//share image.
shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
final int len = thumbnailsselection.length;
int cnt = 0;
ArrayList<Uri> imageUris = new ArrayList<Uri>();
Uri path= null;
String selectImages = "";
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
cnt++;
selectImages = selectImages + arrPath[i] +" | ";
Log.v("roni", selectImages);
path = Uri.parse(arrPath[i]);
imageUris.add(path);
}
}
if (cnt == 0){
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else
{
Log.v("roni", selectImages);
Toast.makeText(getApplicationContext(),cnt +" Images shared ",Toast.LENGTH_SHORT).show();
Log.d("SelectedImages", selectImages);
}
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));
startActivity(shareIntent);
}
});
show();
}
public void show() {
//stored data
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];
//move image
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.MINI_KIND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
}
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) {
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) {
int id = v.getId();
/*Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*");
startActivity(intent);
*/
Intent intent = getIntent();
Uri data = intent.getData();
//Check If data type is Image
if (intent.getType().indexOf("image/") == id)
{
//imageview.setImageURI(data);
ImageView imge = (ImageView)findViewById(R.id.result);
imge.setImageURI(data);
}
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
} }
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mygallary"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:configChanges="orientation|keyboardHidden" >
<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" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
</application>
After changing the code
public class MainActivity extends Activity {
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
File file = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show();
final Button selectBtn = (Button) findViewById(R.id.selectBtn);
final Button shareBtn = (Button) findViewById(R.id.btnShare);
//delete image.
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
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] +" | ";
file= new File(arrPath[i]);
if(file.exists())
{
file.delete();
imageAdapter.notifyDataSetChanged();
Log.v("roni", selectImages);
//arrPath[i] = null;
//selectImages = null;
Log.v("roni", arrPath[i]);
}
}
}
if (cnt == 0){
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else
{
//thumbnails= null;
imageAdapter.notifyDataSetChanged();
show();
Toast.makeText(getApplicationContext(),cnt +" Images Deleted ",Toast.LENGTH_LONG).show();
Log.v("SelectedImages", selectImages);
}
}
});
//share image.
shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
final int len = thumbnailsselection.length;
int cnt = 0;
ArrayList<Uri> imageUris = new ArrayList<Uri>();
Uri path= null;
String selectImages = "";
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
cnt++;
selectImages = selectImages + arrPath[i] +" | ";
Log.v("roni", selectImages);
path = Uri.parse(arrPath[i]);
imageUris.add(path);
}
}
if (cnt == 0){
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else
{
Log.v("roni", selectImages);
Toast.makeText(getApplicationContext(),cnt +" Images shared ",Toast.LENGTH_SHORT).show();
Log.d("SelectedImages", selectImages);
}
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));
startActivity(shareIntent);
}
});
show();
}
public void show() {
//stored data
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];
//move image
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.MINI_KIND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
}
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) {
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) {
int id = v.getId();
/*Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*");
startActivity(intent);
*/
/*Intent intent = getIntent();
Uri data = intent.getData();
//Check If data type is Image
if (intent.getType().indexOf("image/") == id)
{
//imageview.setImageURI(data);
ImageView imge = (ImageView)findViewById(R.id.result);
imge.setImageURI(data);
}*/
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
}
before calling notifyDataSetChanged(); You should remove Deleted image from thumbnails
you need a method in your Custom Adapter to do that
i don't know how to remove one item in Bitmap[] array. but if you can use List<Bitmap> instead of that, the method will be like this :
public void RemoveThumbnail(int position)
{
this.thumbnails.remove(position);
//notifyDataSetChanged() can be called in this method or after
//calling this method in MainActivity
notifyDataSetChanged();
}
otherwise this is something that removes thumbnail in specific position :
public void RemoveThumbnail(int position)
{
Bitmap[] temp = new Bitmap[thumbnails.length - 1];
int tempIndex = 0;
for (int i = 0 ; i < thumbnails.lenght ; i++)
{
if(i != position)
temp[tempIndex ++] = thumbnails[i];
}
thumbnails = temp;
//notifyDataSetChanged() can be called in this method or after
//calling this method in MainActivity
notifyDataSetChanged();
}
You should notify your adapter.
First declare your adapter (imageAdapter for you) in top of codes (before onClickListeners) and then call this any time you change something (for example after deleting photos in your onClickListener):
imageAdapter.notifyDataSetChanged();
Try sending a broadcast after delete a file. In Kotlin you can do :
private fun deleteImage(path: String) {
val fDelete = File(path)
if (fDelete.exists()) {
if (fDelete.delete()) {
MediaScannerConnection.scanFile(this, arrayOf(Environment.getExternalStorageDirectory().toString()), null) { _, _ ->
Log.d("debug", "DELETE FILE DONE")
finish()
}
}
}
}
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.
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.
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);