In my code when i take image from camera it shows correctly in imageview. But when i take second image, both listview items shows same picture..Old picture replaces with new one..when i take third picture then all of three items show same result.and so on..Please can anyone solve my problem.
public class CustomerRegistrationL0 extends Activity {
int take_image;
int UploadFile;
static SimpleAdapter Adapter;
static Bitmap thumbnail;
static String encodedImageString;
Bitmap image2;
LayoutInflater mInflater;
Uri selectedImage ;
static ListView listviewattachment;
public ArrayList<ListItem> myItems = new ArrayList<ListItem>();
private MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cr_l0);
//declare fields
final EditText textcnic=(EditText)findViewById(R.id.EditTextCNIC);
final String cnic=textcnic.getText().toString();
final EditText textmobile=(EditText)findViewById(R.id.editTextMob);
final String mobileNo=textmobile.getText().toString();
final EditText textname=(EditText)findViewById(R.id.editTextName);
final String name=textname.getText().toString();
final EditText textaddress=(EditText)findViewById(R.id.EditTextAdd);
final String address=textaddress.getText().toString();
final EditText textkin=(EditText)findViewById(R.id.EditTextKin);
final String nextkin=textkin.getText().toString();
listviewattachment=(ListView)findViewById(R.id.listView1);
//////////////////////////////////////////////////////////
//make listview scrollable manuallly(shit)
listviewattachment.setOnTouchListener(new ListView.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent arg1) {
// TODO Auto-generated method stub
int action = arg1.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(arg1);
return true;
}
});
//////////////// // //////////////////////////////////////////////////////////////
Button buttonCamera=(Button)findViewById(R.id.buttonCamera);
Button buttonFromGallery=(Button)findViewById(R.id.buttonAttach);
Button formSubmit=(Button)findViewById(R.id.buttonSubmit);
buttonCamera.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, take_image);
}
});
buttonFromGallery.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
UploadFile);
}
});
formSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
validate(textcnic,textmobile,textname,textaddress,textkin);
//decoding bytes
String attachedImage=encodedImageString;
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("CNIC Number", cnic);
jsonObj.put("Mobile Number", mobileNo);
jsonObj.put("Name", name);
jsonObj.put("Address", address);
jsonObj.put("Next Kin", nextkin);
jsonObj.put("Image",attachedImage);
String jsonString=jsonObj.toString();
File sdcard = Environment.getExternalStorageDirectory();
try {
File myfile = new File(sdcard,"JSONCache.json");
myfile.createNewFile();
Writer myOutWriter = new BufferedWriter(new FileWriter(myfile));
myOutWriter.write(jsonString);
myOutWriter.close();
Toast.makeText(v.getContext(), "File Created", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.getStackTrace();
Toast.makeText(v.getContext(), "COuld not create file", Toast.LENGTH_LONG).show();
}
//end of write json object
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write json object
}
});
}
private void validate(EditText cnic, EditText mobile,
EditText name, EditText address, EditText kin) {
// TODO Auto-generated method stub
if(name.getText().toString().trim().equals("")){
name.setError("Please Enter Name");
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK )
{
if (requestCode==UploadFile){
// Uri selectedImage = data.getData();
// if ("content".equalsIgnoreCase(selectedImage.getScheme())) {
// String[] filePathColumn = { "_data" };
//Cursor cursor = getContentResolver().query(selectedImage,
// filePathColumn, null, null, null);
//cursor.moveToFirst();
//int columnIndex = cursor.getColumnIndex("_data");}
// String picturePath = cursor.getString(columnIndex);
// cursor.close();
// }
// else if ("file".equalsIgnoreCase(selectedImage.getScheme())) {
// String path= selectedImage.getPath();}
/* Uri selectedImage = data.getData();
String[] filePathColumn = { "data"};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();*/
}
if (requestCode == take_image) {
//get image
thumbnail = (Bitmap) data.getExtras().get("data");
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
factoryOptions.inJustDecodeBounds = true;
int imageWidth = factoryOptions.inDensity=50;
int imageHeight = factoryOptions.inDensity=50;
image2 = Bitmap.createScaledBitmap(thumbnail, imageWidth , imageHeight, true);
//////listview work
listviewattachment.setItemsCanFocus(true);
myAdapter = new MyAdapter();
ListItem listItem = new ListItem();
myItems.add(listItem);
listviewattachment.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
////////////////////end of listview work
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//encode image
byte[] b = bytes.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
}
}
}
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return myItems.size();
}
public ListItem getItem(int position) {
return myItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.imageview2, null);
holder.image = (ImageView) convertView
.findViewById(R.id.imageView2);
holder.Delete=(Button)convertView.findViewById(R.id.buttonClose);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.image.setImageBitmap(image2);
holder.image.setTag(position);
holder.Delete.setTag(position);
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
final Dialog imgDialog = new Dialog(view.getContext(),android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
imgDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
imgDialog.setCancelable(false);
// layout imageview2 is used because when i use simple imageview layout dialogue with imageview and closebutton,
// every taken image at instancewill not be shown in dialogue.
imgDialog.setContentView(R.layout.imageview);
Button btnClose = (Button)imgDialog.findViewById(R.id.btnIvClose);
ImageView ivPreview = (ImageView)imgDialog.findViewById(R.id.image1);
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
int imageWidth = factoryOptions.inDensity=400;
int imageHeight = factoryOptions.inDensity=500;
//thumbnail is selected coz if we select bm to enlarge it will give poor quality(bm is small sized image)
Bitmap Scaled = Bitmap.createScaledBitmap(CustomerRegistrationL0.thumbnail, imageWidth, imageHeight, true);
ivPreview.setImageBitmap(Scaled);
btnClose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
imgDialog.dismiss();
}
});
imgDialog.show();
// ListItem listItem = new ListItem();
//myItems.add(listItem);
myAdapter.notifyDataSetChanged();
//listviewattachment.setSelection(myAdapter.getCount()+1 );
}
});
holder.Delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
int tag = (Integer) view.getTag();
if (tag != (myItems.size() )) {
myItems.remove(tag);
Log.d("GCM", "Item removed from " + tag);
myAdapter.notifyDataSetChanged();
}
}
});
return convertView;
}
}
class ViewHolder {
ImageView image;
Button Delete;
}
}
This is because in your getView() you do not consider the position. You always set the bitmap to image2 which is the most recent bitmap: holder.image.setImageBitmap(image2);
I think you misunderstood how get view works. The getView() method is called for each item in the list when you notifyDataSetChanged().
The solution is to keep reference to the different bitmaps in a list (or elsewhere.. i am just giving a possible solution),
List<Bitmap> images = new ArrayList<>();
When you get the image from the result, add it to the images list.
image2 = Bitmap.createScaledBitmap(thumbnail, imageWidth , imageHeight, true);
images.add(image2)
Finally, setImageBitmap based on the position of the item during getView()
holder.image.setImageBitmap(images.get(position));
Related
I try set image into ImageView from gallery.
public class CollageCreateActivity extends AppCompatActivity {
private static final String TAG ="MyLogs" ;
Draw2d draw2d;
static final int GALLERY_REQUEST = 1;
private final int TAKE_PICTURE_CAMERA = 2;
private Uri mOutputFileUri;
ArrayList<CollageView> collageViewList1;
ArrayList<CollageView> collageViewList2;
float width;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage_creator);
collageViewList1 = new ArrayList<>();
collageViewList2 = new ArrayList<>();
Data data = new Data();
draw2d = new Draw2d(this);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_1);
if (frameLayout != null) {
frameLayout.addView(draw2d);
}
createCollage(data, layout);
if (layout != null) {
layout.bringToFront();
}
click();
}
public void createCollage(Data data, LinearLayout layout) {
ArrayList<Integer> list = new ArrayList<>();
list.add((int) data.getMap().get("mainLayout"));
list.add((int) data.getMap().get("firstLayout"));
list.add((int) data.getMap().get("secondLayout"));
final LinearLayout layout1 = new LinearLayout(this);
final LinearLayout layout2 = new LinearLayout(this);
LinearLayout[] massLay = {layout, layout1, layout2};
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1;
layout1.setLayoutParams(params);
layout2.setLayoutParams(params);
for (int i = 0; i < (int) data.getMap().get("layButt1"); i++) {
final Button button = new Button(this);
button.setLayoutParams(params);
button.setTextSize(50);
button.setId(i);
button.setPadding(16, 16, 16, 16);
button.setText(R.string.plus);
layout1.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout1.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
saveFromGallery();
layout1.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
collageViewList1.add(collageView);
}
});
}
for (int j = 0; j < (int) data.getMap().get("layButt2"); j++) {
Button button2 = new Button(this);
button2.setLayoutParams(params);
button2.setTextSize(50);
button2.setId(j);
button2.setPadding(16, 16, 16, 16);
button2.setText(R.string.plus);
layout2.addView(button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout2.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
layout2.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
width = layout2.getWidth();
collageViewList2.add(collageView);
}
});
}
for (int x = 0; x < list.size(); x++) {
if (list.get(x) == 0) {
massLay[x].setOrientation(LinearLayout.HORIZONTAL);
} else {
massLay[x].setOrientation(LinearLayout.VERTICAL);
}
}
layout.addView(layout1);
layout.addView(layout2);
}
public void click() {
Button button = (Button) findViewById(R.id.butt);
if (button != null) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < collageViewList1.size(); i++) {
collageViewList1.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap1 = Bitmap.createBitmap(collageViewList1.get(i).getDrawingCache());
collageViewList1.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap1);
draw2d.listX.add(collageViewList1.get(i).getX());
draw2d.listY.add(collageViewList1.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
for (int i = 0; i < collageViewList2.size(); i++) {
collageViewList2.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap2 = Bitmap.createBitmap(collageViewList2.get(i).getDrawingCache());
collageViewList2.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap2);
draw2d.listX.add(collageViewList2.get(i).getX() + width);
draw2d.listY.add(collageViewList2.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
draw2d.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(draw2d.getDrawingCache());
draw2d.setDrawingCacheEnabled(false);
draw2d.invalidate();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
InputStream imageStream = null;
CollageView collageView = new CollageView(CollageCreateActivity.this);
switch(requestCode) {
case GALLERY_REQUEST:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
try {
imageStream=getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap= BitmapFactory.decodeStream(imageStream);
Log.d(TAG, "сетим з галереї1");
collageView.setImageBitmap(bitmap);
Log.d(TAG, "сетим з галереї");
}
break;
case TAKE_PICTURE_CAMERA:
if (data != null) {
if (data.hasExtra("data")) {
Bitmap thumbnailBitmap = data.getParcelableExtra("data");
collageView.setImageBitmap(thumbnailBitmap);
}
} else {
collageView.setImageURI(mOutputFileUri);
}
}
}
private void saveFromGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
}
When i try set image from folder "drawrable" it's work, but if i try load image and set from gallery it's don't work, all i have "W/EGL_genymotion: eglSurfaceAttrib not implemented" in logs
In this case you will have to create a content provider which will use to share your local (Application's internal) file to the camera activity.when you try to take picture from camera
try this code:
Content provider class
public class MyFileContentProvider extends ContentProvider {
public static final Uri CONTENT_URI =
Uri.parse("content://com.example.camerademo/");
private static final HashMap<String, String> MIME_TYPES = new
HashMap<String, String>();
static {
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
}
#Override
public boolean onCreate() {
try {
File mFile = new File(getContext().getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
mFile.createNewFile();
}
getContext().getContentResolver().notifyChange(CONTENT_URI, null);
return (true);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public String getType(Uri uri) {
String path = uri.toString();
for (String extension : MIME_TYPES.keySet()) {
if (path.endsWith(extension)) {
return (MIME_TYPES.get(extension));
}
}
return (null);
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
File f = new File(getContext().getFilesDir(), "newImage.jpg");
if (f.exists()) {
return (ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_WRITE));
}
throw new FileNotFoundException(uri.getPath());
}
#Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
throw new RuntimeException("Operation not supported");
}
#Override
public Uri insert(Uri uri, ContentValues initialValues) {
throw new RuntimeException("Operation not supported");
}
#Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
#Override
public int delete(Uri uri, String where, String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
}
Home.java:
public class Home extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
Button button1;
ImageView imageView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
imageView1 = (ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(this);
}
public void onClick(View v) {
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available",
Toast.LENGTH_LONG).show();
} }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(Tag, "Receive the camera result");
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
File out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
imageView1.setImageBitmap(mBitmap);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
imageView1 = null;
}
}
hope it will help you,otherwise u will contact me my email
id:daminimehra28#gmail.com
i have used asynctask to insert images of sd card in listview. At around 229th image logcat shows OUT OF MEMORY error. I have used MediaStore.Images to retreive images from sd card into a cursor. Below is my code:
CursorLoader cursorLoader = new CursorLoader(MainActivity.this,
sourceUri, null, null, null, MediaStore.Images.Media.TITLE);
Cursor cursor = cursorLoader.loadInBackground();
new MyTask().execute(cursor);
MyTask extends AsyncTask. Here i have used do-while to retreive image using cursor and used for loop to correct the orientation of each image by using ExifInterface:
class MyTask extends AsyncTask<Cursor, Bitmap, Void> {
MyAdapter adap;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
adap = (MyAdapter) listviewPic.getAdapter();
}
#Override
protected Void doInBackground(Cursor... cursor) {
// TODO Auto-generated method stub
ThumbImage = new Bitmap[cursor[0].getCount()];
cursor[0].moveToFirst();
int count = 0;
do {
String _id = cursor[0].getString(cursor[0]
.getColumnIndex(MediaStore.Images.Media._ID));
fileURI = Uri.withAppendedPath(sourceUri, _id);
fileURI = Uri.parse("file://"
+ getRealPathFromUri(getApplicationContext(), fileURI));
file = new File(fileURI.getPath());
Log.d("Fahad", "Value of pathURi is = " + fileURI);
try {
ThumbImage[count] = ThumbnailUtils.extractThumbnail(
BitmapFactory.decodeFile(file.getAbsolutePath()), 100,
100);
} catch (OutOfMemoryError e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("Fahad", "Error at = " + cursor[0].getPosition());
}
++count;
} while (cursor[0].moveToNext());
for (int i = 0; i < ThumbImage.length; i++) {
try {
ExifInterface exif = new ExifInterface(file.getName());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
if (orientation == exif.ORIENTATION_ROTATE_90) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
Log.d("Fahad", "Changing orientation. ThumbImage id " + i);
ThumbImage[i] = Bitmap.createBitmap(ThumbImage[i], 0, 0,
ThumbImage[i].getWidth(),
ThumbImage[i].getHeight(), matrix, true);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
publishProgress(ThumbImage);
return null;
}
#Override
protected void onProgressUpdate(Bitmap... bmp) {
// TODO Auto-generated method stub
MyAdapter adapter = new MyAdapter(getApplicationContext(),
R.layout.row, null, bmp);
listviewPic.setAdapter(adapter);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
I have made custom adapter to display image:
class MyAdapter extends ArrayAdapter<String> {
Bitmap[] bmp = null;
Context context;
public MyAdapter(Context context, int resource, List<String> objects,
Bitmap[] bmp) {
super(context, resource, objects);
// TODO Auto-generated constructor stub
this.bmp = bmp;
this.context = context;
}
class MyViewHolder {
ImageView imageView;
public MyViewHolder(View v) { // TODO Auto-generated constructor
// stub
imageView = (ImageView) v.findViewById(R.id.imageView_row);
}
}
#Override
public int getCount() { // TODO Auto-generated method stub
return bmp.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("Fahad", "Inside getView");
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
LayoutInflater layout = (LayoutInflater) context
.getSystemService(LAYOUT_INFLATER_SERVICE);
row = layout.inflate(R.layout.row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
} else {
holder = (MyViewHolder) row.getTag();
}
holder.imageView.setBackground(new BitmapDrawable(getResources(),
bmp[position]));
return row;
}
}
When you decode all bitmap at once, OOM will occur.
It's good idea to load bitmap in getView.
(and you can use loader that have async and caching system like Piccaso)
Here is how I set up the list view and how I get the image by downloading it.
Some variable explanation :
The PostItem is the model object that contain the data for a listview item
The ImageLoader is the async task class to download the image by getting the image url from PostItem
The problem are , the ordering of the image in the listview is incorrect , for example, the image should appear in 1st is appear in both 1st , 4th, and if I scroll , the display pattern change as well.
Also, I find the image are download again if I scroll, even I have check the imageView whether has drawable
Thanks for helping.
====================================================
Here is how I generate the listview:
static class ViewHolderItem {
TextView name;
TextView date;
ImageView img;
TextView msg;
TextView count;
ImageView likeBtn;
ImageView commentBtn;
ImageView shareBtn;
}
private class MyPostAdapter extends ArrayAdapter<PostItem> {
#Override
public boolean isEnabled(int position) {
return false;
}
public MyPostAdapter(Context context, int resource, List<PostItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolderItem viewHolder;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.post_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.name = (TextView) v.findViewById(R.id.postName);
viewHolder.date = (TextView) v.findViewById(R.id.postDate);
viewHolder.img = (ImageView) v.findViewById(R.id.postImg);
viewHolder.msg = (TextView) v.findViewById(R.id.postMsg);
viewHolder.count = (TextView) v.findViewById(R.id.count);
viewHolder.likeBtn = (ImageView) v.findViewById(R.id.likeBtn);
viewHolder.commentBtn = (ImageView) v.findViewById(R.id.commentBtn);
viewHolder.shareBtn = (ImageView) v.findViewById(R.id.shareBtn);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolderItem) convertView.getTag();
}
final PostItem post = getItem(position);
if (post != null) {
viewHolder.name.setText(post.name);
try {
c.setTime(sdf.parse(post.createDate));
} catch (ParseException e) {
e.printStackTrace();
}
relative_date = DateUtils.getRelativeDateTimeString (ctx, c.getTimeInMillis() , DateUtils.MINUTE_IN_MILLIS,DateUtils.WEEK_IN_MILLIS, 0).toString();
viewHolder.date.setText(relative_date);
viewHolder.msg.setText(post.txtMsg);
viewHolder.count.setText(post.likeCount + " " + getString(R.string.pro_like) + " " + post.commentCount + " " + getString(R.string.reply));
if (post.isLike) {
viewHolder.likeBtn.setImageResource(R.drawable.like);
} else {
viewHolder.likeBtn.setImageResource(R.drawable.before_like);
}
if (!post.imageURL.equals("null") && viewHolder.img.getDrawable() == null ) {
new ImageLoader(ctx).execute(viewHolder.img,Constant.comment_imageFolder + post.imageURL);
} else {
viewHolder.img.setImageDrawable(null);
}
viewHolder.likeBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new APIManager("like", ctx, Constant.likeAPI + "/"
+ post.commentID + "/" + userID, jsonListener,
getResources().getString(R.string.update_data));
}
});
viewHolder.commentBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<PostItem> filterReplyList = new ArrayList<PostItem>();
Intent i = new Intent(ctx, ReplyActivity.class);
i.putExtra("commentID", post.commentID);
// get reply list
for (PostItem reply : replyItemList) {
if (reply.postID.equals(post.commentID)
|| reply.commentID.equals(post.commentID)) {
filterReplyList.add(reply);
}
}
i.putExtra("replyItemList", filterReplyList);
startActivityForResult(i, 0);
}
});
viewHolder.shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
String data = "date: " + post.createDate + "\nmsg:" + post.txtMsg;
sendIntent.putExtra(Intent.EXTRA_TEXT, data);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
}
return v;
}
}
And Here is the imageloader, take the imageview, url as input and put the bitmap in the imageview
public class ImageLoader extends AsyncTask<Object, Void, Bitmap> {
private static String TAG = "ImageLoader";
private InputStream input;
private ImageView view;
private ProgressBar loadingIcon;
private ListView myListView;
private String imageURL;
private Context ctx;
public ImageLoader(Context _ctx) {
ctx = _ctx;
}
#Override
protected Bitmap doInBackground(Object... params) {
try {
view = (ImageView) params[0];
// handle Chinese characters in file name
// String[] imgUrlArray = ((String) params[1]).split("/");
// String fileName = imgUrlArray[imgUrlArray.length - 1];
// String newfileName = URLEncoder.encode(fileName, "utf-8");
// imageURL = ((String) params[1]).replace(fileName, newfileName);
imageURL = ((String) params[1]);
if (params.length > 2 && (ProgressBar) params[2] != null)
loadingIcon = (ProgressBar) params[2];
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
final BitmapFactory.Options options = new BitmapFactory.Options();
BufferedInputStream bis = new BufferedInputStream(input, 4*1024);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte)current);
}
byte[] imageData = baf.toByteArray();
BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
options.inJustDecodeBounds = true;
options.inSampleSize = 2;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null && view != null) {
if (loadingIcon != null)
loadingIcon.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
view.setImageBitmap(result);
}
}
Updated code (implement volley library):
static class ViewHolderItem {
TextView name;
TextView date;
NetworkImageView img;
TextView msg;
TextView count;
ImageView likeBtn;
ImageView commentBtn;
ImageView shareBtn;
}
private class MyPostAdapter extends ArrayAdapter<PostItem> {
#Override
public boolean isEnabled(int position) {
return false;
}
public MyPostAdapter(Context context, int resource, List<PostItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolderItem viewHolder;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.post_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.name = (TextView) v.findViewById(R.id.postName);
viewHolder.date = (TextView) v.findViewById(R.id.postDate);
viewHolder.img = (NetworkImageView) v.findViewById(R.id.postImg);
viewHolder.msg = (TextView) v.findViewById(R.id.postMsg);
viewHolder.count = (TextView) v.findViewById(R.id.count);
viewHolder.likeBtn = (ImageView) v.findViewById(R.id.likeBtn);
viewHolder.commentBtn = (ImageView) v.findViewById(R.id.commentBtn);
viewHolder.shareBtn = (ImageView) v.findViewById(R.id.shareBtn);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolderItem) convertView.getTag();
}
final PostItem post = getItem(position);
if (post != null) {
viewHolder.name.setText(post.name);
try {
c.setTime(sdf.parse(post.createDate));
} catch (ParseException e) {
e.printStackTrace();
}
relative_date = DateUtils.getRelativeDateTimeString (ctx, c.getTimeInMillis() , DateUtils.MINUTE_IN_MILLIS,DateUtils.WEEK_IN_MILLIS, 0).toString();
viewHolder.date.setText(relative_date);
viewHolder.msg.setText(post.txtMsg);
viewHolder.count.setText(post.likeCount + " " + getString(R.string.pro_like) + " " + post.commentCount + " " + getString(R.string.reply));
if (post.isLike) {
viewHolder.likeBtn.setImageResource(R.drawable.like);
} else {
viewHolder.likeBtn.setImageResource(R.drawable.before_like);
}
if (!post.imageURL.equals("null")) {
viewHolder.img.setImageUrl(Constant.comment_imageFolder + post.imageURL, mImageLoader);
}
viewHolder.likeBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new APIManager("like", ctx, Constant.likeAPI + "/"
+ post.commentID + "/" + userID, jsonListener,
getResources().getString(R.string.update_data));
}
});
viewHolder.commentBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<PostItem> filterReplyList = new ArrayList<PostItem>();
Intent i = new Intent(ctx, ReplyActivity.class);
i.putExtra("commentID", post.commentID);
// get reply list
for (PostItem reply : replyItemList) {
if (reply.postID.equals(post.commentID)
|| reply.commentID.equals(post.commentID)) {
filterReplyList.add(reply);
}
}
i.putExtra("replyItemList", filterReplyList);
startActivityForResult(i, 0);
}
});
viewHolder.shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
String data = "date: " + post.createDate + "\nmsg:" + post.txtMsg;
sendIntent.putExtra(Intent.EXTRA_TEXT, data);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
}
return v;
}
For the task you are trying to do I would strongly recommend you to use Volley library.
Read from here
All you need to do is as below
mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache());
mImageView.setImageUrl(BASE_URL + item.image_url, mImageLoader);
Where mImageView is com.android.volley.NetworkImageView instead of a regular ImageView.
Volley takes care of maintaining the cache and the ordering of the images.
if you scroll the listview you will get back recycled convertview, it is not null but it has incorrect imageview. convertView is a view thats created and recycled through scrolling the list. this view makes GC be called less and also save memory for you. it first assigned by your earliest items of list. after you scroll the list, for example item one of list disappears and you see item 15 the convertView of item one is passed again to you. in this time it is not null and it holdes the reference of last imageview, the imageview of item 1.
so this is your problem, you skipped assigning correct imageview to your viewHolder.img.
Ok, what should you do?
the best thing you can do is create in memory cache that holds your downloaded imageview by their URLs as keys of the cache. in getview you check the cache, if it has your URL of current imageview position read from it and set it to viewHolder.img else download the image from internet.
Golden rule is:
ALWAYS OVERWRITE VIEWHOLDER VALUES WITH VALUES OF YOUR ITEM AT INDEX POSITON THAT
GETVIEW PASSES TO YOU
how to create cache? look at Example LRU cache at
http://developer.android.com/training/volley/request.html
and if you want you can also use volley library instead.
if (!post.imageURL.equals("null") && viewHolder.img.getDrawable() == null ) {
new ImageLoader(ctx).execute(viewHolder.img,Constant.comment_imageFolder + post.imageURL);
}
I am guessing that the problem lies here. What happens when you get a recycled view which already has an image from the previous view it was used for? That explains why the image appears in both 1st and 4th position and the change in the display pattern when you scroll.
Get the point? Remove the viewHolder.img.getDrawable() == null and try. See if that helps.
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);