CustomAdapter is not displaying ArrayList Item: ImageView - android

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.

Related

how to add display images and sort from newest uploaded

I have fork from github this source code
https://github.com/quocnguyenvan/food-sqlite-demo
I need some help here
How to add display image in full screen? If we are in food list and click an image, the image will show at full screen
And one more, how to add sorting file? So the newest uploaded will be at the top of the list, thanks for helping me, i need this for my office
======================================================
here is my code
FoodList class
public class FoodList extends AppCompatActivity {
GridView gridView;
ArrayList<Food> list;
FoodListAdapter adapter = null;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_list_activity);
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new FoodListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
// get all data from sqlite
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Food(name, price, image, id));
}
adapter.notifyDataSetChanged();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
CharSequence[] items = {"Preview", "Download"};
AlertDialog.Builder dialog = new AlertDialog.Builder(FoodList.this);
dialog.setTitle("Choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent i = new Intent(getApplicationContext(), ImageDisplay.class);
i.putExtra("id", position);
startActivity(i);
Toast.makeText(getApplicationContext(),"You click on " + position, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"you download " + position, Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
//return true;
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(FoodList.this);
dialog.setTitle("Choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
// update
Cursor c = MainActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while (c.moveToNext()){
arrID.add(c.getInt(0));
}
// show dialog update at here
showDialogUpdate(FoodList.this, arrID.get(position));
} else {
// delete
Cursor c = MainActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while (c.moveToNext()){
arrID.add(c.getInt(0));
}
showDialogDelete(arrID.get(position));
}
}
});
dialog.show();
return true;
}
});
}
ImageView imageViewFood;
private void showDialogUpdate(Activity activity, final int position){
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.update_food_activity);
dialog.setTitle("Update");
imageViewFood = (ImageView) dialog.findViewById(R.id.imageViewFood);
final EditText edtName = (EditText) dialog.findViewById(R.id.edtName);
final EditText edtPrice = (EditText) dialog.findViewById(R.id.edtPrice);
Button btnUpdate = (Button) dialog.findViewById(R.id.btnUpdate);
// set width for dialog
int width = (int) (activity.getResources().getDisplayMetrics().widthPixels * 0.95);
// set height for dialog
int height = (int) (activity.getResources().getDisplayMetrics().heightPixels * 0.7);
dialog.getWindow().setLayout(width, height);
dialog.show();
imageViewFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// request photo library
ActivityCompat.requestPermissions(
FoodList.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
888
);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
MainActivity.sqLiteHelper.updateData(
edtName.getText().toString().trim(),
edtPrice.getText().toString().trim(),
MainActivity.imageViewToByte(imageViewFood),
position
);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Update successfully!!!",Toast.LENGTH_SHORT).show();
}
catch (Exception error) {
Log.e("Update error", error.getMessage());
}
updateFoodList();
}
});
}
private void showDialogDelete(final int idFood){
final AlertDialog.Builder dialogDelete = new AlertDialog.Builder(FoodList.this);
dialogDelete.setTitle("Warning!!");
dialogDelete.setMessage("Are you sure you want to this delete?");
dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
MainActivity.sqLiteHelper.deleteData(idFood);
Toast.makeText(getApplicationContext(), "Delete successfully!!!",Toast.LENGTH_SHORT).show();
} catch (Exception e){
Log.e("error", e.getMessage());
}
updateFoodList();
}
});
dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialogDelete.show();
}
private void updateFoodList(){
// get all data from sqlite
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Food(name, price, image, id));
}
adapter.notifyDataSetChanged();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 888){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 888);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 888 && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageViewFood.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
i want to display image in fullscreen when user click on it
here is my DisplayImage class
public class ImageDisplay extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageView imageViewFood = (ImageView) findViewById(R.id.fullimage);
imageViewFood.setImageResource(position);
}
}
is it correct code ? please help me, thanks

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;
}
}

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

Adding Bitmaps into an Array, then set it in ImageView inside GridView

Since I was getting out of memory error when a picture taken with the phones camera was added into the imageView inside GridView, I tried to rescale it - as a bitmap (This worked just fine). I now want to add the images into an Array from which the items are going to load in the GridViews ImageView.
What I tried :
public class ImageGridAdapter extends BaseAdapter {
public Uri imageUri;
public String picture;
ArrayList<Bitmap> bitmapArrayList = new ArrayList<Bitmap>();
private Context mContext;
public ImageGridAdapter(Context c) {
this.mContext = c;
}
#Override
public int getCount() {
return bitmapArrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
try {
imageUri = PictureGroupActivity.selectedImage;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(imageUri, filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picture = cursor.getString(columnIndex);
cursor.close();
} catch (Exception e) {}
bitmapArrayList.add(BitmapScaled(picture, 100, 100));
Toast.makeText(mContext.getApplicationContext(), "bitmapArrayList je: " + bitmapArrayList, Toast.LENGTH_SHORT).show();
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(bitmapArrayList.get(position));
return imageView;
}
private Bitmap BitmapScaled(String picturePath, int width, int height) {
BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, sizeOptions);
sizeOptions.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(picturePath, sizeOptions);
}
}
Setting the adapter to GridView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picture_group_activity_layout);
GridView gridView = (GridView) findViewById(R.id.picture_group_gridView);
gridView.setAdapter(new ImageGridAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(PictureGroupActivity.this, "You clicked " + position, Toast.LENGTH_SHORT).show();
}
});
}
Choosing the Image:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
String picturePath = loadPath();
if (id == R.id.addPictureFolder) {
if (picturePath != null) {
Toast.makeText(this, "Click the plus button to add pictures", Toast.LENGTH_LONG).show();
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
} else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
} else if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
gridView = (GridView)findViewById(R.id.picture_group_gridView);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
selectedImage = data.getData();
Intent restart = getIntent();
finish();
startActivity(restart);
}
}
This does like nothing, no error, no Image is displayed, nothing.
What am I doing wrong? (If I'm not anywhere near the answer, how do you do it?)
Thank you in advance!
It seems you are not setting arraylist in adapter from activity. bitmapArrayList size is zero thats why gridview not showing anything. Please check the bitmapArrayList size.

Uploading images from GalleryView to PHP Server

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.

Categories

Resources