Image is displaying in only first item in gridview. Below is my GridImageActivity where i am taking the image either from gallery or capturing it from camera. After taking the image, image is setting in only first item of gridview.
How can I display the image in different items of gridview. Any help is appreciated. Thanks in advance.
public class GridImage extends AppCompatActivity {
GridView gv_gridimg;
private Context context = this;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_image);
gv_gridimg = findViewById(R.id.gv_gridimg);
GridImgAdapter gridImgAdapter = new GridImgAdapter(this);
gv_gridimg.setAdapter(gridImgAdapter);
gv_gridimg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// gridImgAdapter.notifyDataSetChanged(); //to clear all the data that is assigned
String[] galleryPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(context, galleryPermissions)) {
pickImageFromGallery();
} else {
EasyPermissions.requestPermissions(activity, "Access for storage", 101, galleryPermissions);
}
}
});
}
private void pickImageFromGallery() {
final CharSequence[] options = {"Take photo", "Choose from gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take photo")) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from gallery")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
ImageView iv_gridimg = (ImageView) gv_gridimg.findViewById(R.id.iv_gridimg);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null) {
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
iv_gridimg.setImageBitmap(selectedImage);
}
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = new String[]{MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturesPath = cursor.getString(columnIndex);
iv_gridimg.setImageBitmap(BitmapFactory.decodeFile(picturesPath));
cursor.close();
}
}
}
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
This is my adapter class
public class GridImgAdapter extends BaseAdapter {
private Context context;
public GridImgAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return 4;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gv_gridimg;
gv_gridimg = layoutInflater.inflate(R.layout.item_grid_img,null);
ImageView iv_gridimg = (ImageView) gv_gridimg.findViewById(R.id.iv_gridimg);
return gv_gridimg;
}
}
This is my main xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity.GridImage">
<GridView
android:id="#+id/gv_gridimg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:numColumns="2"/>
</RelativeLayout>
This is my item xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iv_gridimg"
android:layout_width="200dp"
android:layout_height="200dp"
android:padding="40dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#drawable/ic_camera_black_24dp"/>
</RelativeLayout>
You can't use findViewById always because it's always return first item in list.
You have to hold your bitmaps in adapter with positions for display.
public class GridImgAdapter extends BaseAdapter {
HashMap<Integer, Bitmap> images = new HashMap<>();
public void putImage(int position, Bitmap bitmap) {
images.put(position, bitmap);
notifyDataSetChanged()
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gv_gridimg;
gv_gridimg = layoutInflater.inflate(R.layout.item_grid_img,null);
ImageView iv_gridimg = (ImageView) gv_gridimg.findViewById(R.id.iv_gridimg);
if(images.get(position)!=null) iv_gridimg.setImageBitmap(images.get(position);
return gv_gridimg;
}
...
declare variable for current selected position in grid
int selectedPosition;
gv_gridimg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedPosition=position;
OnActivityReult:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null) {
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
//call adapter putImage method
}
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = new String[]{MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturesPath = cursor.getString(columnIndex);
//call adapter putImage method
}
}
}
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
In item.xml change height and width of parent layout to wrap_content because you are set as match_parent so, it's shows in whole screen.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iv_gridimg"
android:layout_width="200dp"
android:layout_height="200dp"
android:padding="40dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#drawable/ic_camera_black_24dp"/>
</RelativeLayout>
I hope this can help you!
Thank You.
Your adapter doesn't contain any data to show, you should add an ArrayList of data to constructor of the adapter like this:
public GridImgAdapter(Context context, ArrayList images) {
this.context = context;
this.images = images;
}
then in the getView() method you need to set the data to your ImageView like this:
ImageView iv_gridimg = (ImageView) gv_gridimg.findViewById(R.id.iv_gridimg);
iv_gridimg.setImageResource(images.get(position));
Related
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;
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;
}
}
My question is how do i select multiple images from gallery and dynamically add ImageViews for each photo? I have tried multiple methods but i just cant get the one that fits my situation. As i am a newbie i cant figure out myself how to do this.
What i tried:
btn=(Button)findViewById(R.id.imageButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
}
});
--
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
}else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
I have a working image selector but only for 1 picture:
Can i somehow change this so it can handle multiple images and add ImageViews programmaticaly?
private static int RESULT_LOAD_IMAGE = 1;
btn=(Button)findViewById(R.id.imageButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
if (ContextCompat.checkSelfPermission(MainComp_News_Edit.this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainComp_News_Edit.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(MainComp_News_Edit.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
}
}
});
--
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try{
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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
catch(Exception e) {
e.printStackTrace();
}
}
Translations:
Selecteer een foto = Select a photo.
Verwijder Foto = Delete photo.
Call that Function when you get the uri of the images you selected
Add following lines in build graddle files
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.support:cardview-v7:23.1.1'
recyclerView_myc
<com.pacakage.AutofitRecyclerView
android:id="#+id/recyclerView_myc"
android:layout_marginTop="3dp"
android:background="#color/AppBackGroundColor"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:layout_marginLeft="#dimen/activity_vertical_margin"
android:layout_marginStart="#dimen/activity_vertical_margin"
android:layout_marginRight="1dp"
android:layout_marginEnd="1dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/view" />
previewMediaInGrid Function
private ArrayList<String> mArrayUri; //uri of images you selected
private void previewMediaInGrid(ArrayList<String> mArrayUri) {
recyclerView= (AutofitRecyclerView) findViewById(R.id.recyclerView_myc); //recyclerView_myc will be autofitrecyelrview
recyclerView.setVisibility(View.VISIBLE);
vidPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.GONE);
mAdapter = new GridAdapterUpload(mArrayUri, getApplicationContext());
recyclerView.setAdapter(mAdapter);
}
GridAdapterUpload
public class GridAdapterUpload extends RecyclerView.Adapter<GridAdapterUpload.ViewHolder> {
private ArrayList<String> mItems;
private MyClickListener myClickListener;
private Context mContext;
private String TAG="GridAdapter";
//private ProgressBar mProgressBar;
public GridAdapterUpload(ArrayList<String> items,Context mContext) {
this.mItems = items;
this.mContext= mContext;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.galary_item, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
viewHolder.mProgbar.setVisibility(View.VISIBLE);
viewHolder.mProgbar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(mContext,
R.color.colorButton), android.graphics.PorterDuff.Mode.MULTIPLY);
Picasso.with(mContext)
.load(new File(mItems.get(position)))
.into(viewHolder.imgThumbnail, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
viewHolder.mProgbar.setVisibility(View.INVISIBLE);
}
#Override
public void onError() {
viewHolder.mProgbar.setVisibility(View.INVISIBLE);
}
});
viewHolder.imgThumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imgThumbnail;
public ProgressBar mProgbar;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView)itemView.findViewById(R.id.img_thumbnail);
mProgbar = (ProgressBar) itemView.findViewById(R.id.progressBar);
// itemView.setOnClickListener(this);
}
public void onClick(View v) {
myClickListener.onItemClick(getLayoutPosition(), v);
}
}
public interface MyClickListener {
void onItemClick(int position, View v);
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
}
gallery_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:padding="2dp"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="0dp"
card_view:cardElevation="0.01dp">
<RelativeLayout
android:id="#+id/layout_root"
android:layout_width="match_parent"
android:background="#color/AppUploadCamreaPictureColor"
android:layout_height="100dp">
<ImageView
android:id="#+id/img_thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="invisible"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
AutofitRecyclerView
public class AutofitRecyclerView extends RecyclerView {
private GridLayoutManager manager;
private int columnWidth = -1;
public AutofitRecyclerView(Context context) {
super(context);
init(context, null);
}
public AutofitRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public AutofitRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
if (attrs != null) {
int[] attrsArray = {
android.R.attr.columnWidth
};
TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
columnWidth = array.getDimensionPixelSize(0, -1);
array.recycle();
}
manager = new GridLayoutManager(getContext(),3);
setLayoutManager(manager);
}
#Override
protected void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(widthSpec, heightSpec);
if (columnWidth > 0) {
int spanCount = Math.max(1, getMeasuredWidth() / columnWidth);
manager.setSpanCount(spanCount);
}
}
}
Since I was getting out of memory error when a picture taken with the phones camera was added into the imageView inside GridView, I tried to rescale it - as a bitmap (This worked just fine). I now want to add the images into an Array from which the items are going to load in the GridViews ImageView.
What I tried :
public class ImageGridAdapter extends BaseAdapter {
public Uri imageUri;
public String picture;
ArrayList<Bitmap> bitmapArrayList = new ArrayList<Bitmap>();
private Context mContext;
public ImageGridAdapter(Context c) {
this.mContext = c;
}
#Override
public int getCount() {
return bitmapArrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
try {
imageUri = PictureGroupActivity.selectedImage;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(imageUri, filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picture = cursor.getString(columnIndex);
cursor.close();
} catch (Exception e) {}
bitmapArrayList.add(BitmapScaled(picture, 100, 100));
Toast.makeText(mContext.getApplicationContext(), "bitmapArrayList je: " + bitmapArrayList, Toast.LENGTH_SHORT).show();
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(bitmapArrayList.get(position));
return imageView;
}
private Bitmap BitmapScaled(String picturePath, int width, int height) {
BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, sizeOptions);
sizeOptions.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(picturePath, sizeOptions);
}
}
Setting the adapter to GridView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picture_group_activity_layout);
GridView gridView = (GridView) findViewById(R.id.picture_group_gridView);
gridView.setAdapter(new ImageGridAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(PictureGroupActivity.this, "You clicked " + position, Toast.LENGTH_SHORT).show();
}
});
}
Choosing the Image:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
String picturePath = loadPath();
if (id == R.id.addPictureFolder) {
if (picturePath != null) {
Toast.makeText(this, "Click the plus button to add pictures", Toast.LENGTH_LONG).show();
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
} else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
} else if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
gridView = (GridView)findViewById(R.id.picture_group_gridView);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
selectedImage = data.getData();
Intent restart = getIntent();
finish();
startActivity(restart);
}
}
This does like nothing, no error, no Image is displayed, nothing.
What am I doing wrong? (If I'm not anywhere near the answer, how do you do it?)
Thank you in advance!
It seems you are not setting arraylist in adapter from activity. bitmapArrayList size is zero thats why gridview not showing anything. Please check the bitmapArrayList size.
I have a listview which contains two buttons, when the button is clicked it should open a gallery. I tried to implement it and followed some post on stackoverflow but still I'm not able to get exact result. How to open the gallery using buttons in listViewlistview?
I have tried the following and used the adapter class as inner class
MyAdapter adapter=new MyAdapter(getApplicationContext(),videoFileList);
im my adapter class
private class MyAdapter extends BaseAdapter
{
ImageView picture;
Button imgbtn,videobtn;
ImageButton play;
Context context;
private LayoutInflater inflater;
private ArrayList<String> videolisty;
public MyAdapter(Context context,ArrayList<String> videolistx)
{
this.context=context;
inflater = LayoutInflater.from(context);
videolisty = videolistx;
Field[] arrayOfField = R.raw.class.getFields();
for (int i = 0; ; i++)
{
if (i >= arrayOfField.length)
{
System.out.println("-----------videolist------" +videoFileList);
return;
}
System.out.println("audio files-----" + arrayOfField[i].getName());
videoFilename.add(arrayOfField[i].getName());
Uri localUri = Uri.parse("android.resource://" + Listmodels.this.getPackageName() + "/" + "R.raw." + arrayOfField[i].getName());
System.out.println("--------uri path------" + localUri);
}
}
#Override
public int getCount() {
return videolisty.size();
}
#Override
public Object getItem(int i)
{
return videolisty.get(i);
}
#Override
public long getItemId(int i)
{
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup)
{
View v = view;
final int xx = i;
if(v == null)
{
v = inflater.inflate(R.layout.clistview, viewGroup, false);
v.setTag(R.id.categoryimageView1, v.findViewById(R.id.categoryimageView1));
v.setTag(R.id.uploadimg, v.findViewById(R.id.uploadimg));
v.setTag(R.id.uploadvideo, v.findViewById(R.id.uploadvideo));
v.setTag(R.id.play, v.findViewById(R.id.play));
}
picture = (ImageView)v.getTag(R.id.categoryimageView1);
imgbtn = (Button)v.getTag(R.id.uploadimg);
videobtn = (Button)v.getTag(R.id.uploadvideo);
play=(ImageButton)v.getTag(R.id.play);
imgbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Activity aa = (Activity)context;
aa.startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
System.out.println("YEST"+xx);
Intent localIntent = new Intent(Listmodels.this, Videoplay.class);
localIntent.putExtra("videopath", videoFileList.get(xx));
startActivity(localIntent);
}
});
/*picture.setImageResource(item.drawableId);
name.setText(item.name);*/
return v;
}
protected void onActivityResult(int requestCode, int resultCode) {
super.onActivityResult(requestCode, resultCode, data);
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();
System.out.println("------data path-------"+picturePath);
//filechoose.setText(picturePath);
}
}