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.
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.
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();
}
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);