Uploading images from GalleryView to PHP Server - android

I am new to android development. I am trying to send android-gallery images to the server. I take a photo from the camera and display the taken images in a gallery view android. Now i need to send those images to the server -database. I have no idea ow to do this. hear is my code up to now.
<Gallery
android:id="#+id/gallery"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#55000000"
android:gravity="center_vertical"
android:spacing="16dp" />
MainActivity
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
Button b;
public static int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.btnSelectPhoto);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this, ReadSDCard()));
g.setOnItemSelectedListener(this);
}
private void selectImage() {
// TODO Auto-generated method stub
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final String dir = (android.os.Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolderrr/");
File f = new File(dir);
f.mkdir();
count++;
Uri uriSavedImage = Uri.fromFile(new File(dir + count
+ ".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
/* mSwitcher.setImageResource(mImageIds[position]); */
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT));
return i;
}
private List<String> ReadSDCard() {
List<String> tFileList = new ArrayList<String>();
// It have to be matched with the directory in SDCard
File f = new File("/storage/sdcard0/Pictures/picFolderrr/");
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
/* It's assumed that all file in the path are in supported type */
tFileList.add(file.getPath());
}
return tFileList;
}
/* private ImageSwitcher mSwitcher; */
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private List<String> FileList;
public ImageAdapter(Context c, List<String> fList) {
mContext = c;
FileList = fList;
}
public int getCount() {
return FileList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
Bitmap bm = BitmapFactory.decodeFile(FileList.get(position)
.toString());
Bitmap re = Bitmap.createScaledBitmap(bm, 60, 60, false);
i.setImageBitmap(re);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
}
}

This code uploads data (images, mp3′s, text files etc.) to HTTP server
Uploading files to HTTP server using POST on Android.

Related

Android View Pager deleting images from folder not refreshing

Whenever i delete my Image from my ViewPager. Then sometimes next Image will be deleted.or sometime's no image delete.
where i am wrong i dont know.
My GallaryActivity
public class GalleryActivity extends AppCompatActivity implements View.OnClickListener {
ImageButton imgBtnDelete;
TextView tvImageCount;
ViewPager galleryViewPager;
GalleryAdapter adapter;
private static String filePath = "";
public int mPosition = 0;
// File Code
public File mDirectory;
File[] imageList;
ArrayList<Integer> mTotalImages = new ArrayList<>();
ArrayList<String> mFilePaths = new ArrayList<>();
Uri[] mUrls;
String[] mFiles, mFileNames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the Status bar...Write Before setContentView()
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_gallery);
imgBtnDelete = (ImageButton) findViewById(R.id.imgBtnDelete);
imgBtnDelete.setOnClickListener(this);
// File Code
mDirectory = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
imageList = mDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
int imgLength = (imageList == null) ? 0 : imageList.length;
if (imgLength > 0) {
mFiles = new String[imgLength];
// add imgLength here for set Total Images in TextView
for (int k = 0; k < imageList.length; k++) {
mTotalImages.add(imgLength);
filePath = imageList[k].getAbsolutePath();
mFilePaths.add(filePath);
}
mFileNames = new String[imgLength];
tvImageCount.setVisibility(View.VISIBLE);
tvImageCount.setText(1 + "/" + mTotalImages.size());
mUrls = new Uri[imgLength];
int i, j = 0;
for (i = imgLength - 1; i >= 0; i--) {
mFiles[j] = imageList[i].getAbsolutePath();
mFileNames[j] = imageList[i].getName();
j++;
}
galleryViewPager = (ViewPager) findViewById(R.id.galleryViewPager);
adapter = new GalleryAdapter(this, mFiles);
galleryViewPager.setAdapter(adapter);
galleryViewPager.setOnPageChangeListener(pageChangeListener);
} else {
tvImageCount.setVisibility(View.INVISIBLE);
Toast.makeText(this, "Please capture some images from App!", Toast.LENGTH_SHORT).show();
}
}
OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mPosition = position;
tvImageCount.setText((position + 1) + "/" + mTotalImages.size());
Toast.makeText(GalleryActivity.this, "mPosition is : " + mPosition, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void openAlert() {
new AlertDialog.Builder(this)
.setTitle("Delete Image")
.setMessage("Are you sure you want to delete this Image?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
DeleteImage();
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.setCancelable(true)
.show();
}
my DeleteImage()
private void DeleteImage() {
File file = new File(mFilePaths.get(mPosition));
boolean deleted = file.delete();
if (deleted) {
mFilePaths.remove(mPosition);
if (mFilePaths.size() == 0) {
tvImageCount.setVisibility(View.INVISIBLE);
}
if (mFilePaths.size() != 0 && mFilePaths.size() != 1) {
adapter.notifyDataSetChanged();
galleryViewPager.setCurrentItem(mPosition + 1);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgBtnDelete:
if (mDirectory.exists() && mDirectory != null && mFilePaths.size() != 0) {
openAlert();
} else {
Toast.makeText(this, "No Images to Delete!", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
and following is my GallaryAdapter of Viewpager
public class GalleryAdapter extends PagerAdapter {
private Context mContext;
private String[] mFiles;
public GalleryAdapter(Context mContext, String[] mFiles) {
this.mContext = mContext;
this.mFiles = mFiles;
}
#Override
public int getCount() {
return mFiles.length;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.gallary_viewpager_item, container, false);
ImageView mImageView = (ImageView) itemView.findViewById(R.id.imgViewCenterGallery);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(mFiles[position], options);
mImageView.setImageBitmap(bitmap);
container.addView(itemView);
return itemView;
}
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Try this way
if (imgLength > 0) {
mFiles = new String[imgLength];
mFileNames = new String[imgLength];
mUrls = new Uri[imgLength];
int j=0;
for (int i = imgLength-1; i >= 0; i--) {
mFiles[j] = imageList[i].getAbsolutePath();
mFileNames[j] = imageList[i].getName();
j++;
Toast.makeText(this, "Image Name - " + Arrays.toString(mFileNames), Toast.LENGTH_SHORT).show();
galleryViewPager = (ViewPager) findViewById(R.id.galleryViewPager);
adapter = new GallerySlideImageAdapter(this, mFiles, mFileNames);
galleryViewPager.setAdapter(adapter);
}
} else {
Toast.makeText(this, "Please capture some images from App !", Toast.LENGTH_SHORT).show();
}
Sort your file list as per latest to older datetime and bind files in adapter.
File[] files = directory.listFiles(); //your files object
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});

Android Gallery Display two item

Hello I made android gallery . I added capture image camera or gallery but I show only one image in display How can show two gallery item in gallery For example that is
here is my gallery code xml
<Gallery
android:id="#+id/main_list_view"
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_alignLeft="#+id/btnAdd"
android:layout_below="#+id/btnAdd"
android:layout_marginTop="28dp"
android:cacheColorHint="#color/deepPurple1"/>
And My MainActivity
#SuppressLint("NewApi")
public class MainActivity extends Activity {
private ArrayList<MyImage> images;
private ImageAdapter imageAdapter;
private Gallery listView;
private Uri mCapturedImageURI;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
private Handler handler;
Dialog dialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Alert Dialog View");
// Construct the data source
images = new ArrayList<MyImage>();
// Create the adapter to convert the array to views
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setAdapter(imageAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Button btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnChoosePath)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeTakePhoto();
}
});
// show dialog on screen
dialog.show();
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
imageAdapter.remove(images.remove(position));
return false;
}
});
}
public void btnAddOnClick(View view) {
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Alert Dialog View");
Button btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnChoosePath)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeTakePhoto();
}
});
// show dialog on screen
dialog.show();
}
/**
* take a photo
*/
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
/**
* to gallery
*/
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE &&
resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.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();
MyImage image = new MyImage();
image.setTitle("Test");
image.setDescription(" add list view");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
images.add(image);
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setSpacing(-20);
listView.setAdapter(imageAdapter);
// listView.setSelection(imageAdapter.getCount()-1);
imageAdapter.notifyDataSetChanged();
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor =
managedQuery(mCapturedImageURI, projection, null,
null, null);
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
MyImage image = new MyImage();
image.setTitle("Test");
image.setDescription("list view");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
images.add(image);
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setSpacing(-20);
listView.setAdapter(imageAdapter);
// listView.setSelection(imageAdapter.getCount()-1);
imageAdapter.notifyDataSetChanged();
}
}
}
And My Adapter
public class ImageAdapter extends ArrayAdapter<MyImage>{
/**
* applying ViewHolder pattern to speed up ListView, smoother and faster
* item loading by caching view in A ViewHolder object
*/
private static class ViewHolder {
ImageView imgIcon;
TextView description;
}
public ImageAdapter(Context context, ArrayList<MyImage> images) {
super(context, 0, images);
}
#Override public View getView(int position, View convertView,
ViewGroup parent) {
// view lookup cache stored in tag
ViewHolder viewHolder;
// Check if an existing view is being reused, otherwise inflate the
// item view
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_image, parent, false);
/*
viewHolder.description =
(TextView) convertView.findViewById(R.id.item_img_infor);
*/
viewHolder.imgIcon =
(ImageView) convertView.findViewById(R.id.item_img_icon);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Get the data item for this position
MyImage image = getItem(position);
// set description text
// viewHolder.description.setText(image.toString());
// set image icon
final int THUMBSIZE = 100;
// viewHolder.imgIcon.setImageURI(Uri.fromFile(new File(image
// .getPath())));
viewHolder.imgIcon.setImageBitmap(ThumbnailUtils
.extractThumbnail(BitmapFactory.decodeFile(image.getPath()),
THUMBSIZE, THUMBSIZE));
viewHolder.imgIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
viewHolder.imgIcon.setBackgroundResource(R.drawable.ios_retina_toggle_frame);
// Return the completed view to render on screen
return convertView;
}
}
And My image Class
public class MyImage {
private String title, description, path;
private Calendar datetime;
private long datetimeLong;
protected SimpleDateFormat df = new SimpleDateFormat("MMMM d, yy h:mm");
public String getTitle() { return title; }
public Calendar getDatetime() { return datetime; }
public void setDatetime(long datetimeLong) {
this.datetimeLong = datetimeLong;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(datetimeLong);
this.datetime = cal;
}
public void setDatetime(Calendar datetime) { this.datetime = datetime; }
public String getDescription() { return description; }
public void setTitle(String title) { this.title = title; }
public long getDatetimeLong() { return datetimeLong; }
public void setDescription(String description) {
this.description = description;
}
public void setPath(String path) { this.path = path; }
public String getPath() { return path; }
#Override public String toString() {
return "Title:" + title + " " + df.format(datetime.getTime()) +
"\nDescription:" + description + "\nPath:" + path;
}
}

CustomAdapter is not displaying ArrayList Item: ImageView

In my CheckOutMemo.class I can set any title and content as shown in picture.
MainActivity.class then retrieves this title and content without any problems and displays a custom row. Like in this picture:
Title = Header
Content = bodyText
But the problem is: When I take a picture - I can't display it on my custom row. (That little dog in my MainActivity is there by default).
I don't know what the problem is.
I can preview my captured image as an Bitmap in my CheckOutMemo.class's contentView. I can successfully save it to my External Storage. But I can't display it on my MainActivity.
MAINACTIVITY.CLASS
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {
public ImageView view;
private String[] mPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private static final int REQUEST_CODE_PERMISSION = 5;
CustomAdapter customAdapter;
ListView listView;
Intent intent;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customAdapter = new CustomAdapter();
listView = (ListView) findViewById(R.id.myListView);
listView.setAdapter(customAdapter);
listView.setOnItemLongClickListener(this);
listView.setOnItemClickListener(this);
view = (ImageView) this.findViewById(R.id.imageIcon);
if (ActivityCompat.checkSelfPermission(MainActivity.this, mPermission[0])
!= MockPackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(MainActivity.this, mPermission[1])
!= MockPackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
mPermission, REQUEST_CODE_PERMISSION);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Memo memo = customAdapter.getItem(position);
intent = new Intent(getApplicationContext(), CheckOutMemo.class);
intent.putExtra("header", memo.header);
intent.putExtra("bodyText", memo.bodyText);
intent.putExtra("position", position);
// launches edit request and saving existing item.
startActivityForResult(intent, CheckOutMemo.EDIT_REQUEST_CODE);
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Confirm Delete");
alertDialogBuilder.setMessage("Delete memo?");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
customAdapter.delete(position);
customAdapter.notifyDataSetChanged();
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
public void addNewNote(View view) {
Intent intent = new Intent(getApplicationContext(), CheckOutMemo.class);
//Adding new listItem to the ArrayList.
startActivityForResult(intent, CheckOutMemo.ADD_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == CheckOutMemo.ADD_REQUEST_CODE) {
String header = data.getStringExtra("header");
String bodyText = data.getStringExtra("bodyText");
if (getIntent().hasExtra("byteArray")) {
Bitmap bitmap = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
view.setImageBitmap(bitmap);
}
Memo memo = new Memo(header, bodyText, view);
customAdapter.add(memo);
customAdapter.notifyDataSetChanged();
}
if (requestCode == CheckOutMemo.EDIT_REQUEST_CODE) {
int position = data.getIntExtra("position", 0);
Memo memo = customAdapter.getItem(position);
memo.header = data.getStringExtra("header");
memo.bodyText = data.getStringExtra("bodyText");
customAdapter.notifyDataSetChanged();
}
}
}
CHECKOUTMEMO.CLASS
public class CheckOutMemo extends AppCompatActivity {
public static final int ADD_REQUEST_CODE = 1;
public static final int EDIT_REQUEST_CODE = 2;
public static final int REQUEST_IMAGE_CAPTURE = 1337;
public String fileName;
public Bitmap bitmap;
private int position;
EditText editableTitle;
EditText editableContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
editableTitle = (EditText) findViewById(R.id.editHeader);
editableContent = (EditText) findViewById(R.id.editBodyText);
editableTitle.setText(intent.getStringExtra("header"));
editableContent.setText(intent.getStringExtra("bodyText"));
checkIfUserChangedOrWroteAnyText();
//Declaring keyword and default position.
position = intent.getIntExtra("position", 0);
}
public void capturePhoto(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
loadImageFromFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void loadImageFromFile() throws IOException {
ImageView view = (ImageView)this.findViewById(R.id.primeImage);
view.setVisibility(View.VISIBLE);
int targetW = view.getWidth();
int targetH = view.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fileName, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bitmap = BitmapFactory.decodeFile(fileName, bmOptions);
view.setImageBitmap(bitmap);
}
public void createImageFromBitmap(){
if(bitmap!=null) {
Intent i = new Intent(this, MainActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);
} else {
Toast.makeText(CheckOutMemo.this, "Bitmap is null", Toast.LENGTH_SHORT).show();
}
}
public void onSaveClick(View view){
String editableContentString = editableContent.getText().toString();
String editableTitleString = editableTitle.getText().toString();
if(TextUtils.isEmpty(editableContentString) && TextUtils.isEmpty(editableTitleString)) {
finish();
Toast.makeText(CheckOutMemo.this, "No content to save, note discarded", Toast.LENGTH_SHORT).show();
}
else {
if ((TextUtils.isEmpty(editableTitleString))) {
editableTitleString.equals(editableContentString);
Intent intent = new Intent();
createImageFromBitmap();
intent.putExtra("header", editableContent.getText().toString());
intent.putExtra("position", position);
//Sending userInput back to MainActivity.
setResult(Activity.RESULT_OK, intent);
finish();
} else {
Intent intent = new Intent();
createImageFromBitmap();
intent.putExtra("header", editableTitle.getText().toString());
intent.putExtra("bodyText", editableContent.getText().toString());
intent.putExtra("position", position);
//Sending userInput back to MainActivity.
setResult(Activity.RESULT_OK, intent);
finish();
}
}
}
public void cancelButtonClickedAfterEdit() {
Button button = (Button) findViewById(R.id.bigCancelButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
openDialogFragment(v);
}
});
}
public File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String folder_main = "DNote";
String path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString() + File.separator + folder_main;
File storageDir = new File(path);
if (!storageDir.exists()) {
storageDir.mkdir();
}
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
fileName = image.getAbsolutePath();
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{image.getPath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
// Log.i(TAG, "Scanned " + path);
}
});
return image;
}
#Override
public void onBackPressed() {
openDialogFragment(null);
}
public void onCancelClick(View view){
finish();
}
}
CUSTOMADAPTER.CLASS
public class CustomAdapter extends BaseAdapter {
ArrayList<Memo> memos = new ArrayList<>();
public void add(Memo memo) {
this.memos.add(memo);
}
public void delete(int position) {
memos.remove(position);
}
#Override
public Memo getItem(int position) {
return memos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getCount() {
return memos.size();
}
class MyViewHolder {
public TextView header, bodyText;
public ImageView imageView;
public MyViewHolder(View view) {
header = (TextView) view.findViewById(R.id.header);
bodyText = (TextView) view.findViewById(R.id.bodyText);
imageView = (ImageView) view.findViewById(R.id.primeImage);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
MyViewHolder viewHolder;
if(null == convertView){
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.custom_row, parent, false);
viewHolder = new MyViewHolder(convertView);
viewHolder.header.setTag(position);
convertView.setTag(viewHolder);
}
else{
viewHolder = (MyViewHolder) convertView.getTag();
}
Memo memo = getItem(position);
viewHolder.header.setText(memo.header);
viewHolder.bodyText.setText(memo.bodyText);
CheckOutMemo checkOutMemo = new CheckOutMemo();;
if(checkOutMemo.bitmap!=null) {
viewHolder.imageView.setImageBitmap(checkOutMemo.bitmap);
}
return convertView;
}
}
MEMO.CLASS
public class Memo {
public String header, bodyText;
public ImageView imageView;
public Memo(String header, String bodyText, ImageView imageView){
this.header = header;
this.bodyText = bodyText;
this.imageView = imageView;
}
}
I've been working on this for over 2 months every day. Any help would be appreciated!!
Ok here is the minimal viable solution to get what you want. I just fixed it enough so an image is returned to your main activity. The rest of your issues are for you to fix. The only class I haven't touched is your Memo class. But that being said I highly recommend you update it to store a String with the path to the image instead of an ImageView.
But if for you what you want to do here are your files edited to work:
First custom adapter:
I've changed the lines where you get the image from memo, to check it's image view for a bitmap drawable and transfer that bitmap to the row's image view. There was no need to instantiate that CheckoutMemo activity here.
public class CustomAdapter extends BaseAdapter {
ArrayList<Memo> memos = new ArrayList<>();
public void add(Memo memo) {
this.memos.add(memo);
}
public void delete(int position) {
memos.remove(position);
}
#Override
public Memo getItem(int position) {
return memos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getCount() {
return memos.size();
}
class MyViewHolder {
public TextView header, bodyText;
public ImageView imageView;
public MyViewHolder(View view) {
header = (TextView) view.findViewById(R.id.header);
bodyText = (TextView) view.findViewById(R.id.bodyText);
imageView = (ImageView) view.findViewById(R.id.primeImage);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
MyViewHolder viewHolder;
if(null == convertView){
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.custom_row, parent, false);
viewHolder = new MyViewHolder(convertView);
viewHolder.header.setTag(position);
convertView.setTag(viewHolder);
}
else{
viewHolder = (MyViewHolder) convertView.getTag();
}
Memo memo = getItem(position);
viewHolder.header.setText(memo.header);
viewHolder.bodyText.setText(memo.bodyText);
if (memo.imageView.getDrawable() instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) memo.imageView.getDrawable();
viewHolder.imageView.setImageBitmap(bitmapDrawable.getBitmap());
}
return convertView;
}
}
Next your CheckoutMemo:
I've changed how your setResult methods work. I've also deleted the method createImageFromBitmap. It was problematic, and also caused confusion. That one was a doozy. The createImageFromBitmap method was creating another MainActivity... confused me for a bit why onActivityResult wasn't being called. It wasn't being called because you were creating another activity =/
Anyways in your intent you create with your results, you'll notice I am also adding the file path string to the image created. So that main activity can use it to get the image!
public class CheckOutMemo extends AppCompatActivity {
public static final int ADD_REQUEST_CODE = 1;
public static final int EDIT_REQUEST_CODE = 2;
public static final int REQUEST_IMAGE_CAPTURE = 1337;
public String fileName;
public Bitmap bitmap;
private int position;
EditText editableTitle;
EditText editableContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
editableTitle = (EditText) findViewById(R.id.editHeader);
editableContent = (EditText) findViewById(R.id.editBodyText);
editableTitle.setText(intent.getStringExtra("header"));
editableContent.setText(intent.getStringExtra("bodyText"));
//checkIfUserChangedOrWroteAnyText();
//Declaring keyword and default position.
position = intent.getIntExtra("position", 0);
}
public void capturePhoto(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
loadImageFromFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void loadImageFromFile() throws IOException {
ImageView view = (ImageView)this.findViewById(R.id.primeImage);
view.setVisibility(View.VISIBLE);
int targetW = view.getWidth();
int targetH = view.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fileName, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bitmap = BitmapFactory.decodeFile(fileName, bmOptions);
view.setImageBitmap(bitmap);
}
public void onSaveClick(View view){
String editableContentString = editableContent.getText().toString();
String editableTitleString = editableTitle.getText().toString();
if(TextUtils.isEmpty(editableContentString) && TextUtils.isEmpty(editableTitleString)) {
finish();
Toast.makeText(CheckOutMemo.this, "No content to save, note discarded", Toast.LENGTH_SHORT).show();
}
else {
if ((TextUtils.isEmpty(editableTitleString))) {
editableTitleString.equals(editableContentString);
Intent intent = new Intent();
//createImageFromBitmap();
intent.putExtra("header", editableContent.getText().toString());
intent.putExtra("position", position);
intent.putExtra("photo", fileName);
//Sending userInput back to MainActivity.
setResult(AppCompatActivity.RESULT_OK, intent);
finish();
} else {
Intent intent = new Intent();
//createImageFromBitmap();
intent.putExtra("header", editableTitle.getText().toString());
intent.putExtra("bodyText", editableContent.getText().toString());
intent.putExtra("photo", fileName);
intent.putExtra("position", position);
//Sending userInput back to MainActivity.
setResult(AppCompatActivity.RESULT_OK, intent);
finish();
}
}
}
public void cancelButtonClickedAfterEdit() {
Button button = (Button) findViewById(R.id.bigCancelButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//openDialogFragment(v);
}
});
}
public File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String folder_main = "DNote";
String path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString() + File.separator + folder_main;
File storageDir = new File(path);
if (!storageDir.exists()) {
storageDir.mkdir();
}
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
fileName = image.getAbsolutePath();
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{image.getPath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
// Log.i(TAG, "Scanned " + path);
}
});
return image;
}
#Override
public void onBackPressed() {
//openDialogFragment(null);
}
public void onCancelClick(View view){
finish();
}
}
Finally your MainActivity:
In on activity result if the photo path exists. Then I am adding it to the memo object's image view to later be retrieved by the adapters ImageView. This can be upgraded a bit hence my comments above to be a little less convoluted by just passing the file path ;)
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener,
AdapterView.OnItemClickListener {
public ImageView view;
private String[] mPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private static final int REQUEST_CODE_PERMISSION = 5;
CustomAdapter customAdapter;
ListView listView;
Intent intent;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customAdapter = new CustomAdapter();
listView = (ListView) findViewById(R.id.myListView);
listView.setAdapter(customAdapter);
listView.setOnItemLongClickListener(this);
listView.setOnItemClickListener(this);
//view = (ImageView) this.findViewById(R.id.imageIcon);
if (ActivityCompat.checkSelfPermission(MainActivity.this, mPermission[0])
!= MockPackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(MainActivity.this, mPermission[1])
!= MockPackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
mPermission, REQUEST_CODE_PERMISSION);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Memo memo = customAdapter.getItem(position);
intent = new Intent(getApplicationContext(), CheckOutMemo.class);
intent.putExtra("header", memo.header);
intent.putExtra("bodyText", memo.bodyText);
intent.putExtra("position", position);
// launches edit request and saving existing item.
startActivityForResult(intent, CheckOutMemo.EDIT_REQUEST_CODE);
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Confirm Delete");
alertDialogBuilder.setMessage("Delete memo?");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
customAdapter.delete(position);
customAdapter.notifyDataSetChanged();
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
public void addNewNote(View view) {
Intent intent = new Intent(getApplicationContext(), CheckOutMemo.class);
//Adding new listItem to the ArrayList.
startActivityForResult(intent, CheckOutMemo.ADD_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == CheckOutMemo.ADD_REQUEST_CODE) {
String header = data.getStringExtra("header");
String bodyText = data.getStringExtra("bodyText");
File photo = new File(data.getStringExtra("photo"));
ImageView view = new ImageView(this);
if (photo.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(photo.getAbsolutePath());
view.setImageBitmap(myBitmap);
}
Memo memo = new Memo(header, bodyText, view);
customAdapter.add(memo);
customAdapter.notifyDataSetChanged();
}
if (requestCode == CheckOutMemo.EDIT_REQUEST_CODE) {
int position = data.getIntExtra("position", 0);
Memo memo = customAdapter.getItem(position);
memo.header = data.getStringExtra("header");
memo.bodyText = data.getStringExtra("bodyText");
File photo = new File(data.getStringExtra("photo"));
if (photo.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(photo.getAbsolutePath());
memo.imageView.setImageBitmap(myBitmap);
}
customAdapter.notifyDataSetChanged();
}
}
}
All in all, running this I can now see images in the notes created!
Keep at your project here. Two months is a good commitment. You are doing great, keep up the good work. There are more things you can improve in there! Just keep massaging it, and never give up.
You rock =)
I can get you the working project I've created to test this if needed.

dynamically created imageview in gridlayout not working

I want to set captured image to dynamically created imageview in same gridlayout but it creates a new grid layout and sets the captured image to the new gridview.
This is my mainactivity.java file
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
GridView gridView;
ArrayList<Damage_Item> gridArray = new ArrayList<Damage_Item>();
CustomAdapter_back customGridAdapter;
GridLayout mContainerView;
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
ImageView dynamic_imageview;
LinearLayout dynamic_linearview;
String image1;
ArrayList<String> arrayList_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainerView = (GridLayout)findViewById(R.id.describedamage_gridview) ;
//gridArray.add(new Item(homeIcon,"Home"));
gridView = (GridView) findViewById(R.id.gridview1);
Button add = (Button)findViewById(R.id.button1);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inflateImageRow();
}
});
}
public void selectImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 140, 150, true);
Bitmap dest = Bitmap.createBitmap(resized.getWidth(), resized.getHeight(), Bitmap.Config.ARGB_8888);
ByteArrayOutputStream byteArrayOutputStream1 = new ByteArrayOutputStream();
dest.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream1);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system
Canvas canvas = new Canvas(dest); //bmp is the bitmap to dwaw into
Paint paint = new Paint();
canvas.drawBitmap(resized, 0f, 0f, null);
paint.setColor(Color.BLACK);
canvas.drawRect(1, 145, 100, 130, paint);
paint.setColor(getResources().getColor(R.color.orange));
paint.setTextSize(10);
paint.setFakeBoldText(true);
paint.setTextAlign(Paint.Align.LEFT);
float height = paint.measureText("yY");
canvas.drawText(dateTime, 5f, height+130f, paint);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
dest.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String image1 = Base64.encodeToString(byteArray, Base64.DEFAULT);
//arrayList_image.add(image1);
BitmapDrawable background = new BitmapDrawable(dest);
//holder.imageItem.setBackground(background);
Damage_Item damage_item = new Damage_Item();
damage_item.setTemp_image(dest);
gridArray.add(damage_item);
customGridAdapter = new CustomAdapter_back(MainActivity.this, gridArray);
gridView.setAdapter(customGridAdapter);
/*gridView.setAdapter(customGridAdapter);
gridView.setOnItemClickListener(MainActivity.this)*/;
}
int count;
private void inflateImageRow() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.dynamic_row, null);
dynamic_imageview = (ImageButton)rowView.findViewById(R.id.dynamic_imageview);
dynamic_linearview=(LinearLayout)rowView.findViewById(R.id.dynamic_linear);
dynamic_imageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//image_flagdynamic_right = true;
selectImage();
}
});
count= mContainerView.getChildCount()-1;
dynamic_imageview.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
int parent=((View) v.getParent()).getId();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Whould you like to delete this image?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int index = ((View) v.getParent()).getId() + 2;
try {
mContainerView.removeView((View) v.getParent());
// arrayList_image.remove(((View) v.getParent()).getId());
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "delete", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
return false;
}
});
mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
}
this is my adapter file CustomAdapter_back.java
public class CustomAdapter_back extends BaseAdapter {
private Context context;
private ArrayList<Damage_Item> Damage_Item;
LayoutInflater inflater;
ImageView button;
public CustomAdapter_back(Context context, ArrayList<Damage_Item> Damage_Item) {
this.context = context;
this.Damage_Item = Damage_Item;
inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return Damage_Item.size();
}
#Override
public Object getItem(int position) {
return Damage_Item.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_grid, null);
button = (ImageView) convertView.findViewById(R.id.imageview);
}
else
{
}
button.setImageBitmap(Damage_Item.get(position).getTemp_image());
return convertView;
}
}
My activity_manin.xml file
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:padding="11dp"
android:text="Add" />
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/describedamage_gridview"
android:columnCount="2"
android:layout_below="#+id/button1"
android:rowCount="1"
android:orientation="horizontal">
<GridView
android:id="#+id/gridview1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="2"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</GridLayout>
row_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/imageview"
android:layout_width="170dp"
android:layout_height="150dp"
android:background="#drawable/camera" />
</LinearLayout>
First it seems you not using holder pattern in your CustomAdapter_back also as Fllo noticed you don't need to remove manually the views.
add this function to your adapter
public void setData(ArrayList<Damage_Item> data)
{
this.Damage_Item = Damage_Item;
notifyDataSetChanged();
}
and call this function from the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Whould you like to delete this image?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//get deleted item index according to your logic
int index = ((View) v.getParent()).getId() + 2;
gridArray.remove(index);
customGridAdapter.setData(gridArray);
Toast.makeText(getApplicationContext(), "delete", Toast.LENGTH_LONG).show();
}
});
in on activityResult you have a 2 lines of code:
customGridAdapter = new CustomAdapter_back(MainActivity.this, gridArray);
gridView.setAdapter(customGridAdapter);
so every single time when you are adding a new image you are recreating the adapter.
Just move adapter declaration to onCreate with empty list.
Add method
public void addItem(Damage_Item item){
this.Damage_Item.add(item);
this.notifyDataSetChange();
}
to your adapter and trigger it instead of creating adapter and setting new inside your onCaptureImageResult.
And for god sake, naming convention. Your code is unreadable
Try this
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
GridView gridView;
ArrayList<Damage_Item> gridArray = new ArrayList<Damage_Item>();
CustomAdapter_back customGridAdapter;
GridLayout mContainerView;
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
ImageView dynamic_imageview;
LinearLayout dynamic_linearview;
String image1;
ArrayList<String> arrayList_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainerView = (GridLayout)findViewById(R.id.describedamage_gridview) ;
//gridArray.add(new Item(homeIcon,"Home"));
gridView = (GridView) findViewById(R.id.gridview1);
Button add = (Button)findViewById(R.id.button1);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inflateImageRow();
}
});
customGridAdapter = new CustomAdapter_back(MainActivity.this, gridArray);
gridView.setAdapter(customGridAdapter);
}
public void selectImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 140, 150, true);
Bitmap dest = Bitmap.createBitmap(resized.getWidth(), resized.getHeight(), Bitmap.Config.ARGB_8888);
ByteArrayOutputStream byteArrayOutputStream1 = new ByteArrayOutputStream();
dest.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream1);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system
Canvas canvas = new Canvas(dest); //bmp is the bitmap to dwaw into
Paint paint = new Paint();
canvas.drawBitmap(resized, 0f, 0f, null);
paint.setColor(Color.BLACK);
canvas.drawRect(1, 145, 100, 130, paint);
paint.setColor(getResources().getColor(R.color.orange));
paint.setTextSize(10);
paint.setFakeBoldText(true);
paint.setTextAlign(Paint.Align.LEFT);
float height = paint.measureText("yY");
canvas.drawText(dateTime, 5f, height+130f, paint);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
dest.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String image1 = Base64.encodeToString(byteArray, Base64.DEFAULT);
//arrayList_image.add(image1);
BitmapDrawable background = new BitmapDrawable(dest);
//holder.imageItem.setBackground(background);
Damage_Item damage_item = new Damage_Item();
damage_item.setTemp_image(dest);
gridArray.add(damage_item);
customGridAdapter.notifyDataSetChanged();
/*gridView.setAdapter(customGridAdapter);
gridView.setOnItemClickListener(MainActivity.this)*/;
}
int count;
private void inflateImageRow() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.dynamic_row, null);
dynamic_imageview = (ImageButton)rowView.findViewById(R.id.dynamic_imageview);
dynamic_linearview=(LinearLayout)rowView.findViewById(R.id.dynamic_linear);
dynamic_imageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//image_flagdynamic_right = true;
selectImage();
}
});
count= mContainerView.getChildCount()-1;
dynamic_imageview.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
int parent=((View) v.getParent()).getId();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Whould you like to delete this image?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int index = ((View) v.getParent()).getId() + 2;
try {
mContainerView.removeView((View) v.getParent());
// arrayList_image.remove(((View) v.getParent()).getId());
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "delete", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
return false;
}
});
mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
}
Try changing your xml by removing the GridView as the gridlayout should change the size of the image automatically.
Another non-recommended solution would be to use the screen dimensions for sizing your image

Store the images picked from gallery android

I want to click the "btnchooserphoto" button to pick the images from gallery and
I can do it now, but I want to store these images and when I click "btnchooserphoto" button again I can add another images and the images I picked are still there. But now the ImageLoader will re-init everytime... log is below
W/ImageLoader(4503): Try to initialize ImageLoader which had already been initialized before. To re-init ImageLoader with new configuration call ImageLoader.destroy() at first.
Can anybody know how to fix it? thanks!!!
These are my code...
Album_Main
public class Album_Main extends Activity {
private Button mbtn,mbtn_choosephoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.album_setting);
mbtn_choosephoto=(Button)findViewById(R.id.btnchooserphoto);
mbtn_choosephoto.setOnClickListener(mbtnchoosephotoonclick);
}
private View.OnClickListener mbtnchoosephotoonclick = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent it = new Intent();
it.setClass(Album_Main.this, Album_Setting.class);
startActivity(it);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Album_Setting
public class Album_Setting extends Activity {
GridView gridGallery;
Handler handler;
GalleryAdapter adapter;
ImageView imgSinglePick;
Button btnGalleryPick;
Button btnGalleryPickMul;
Button mbtngoback;
String action;
ViewSwitcher viewSwitcher;
ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.album_setting_main);
initImageLoader();
init();
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapter(getApplicationContext(), imageLoader);
adapter.setMultiplePick(false);
gridGallery.setAdapter(adapter);
viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
viewSwitcher.setDisplayedChild(1);
mbtngoback=(Button)findViewById(R.id.btngoback);
mbtngoback.setOnClickListener(mbtngobackonclick);
btnGalleryPickMul = (Button) findViewById(R.id.btnGalleryPickMul);
btnGalleryPickMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
}
});
}
private View.OnClickListener mbtngobackonclick = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
storeimage(dataT);
}
}
private void storeimage(ArrayList<CustomGallery> dataT){
viewSwitcher.setDisplayedChild(0);
adapter.addAll(dataT);
}
}
CustomGalleryActivity
public class CustomGalleryActivity extends Activity {
GridView gridGallery;
Handler handler;
GalleryAdapter adapter;
ImageView imgNoMedia;
Button btnGalleryOk;
String action;
private ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
action = getIntent().getAction();
if (action == null) {
finish();
}
initImageLoader();
init();
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(),
CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY).cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
getBaseContext())
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.memoryCache(new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
} catch (Exception e) {
}
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapter(getApplicationContext(), imageLoader);
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,
true, true);
gridGallery.setOnScrollListener(listener);
if (action.equalsIgnoreCase(Action.ACTION_MULTIPLE_PICK)) {
findViewById(R.id.llBottomContainer).setVisibility(View.VISIBLE);
gridGallery.setOnItemClickListener(mItemMulClickListener);
adapter.setMultiplePick(true);
} else if (action.equalsIgnoreCase(Action.ACTION_PICK)) {
findViewById(R.id.llBottomContainer).setVisibility(View.GONE);
gridGallery.setOnItemClickListener(mItemSingleClickListener);
adapter.setMultiplePick(false);
}
gridGallery.setAdapter(adapter);
imgNoMedia = (ImageView) findViewById(R.id.imgNoMedia);
btnGalleryOk = (Button) findViewById(R.id.btnGalleryOk);
btnGalleryOk.setOnClickListener(mOkClickListener);
new Thread() {
#Override
public void run() {
Looper.prepare();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addAll(getGalleryPhotos());
checkImageStatus();
}
});
Looper.loop();
};
}.start();
}
private void checkImageStatus() {
if (adapter.isEmpty()) {
imgNoMedia.setVisibility(View.VISIBLE);
} else {
imgNoMedia.setVisibility(View.GONE);
}
}
View.OnClickListener mOkClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<CustomGallery> selected = adapter.getSelected();
String[] allPath = new String[selected.size()];
for (int i = 0; i < allPath.length; i++) {
allPath[i] = selected.get(i).sdcardPath;
}
Intent data = new Intent().putExtra("all_path", allPath);
setResult(RESULT_OK, data);
finish();
}
};
AdapterView.OnItemClickListener mItemMulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
adapter.changeSelection(v, position);
}
};
AdapterView.OnItemClickListener mItemSingleClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomGallery item = adapter.getItem(position);
Intent data = new Intent().putExtra("single_path", item.sdcardPath);
setResult(RESULT_OK, data);
finish();
}
};
private ArrayList<CustomGallery> getGalleryPhotos() {
ArrayList<CustomGallery> galleryList = new ArrayList<CustomGallery>();
try {
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);
if (imagecursor != null && imagecursor.getCount() > 0) {
while (imagecursor.moveToNext()) {
CustomGallery item = new CustomGallery();
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
item.sdcardPath = imagecursor.getString(dataColumnIndex);
galleryList.add(item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// show newest photo at beginning of the list
Collections.reverse(galleryList);
return galleryList;
}
}

Categories

Resources