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
Related
I have a listview with a textview and imageview in each row, and am trying to figure out how to enlarge my images when clicking on them. The user takes an image from their gallery and stores them in a database with a name. They are maps of resorts/hotels for the purpose of delivering.
This is how everything is laid out:
I'm trying to get my app to where I can click on an ImageView, or simply just the listview itself, and have the image enlarged in the center of the screen. If not enlarged in the center of the screen, I wouldn't even mind opening the enlarged image in a new activity. Either way is fine, I would just like to be able to read the maps, so doing something with pinch-to-zoom would be great! I get the images from the user's gallery and store them in a list, and ask them for a name for the hotel/resort. Then I save the information to a database and display it in a listview. I crop the images down to fit them in the listview as thumbnails, but I would like to expand them back out upon being clicked for easy readability. Any help would be greatly appreciated! My goal is to have it look like the answer to this question, but couldn't figure out how to optimize it into my code.
My adapter class is as follows:
public class dataAdapter extends ArrayAdapter<Hotel> {
Context context;
ArrayList<Hotel> mHotel;
public dataAdapter(Context context, ArrayList<Hotel> hotel)
{
super(context, R.layout.listhotels, hotel);
this.context = context;
this.mHotel = hotel;
}
public class Holder
{
TextView nameFV;
ImageView pic;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Hotel data = getItem(position);
Holder viewHolder;
if (convertView == null)
{
viewHolder = new Holder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listhotels, parent, false);
viewHolder.nameFV = (TextView) convertView.findViewById(R.id.txtViewer);
viewHolder.pic = (ImageView) convertView.findViewById(R.id.imgView);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (Holder) convertView.getTag();
}
viewHolder.nameFV.setText(data.getFName());
viewHolder.pic.setImageBitmap(convertToBitmap(data.getImage()));
return convertView;
}
private Bitmap convertToBitmap(byte[] b)
{
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
}
My code to display the list of hotels:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.display_hotels);
lv = (ListView) findViewById(R.id.list1);
db = new DatabaseHandler(this);
pic = (ImageView) findViewById(R.id.pic);
fname = (EditText) findViewById(R.id.txt1);
final ArrayList<Hotel> hotels = new ArrayList<>(db.getAllHotels());
data = new dataAdapter(this, hotels);
data.sort(new Comparator<Hotel>()
{
#Override
public int compare(Hotel arg0, Hotel arg1)
{
return arg0.getFName().compareTo(arg1.getFName());
}
});
data.notifyDataSetChanged();
lv.setAdapter(data);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(getApplicationContext(), display_full_image.class);
startActivity(i);
}
});
}
And my main activity:
public class MapsMainActivity extends AppCompatActivity {
private EditText fname;
private ImageView pic;
private DatabaseHandler db;
private String f_name;
private ListView lv;
private dataAdapter data;
private Hotel dataModel;
private Bitmap bp;
private byte[] photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_main);
db = new DatabaseHandler(this);
lv = (ListView) findViewById(R.id.list1);
pic = (ImageView) findViewById(R.id.pic);
fname = (EditText) findViewById(R.id.txt1);
}
public void buttonClicked(View v)
{
int id = v.getId();
switch(id)
{
case R.id.save:
if (fname.getText().toString().trim().equals(""))
{
Toast.makeText(getApplicationContext(), "Name edit text is empty, Enter name", Toast.LENGTH_LONG).show();
}
else
{
addHotel();
}
break;
case R.id.display:
showRecords();
Intent intent = new Intent(getApplicationContext(), display_hotels.class);
startActivity(intent);
break;
case R.id.pic:
selectImage();
break;
}
}
public void selectImage()
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode)
{
case 2:
if(resultCode == RESULT_OK)
{
Uri chosenImage = data.getData();
if(chosenImage != null)
{
bp = decodeUri(chosenImage, 400);
pic.setImageBitmap(bp);
}
}
}
}
protected Bitmap decodeUri(Uri selectedImage, int REQUIRED_SIZE)
{
try
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
{
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private byte[] profileImage(Bitmap b)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 0, bos);
return bos.toByteArray();
}
private void getValues()
{
f_name = fname.getText().toString();
photo = profileImage(bp);
}
private void addHotel()
{
getValues();
db.addHotels(new Hotel(f_name, photo));
Toast.makeText(getApplicationContext(), "Saved successfully", Toast.LENGTH_SHORT).show();
}
private void showRecords()
{
final ArrayList<Hotel> hotels = new ArrayList<>(db.getAllHotels());
data = new dataAdapter(this, hotels);
data.notifyDataSetChanged();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
dataModel = hotels.get(position);
Toast.makeText(getApplicationContext(), String.valueOf(dataModel.getID()), Toast.LENGTH_SHORT).show();
}
});
}
}
Thank you in advance to anyone who can help me. I would greatly appreciate it. This is for a final project for my Mobile App Development class that is due in 2 days, and I'm really close to finishing it. Thank you for your time.
use this getView()
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Hotel data = getItem(position);
Holder viewHolder;
if (convertView == null)
{
viewHolder = new Holder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listhotels, parent, false);
viewHolder.nameFV = (TextView) convertView.findViewById(R.id.txtViewer);
viewHolder.pic = (ImageView) convertView.findViewById(R.id.imgView);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (Holder) convertView.getTag();
}
viewHolder.nameFV.setText(data.getFName());
viewHolder.pic.setImageBitmap(convertToBitmap(data.getImage()));
viewHolder.pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog settingsDialog = new Dialog(context);
settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(500, 500);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
ImageView iv = new ImageView(context);
iv.setLayoutParams(lp);
iv.setImageResource(R.drawable.img3);
//use in your case iv.setImageBitmap(convertToBitmap(data.getImage()));
settingsDialog.addContentView(iv,lp);
settingsDialog.show();
}
});
return convertView;
}
just pass the imgeData as extra in intent when you start new Activity to display full image. and in FullImageActivit getIntent extra to get the image data and display it in an imageView.
and if you want to enable pinch zoom there a librabry to handle it
check this
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;
}
}
Hi everyone I am making capture image display on horizontal gridview But I have got some problem . The gridview item contains image , but items overlap each other How can I do it here is my code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.zzbothtime.MainActivity" >
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="#+id/seatLegendLayout" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/linearLayout_gridtableLayout"
android:layout_width="900dp"
android:layout_height="100dp"
android:orientation="horizontal" >
<GridView
android:id="#+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_margin="4dp"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="0dp"
android:numColumns="auto_fit"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="horizontal"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp" >
</GridView>
</LinearLayout>
</FrameLayout>
</HorizontalScrollView>
<Button
android:id="#+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignLeft="#+id/horizontalScrollView1"
android:layout_alignParentBottom="true"
android:layout_marginBottom="33dp"
android:onClick="btnAddOnClick"
android:text="Ekle" />
MainActivityCode
public class MainActivity extends Activity {
#SuppressWarnings("deprecation")
private ArrayList<MyImage> images;
private ImageAdapter imageAdapter;
private GridView 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.popupchoose);
dialog.setTitle("Alert Dialog View");
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 = (GridView) findViewById(R.id.gridView1);
listView.setAdapter(imageAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, 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.popupchoose);
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();
}
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 = (GridView) findViewById(R.id.gridView1);
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 = (GridView) findViewById(R.id.gridView1);
listView.setAdapter(imageAdapter);
// listView.setSelection(imageAdapter.getCount()-1);
imageAdapter.notifyDataSetChanged();
}
}
}
}
myAdapter
public class ImageAdapter extends ArrayAdapter<MyImage>{
private static class ViewHolder {
ImageView imgIcon;
TextView description;
}
public ImageAdapter(Context context, ArrayList<MyImage> images) {
super(context,0, images);
// TODO Auto-generated constructor stub
}
#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.activity_gallery_item, parent, false);
/*
viewHolder.description =
(TextView) convertView.findViewById(R.id.item_img_infor);
*/
viewHolder.imgIcon =(ImageView) convertView.findViewById(R.id.id_index_gallery_item_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Get the data item for this position
MyImage image = getItem(position);
final int THUMBSIZE = 300;
// 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.FIT_XY);
// Return the completed view to render on screen
return convertView;
}
}
MyImageClass
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;
}
}
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.
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.