Android Gallery Display two item - android

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

Related

Listview is setting text only for first position

Listview is setting the filename only in first position. Even though on clicking any positions of the listview it sets the filename for the first position only. Please let me know what changes i need to make so that filename will be set properly on clicked item only instead of first item always. Thanks in advance.
I have done same with in Recycle view I am sharing my project code with you
package com.deepak.myapplication;
public class DocumentActivity extends AppCompatActivity implements
View.OnClickListener {
ImageView toolbar_back;
TextView next, tvDocName;
RecyclerView listView;
ArrayList<Survey_vehiclepojo> mylist = new ArrayList();
My_document_adapter adapter;
private int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//toolbar_back = ( ImageView ) findViewById(R.id.toolbar_back);
//toolbar_back.setOnClickListener(this);
//next = ( TextView ) findViewById(R.id.next);
//next.setOnClickListener(this);
listView = findViewById(R.id.recycleView);
mylist.add(new Survey_vehiclepojo("Pay Slip", "file1"));
mylist.add(new Survey_vehiclepojo("Insurance", "file2"));
mylist.add(new Survey_vehiclepojo("NA Certificate", "file3"));
mylist.add(new Survey_vehiclepojo("NA 1", "file3"));
mylist.add(new Survey_vehiclepojo("NA 2", "file3"));
mylist.add(new Survey_vehiclepojo("NA 3", "file3"));
listView.setLayoutManager(new LinearLayoutManager(this));
adapter = new My_document_adapter(mylist, DocumentActivity.this);
listView.setAdapter(adapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
/*case R.id.toolbar_back:
finish();
break;
case R.id.next:
Intent n=new Intent(DocumentActivity.this, Loan_checklistActivity.class);
startActivity(n);
break;
}*/
}
}
public void Document(int pos) {
position = pos;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
selectedFile(data, requestCode);
}
private void selectedFile(Intent data, int position) {
String displayName = null;
if (data != null) {
Uri uri = data.getData();
String uriString = null;
if (uri != null) {
uriString = uri.toString();
}
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString != null) {
if (uriString.startsWith("content://")) {
try (Cursor cursor = DocumentActivity.this.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
tvDocName = findViewById(R.id.tvDocName);
Survey_vehiclepojo selected = mylist.get(position);
selected.setFile1(displayName);
//My_document_adapter.display(displayName,position);
adapter.notifyDataSetChanged();
}
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
tvDocName = findViewById(R.id.tvDocName);
Survey_vehiclepojo selected = mylist.get(position);
selected.setFile1(displayName);
//My_document_adapter.display(displayName,position);
adapter.notifyDataSetChanged();
}
}
}
}
This is Adapter
class My_document_adapter extends
RecyclerView.Adapter<My_document_adapter.ViewHolder>{
ArrayList<Survey_vehiclepojo> mylist;
DocumentActivity documentActivity;
public My_document_adapter(ArrayList<Survey_vehiclepojo> mylist,
DocumentActivity documentActivity) {
this.mylist = mylist;
this.documentActivity = documentActivity;
}
#NonNull
#Override
public My_document_adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
return new My_document_adapter.ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull My_document_adapter.ViewHolder holder,
final int position) {
holder.name.setText("name"+position);
holder.ivDocument.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Log.d("**Postion", "Postion: "+position);
documentActivity.Document(position);
} });
}
#Override
public int getItemCount() {
return mylist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final TextView tvDocName,name;
ImageView ivDocument;
public ViewHolder(#NonNull View view) {
super(view);
name = view.findViewById(R.id.tvName);
tvDocName = view.findViewById(R.id.tvDocName);
ivDocument = view.findViewById(R.id.ivDocument);
}
}
}
and my file is selecting see this screenshot

"Couldn't read row 0, col 0 from CursorWindow" when save image to database

I am making an application to save images. There is no problem when adding an image from the application's camera and the gallery image. But when I added a photo directly from the phone camera, it was not possible.
Error "Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it." encountered in the code line "int id = cursor.getInt (0);" of MainActivity java class.
How to solve ?
My code is below.
MainActivity class
public class MainActivity extends AppCompatActivity {
Button buttonAddItem;
public static Database database;
ListView listViewItem;
ArrayList<Item> itemArrayList;
ItemAdapter itemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonAddItem = (Button) findViewById(R.id.buttonAddItem);
listViewItem = (ListView) findViewById(R.id.listViewItem);
// Set ListView
itemArrayList = new ArrayList<>();
itemAdapter = new ItemAdapter(this, R.layout.line_item, itemArrayList);
listViewItem.setAdapter(itemAdapter);
// Create db and table
database = new Database(this, "Manage.sqlite", null, 1);
database.QueryData("CREATE TABLE IF NOT EXISTS Item(Id INTEGER PRIMARY KEY, Name VARCHAR(150)," +
"Description VARCHAR(250), Image TEXT)");
// Get all data to ListView
Cursor cursor = database.GetData("SELECT * FROM Item");
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String Name = cursor.getString(1);
String Description = cursor.getString(2);
String Image = cursor.getString(3);
itemArrayList.add(new Item(id, Name, Description, Image));
}
itemAdapter.notifyDataSetChanged();
buttonAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, AddItemActivity.class));
}
});
}
}
Database class
public class Database extends SQLiteOpenHelper {
public Database(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void QueryData(String sql) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.execSQL(sql);
}
public Cursor GetData(String sql) {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
return sqLiteDatabase.rawQuery(sql, null);
}
public void Insert_Item(String name, String desciption, String image) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String sql = "INSERT INTO Item VALUES(null, ?, ?, ?)";
SQLiteStatement sqLiteStatement = sqLiteDatabase.compileStatement(sql);
sqLiteStatement.clearBindings();
sqLiteStatement.bindString(1, name); // Begin index 0: id = null
sqLiteStatement.bindString(2, desciption);
sqLiteStatement.bindString(3, image);
sqLiteStatement.executeInsert();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
AddItemActivity class
public class AddItemActivity extends AppCompatActivity {
EditText editTextName, editTextDescription;
ImageButton imageButtonCamera, imageButtonFolder;
ImageView imageViewImage;
Button buttonAdd, buttonCancel;
int REQUEST_CODE_CAMERA = 123;
int REQUEST_CODE_FOLDER = 456;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
Mapping();
imageButtonCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
});
imageButtonFolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_FOLDER);
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Convert ImageView -> byte[]
BitmapDrawable bitmapDrawable = (BitmapDrawable) imageViewImage.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArray);
byte[] image = byteArray.toByteArray();
String str = Base64.encodeToString(image, Base64.DEFAULT);
// Insert Image to Database
MainActivity.database.Insert_Item(editTextName.getText().toString().trim(),
editTextDescription.getText().toString().trim(), str);
Toast.makeText(AddItemActivity.this, "Added.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AddItemActivity.this, MainActivity.class));
}
});
}
// Get image and export to ImageView
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK && data != null) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imageViewImage.setImageBitmap(bitmap);
}
if (requestCode == REQUEST_CODE_FOLDER && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageViewImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void Mapping() {
editTextName = (EditText) findViewById(R.id.editTextName);
editTextDescription = (EditText) findViewById(R.id.editTextDescription);
imageButtonCamera = (ImageButton) findViewById(R.id.imageButtonCamera);
imageButtonFolder = (ImageButton) findViewById(R.id.imageButtonFolder);
imageViewImage = (ImageView) findViewById(R.id.imageViewImage);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonCancel = (Button) findViewById(R.id.buttonCancel);
editTextName.requestFocus();
}
}
ItemAdapter class
public class ItemAdapter extends BaseAdapter {
private Context context;
private int layout;
List<Item> itemList;
public ItemAdapter(Context context, int layout, List<Item> itemList) {
this.context = context;
this.layout = layout;
this.itemList = itemList;
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
// Initialize view and mapping
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(layout, null);
viewHolder.textViewName = (TextView) convertView.findViewById(R.id.textViewName);
viewHolder.textViewDescription = (TextView) convertView.findViewById(R.id.textViewDescription);
viewHolder.imageViewLineItem = (ImageView) convertView.findViewById(R.id.imageViewLineItem);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Set items
Item item = itemList.get(position);
viewHolder.textViewName.setText(item.getName());
viewHolder.textViewDescription.setText(item.getDescription());
// Convert byte[] -> bitmap
try{
byte[] image = Base64.decode(item.getImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
viewHolder.imageViewLineItem.setImageBitmap(bitmap);
} catch (Exception e) {
e.getMessage();
}
return convertView;
}
private class ViewHolder {
ImageView imageViewLineItem;
TextView textViewName, textViewDescription;
}
}

Can't load images from phone gallery via intent and set it on gridview

i am new to android and want to load images from phone gallery via intent and want to display the list item on gridView.
But when i load the gallery after selection the image is not displaying.
Activity
private static final int CODE = 0;
public GridView gridView;
public Uri selectedImageUri;
ImageAdapter imageAdapter;
...
gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
imageAdapter = new ImageAdapter(this);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Toast.makeText(MainActivity.this, "" + position + "",
Toast.LENGTH_LONG).show();
}
});
Button loadImageButton = (Button) findViewById(R.id.load_image_button);
loadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
Picture"), CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == CODE && resultCode == RESULT_OK && intent != null) {
selectedImageUri = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
objImageAdapter.addToList(picturePath);
cursor.close();
imageView = (ImageView)findViewById(R.id.image_view);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Adapter class
public class ImageAdapter extends BaseAdapter {
public ImageView imageView;
private Context vContext;
ArrayList<String> arrayList = new ArrayList<String>();
public ImageAdapter(Context context) {
this.vContext = context;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
public void addToList(String stringPath) {
this.arrayList.add(stringPath);
this.notifyDataSetChanged();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imageView = new ImageView(vContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(2, 2, 2, 2);
} else {
imageView = (ImageView) convertView;
}
String path = arrayList.get(position);
Bitmap bitmap = BitmapFactory.decodeFile(path);
imageView.setImageBitmap(bitmap);
return imageView;

Android Horizontal Gridview item overlap each other

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

CustomAdapter is not displaying ArrayList Item: ImageView

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

Categories

Resources