I have an ArrayList of Uri's that i want to display in a ViewPager,
this is how my code looks, I have both shown how i have put the URi into a bitmap and a drawable:
public class ImageViewActivity extends Activity {
private List<String> selectedItems;
private Uri uri1;
private Drawable drawable1;
private Bitmap bitmap1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_view);
ExtendedViewPager mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
selectedItems = new ArrayList<String>();
Intent intent = getIntent();
selectedItems = intent.getStringArrayListExtra("selectedItems");
Log.d(ImageViewActivity.class.getSimpleName(), "" + selectedItems.get(0));
uri1 = Uri.parse( selectedItems.get(0));
try {
InputStream inputStream = getContentResolver().openInputStream(uri1);
drawable1 = Drawable.createFromStream(inputStream, uri1.toString());
} catch (FileNotFoundException e) {
drawable1 = getResources().getDrawable(R.drawable.image_for_empty_url);
}
Bitmap myBitmap = BitmapFactory.decodeFile(selectedItems.get(0));
bitmap1 = myBitmap;
}
static class TouchImageAdapter extends PagerAdapter {
private static int[] images = {};
#Override
public int getCount() {
return images.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
TouchImageView img = new TouchImageView(container.getContext());
img.setImageResource(images[position]);
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
but the refference code i'm looking at, has it in the "Drawable Resource Folder", code looks like this:
public class ViewPagerExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager_example);
ExtendedViewPager mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
}
static class TouchImageAdapter extends PagerAdapter {
private static int[] images = { R.drawable.nature_1, R.drawable.nature_2, R.drawable.nature_3, R.drawable.nature_4, R.drawable.nature_5 };
#Override
public int getCount() {
return images.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
TouchImageView img = new TouchImageView(container.getContext());
img.setImageResource(images[position]);
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
I want to use each of my URI's in the ImageAdapter, i just can't figure out how to "put them into" the ImageAdapter.
First of all get the absolute path of image from Uri Because we can not convert image into bitmap using image Uri ,so just with the help of following code you can get Absolute path
Uri ImageURI = "your image uri goes here";
String selectedImagePath = ImageFilePath.getPath(getApplicationContext(), ImageURI);
File imageFile = new File(selectedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
then set image bitmap in the ImageView
imageView.setImageBitmap (bitmap);
hopefully this will solve your problem.
Related
I am a beginner in android programming.Here i have coded to load images(got using serilizable from previous activity) in viewpager.
The issue that i'm facing - When user is seeing this view pager and presses home button to close the app it crashes and shows error as below in my logcat.I am not getting what's wrong with my code. Your help will be appreciated. Thank You.
My Logcat:
java.lang.RuntimeException: Parcel: unable to marshal value extra.Image#30335200 at android.os.Parcel.writeValue(Parcel.java:1343) at android.os.Parcel.writeList(Parcel.java:717) at android.os.Parcel.writeValue(Parcel.java:1290) at android.os.Parcel.writeArrayMapInternal(Parcel.java:644) at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1313) at android.os.Bundle.writeToParcel(Bundle.java:1034) at android.os.Parcel.writeBundle(Parcel.java:669) at android.support.v4.app.FragmentState.writeToParcel(FragmentState.java:120) at android.os.Parcel.writeTypedArray(Parcel.java:1197) at android.support.v4.app.FragmentManagerState.writeToParcel(FragmentManager.java:617) at android.os.Parcel.writeParcelable(Parcel.java:1363)
My Code of previous activity from which this fragment gets called:
List<Image> images = new ArrayList<Image>();
images.add(new Image(data_list.get(arg1).getImage().get(0).toString()));//here my images list array gets added in images array
Bundle bundle = new Bundle();
bundle.putSerializable("images", (Serializable) images);
bundle.putInt("position", 0);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
My Image Model:
public class Image {
private String Image;
private String title;
private String id;
public Image() {
}
public Image(String image, String title, String id) {
Image = image;
this.title = title;
this.id = id;
}
public Image(String image) {
Image = image;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
My Code of SlideShowDialogFragment.java:
public class SlideshowDialogFragment extends DialogFragment {
private String TAG = SlideshowDialogFragment.class.getSimpleName();
private ArrayList<Image> images;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private TextView lblCount, lblTitle, lblDate;
// page change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
displayMetaInfo(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private int selectedPosition = 0;
public static SlideshowDialogFragment newInstance() {
SlideshowDialogFragment f = new SlideshowDialogFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_image_slider, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
lblCount = (TextView) v.findViewById(R.id.lbl_count);
lblTitle = (TextView) v.findViewById(R.id.title);
lblDate = (TextView) v.findViewById(R.id.date);
images = (ArrayList<Image>) getArguments().getSerializable("images");
selectedPosition = getArguments().getInt("position");
Log.e(TAG, "position: " + selectedPosition);
Log.e(TAG, "images size: " + images.size());
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
setCurrentItem(selectedPosition);
return v;
}
private void setCurrentItem(int position) {
viewPager.setCurrentItem(position, false);
displayMetaInfo(selectedPosition);
}
private void displayMetaInfo(int position) {
lblCount.setText((position + 1) + " of " + images.size());
Image image = images.get(position);
lblTitle.setText(image.getTitle());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
}
// adapter
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);
ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);
Image image = images.get(position);
Glide.with(getActivity()).load(ConfigClass.BASE_URL + image.getImage())
.thumbnail(0.5f)
.crossFade()
.placeholder(R.drawable.godarpan_logo)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageViewPreview);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
Hi please used below code else is same.
public class Image implements Serializable
{
// your code..
}
In Android used Parcelable instead of serializable to send data from one activity to other.
Please follow below link for Parcelable:
https://developer.android.com/reference/android/os/Parcelable.html
Because Parcelable is a concept of Android where as Serializable is a concept of Java.
hope it helps.
You have to implement Serializable but its better to implement Parceable because its much faster and efficient than Serializable as it is Android specific interface.
I have image slider in android studio, but images array from inside project.
I want to use images from JSON, how to the best solution..
this is my adapter
public class adapter_image_slider extends PagerAdapter {
Context mContext;
public adapter_image_slider(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return sliderImagesId.length;
}
private int[] sliderImagesId = new int[]{
R.drawable.imghome1, R.drawable.imghome2, R.drawable.imghome3,
};
#Override
public boolean isViewFromObject(View v, Object obj) {
return v == ((ImageView) obj);
}
#Override
public Object instantiateItem(ViewGroup container, int i) {
ImageView mImageView = new ImageView(mContext);
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setImageResource(sliderImagesId[i]);
((ViewPager) container).addView(mImageView, 0);
return mImageView;
}
#Override
public void destroyItem(ViewGroup container, int i, Object obj) {
((ViewPager) container).removeView((ImageView) obj);
}
}
and this is my main activity :
public class activity_img_slider_json extends Fragment {
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.imghome1,R.drawable.imghome2,R.drawable.imghome3,};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_img_slider_json,null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
super.onCreate(savedInstanceState);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager)getActivity().findViewById(R.id.pager);
mPager.setAdapter(new adapter_img_slider_json(getActivity(), XMENArray));
CircleIndicator indicator = (CircleIndicator)getActivity().findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
}
}
Thanks For Attention.
I need to Load Images from a folder in SD Card into a ViewPager. This is what i have managed so far.
public Drawable getImageFromSdCard(String imageName) {
Drawable d = null;
try {
String path = Environment.getExternalStorageDirectory().toString()
+ "/YourSubDirectory/";
Bitmap bitmap = BitmapFactory.decodeFile(path + "/" + imageName
+ ".png");
d = new BitmapDrawable(bitmap);
} catch (IllegalArgumentException e) {
// TODO: handle exception
}
return d;
}
How can i set this as a ViewPager ?
You need make adapter that extends PagerAdapter then set adapter to view pager
Try below code:
ViewPager mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
TouchImageAdapter class:
class TouchImageAdapter extends PagerAdapter {
#Override
public int getCount() {
return 1;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
ImageView img = new ImageView(container.getContext());
img.setImageDrawable(getImageFromSdCard(filename));
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Here is your method used in adapter class
public Drawable getImageFromSdCard(String imageName) {
Drawable d = null;
try {
String path = Environment.getExternalStorageDirectory().toString()
+ "/YourSubDirectory/";
Bitmap bitmap = BitmapFactory.decodeFile(path + "/" + imageName
+ ".png");
d = new BitmapDrawable(bitmap);
} catch (IllegalArgumentException e) {
// TODO: handle exception
}
return d;
}
Hope this helps!
public class EyeLinerActivity extends Activity {
int position;
private ShareActionProvider provider;
ELImageAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eyeliner);
//ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
//adapter = new ELImageAdapter(this);
//viewPager.setAdapter(adapter);
//ViewPager.setCurrentItem(0);
ViewPager pager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ELImageAdapter(this);
pager.setAdapter(new ELImageAdapter(this));
// ImageView imageView = new ImageView(context);
// imageView.setImageResource(GalImages[position]);
// if (pager.getAdapter() != null)
// pager.setAdapter(adapter);
// pager.setCurrentItem(position);
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem shareitem= (MenuItem)menu.findItem(R.id.action_share);
ShareActionProvider provider = (ShareActionProvider)shareitem.getActionProvider();
Bitmap bitmap;
OutputStream output;
//ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
bitmap = BitmapFactory.decodeResource(getResources(),adapter.GalImages[position]);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Eye Liner/");
dir.mkdirs();
File file = new File(dir, "Image.png");
try {
Intent share = new Intent(Intent.ACTION_SEND);
share.setAction(Intent.ACTION_SEND);
share.setType("image/jpeg");
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
Uri uri = Uri.fromFile(file);
share.putExtra(Intent.EXTRA_STREAM, uri);
provider.setShareIntent(share);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
//return super.onCreateOptionsMenu(menu);
private void setShareIntent(Intent intent) {
if (provider != null) {
provider.setShareIntent(intent);
}
}
}
adapter.java
public class ELImageAdapter extends PagerAdapter {
Context context;
public int[] GalImages = new int[] {
R.drawable.l_1,
R.drawable.l_2,
R.drawable.l_3,
R.drawable.l_4,
R.drawable.l_5,
R.drawable.l_6,
R.drawable.l_7,
R.drawable.l_8,
R.drawable.l_9,
R.drawable.l_10,
R.drawable.l_11,
R.drawable.l_12,
R.drawable.l_13,
R.drawable.l_14,
R.drawable.l_15,
R.drawable.l_16,
R.drawable.l_17
};
ELImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
i want to share images .. and i am using viewpager
how can i get images ids to share.? as viewpager does not support onclickitemlistener property. kindly suggest how i can get image id to dhare
If you implement a FragmentStatePagerAdapter, each page of your ViewPager can host an instance of a Fragment of your design, with its layout defined in XML. This will allow you to include whatever Views you need to compose your custom sharing UI.
From Creating Swipe Views with Tabs | Android Developers:
FragmentStatePagerAdapter
This is best for paging across a collection of objects for which the number of pages is undetermined. It destroys fragments as the user navigates to other pages, minimizing memory usage.
For example, here's how you might use FragmentStatePagerAdapter to swipe across a collection of Fragment objects:
public class CollectionDemoActivity extends FragmentActivity {
// When requested, this adapter returns a DemoObjectFragment,
// representing an object in the collection.
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
In your case you could change share intent on every page selected event, like following:
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
setShareIntentForPosition(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
private void setShareIntentForPosition(int currentPosition){
Bitmap bitmap;
OutputStream output;
bitmap = BitmapFactory.decodeResource(getResources(),adapter.GalImages[currentPosition]);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Eye Liner/");
dir.mkdirs();
File file = new File(dir, "Image.png");
try {
Intent share = new Intent(Intent.ACTION_SEND);
share.setAction(Intent.ACTION_SEND);
share.setType("image/jpeg");
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
Uri uri = Uri.fromFile(file);
share.putExtra(Intent.EXTRA_STREAM, uri);
setShareIntent(share);
}
private void setShareIntent(Intent intent) {
if (provider != null) {
provider.setShareIntent(intent);
}
}
how can i get images ids to share.?
Use ViewPager.getCurrentItem() to get current image id from ViewPager:
1. Create a method in ELImageAdapter class to get current selected image id :
public int getImageId(int pos){
return GalImages[pos];
}
2. Call getImageId method using adapter object in onCreateOptionsMenu method :
int currentPos=pager.getCurrentItem();
int currentImgId=adapter.getImageId(currentPos);
Now use currentImgId id to share selected image.
File file = new File(adapter.images.get(myPager.getCurrentItem()));
Intent mShareIntent = new Intent(Intent.ACTION_SEND);
mShareIntent.setType("image/*");
mShareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
startActivity(Intent.createChooser(mShareIntent,"Shareith:"));
Where adapter is object of CustomAdapter creating pages for viewpager, myPager is reference variable for ViewPager enter code here and images is arraylist storing imagepath.
I'm displaying images from resource/drawable folder in full screen using viewpager. It's working fine and are sliding well. now i want to save image name in sdcard,but i am not able to get image file name. if any one will please help me . I have google it, i didn't get correct solution for my expection.
code
public class MainActivity extends Activity{
//private static Context context;
ExtendedViewPager mViewPager;
private static Uri imageUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
}
static class TouchImageAdapter extends PagerAdapter {
private static int[] images = { R.drawable.nature_1, R.drawable.nature_2, R.drawable.nature_3, R.drawable.nature_4, R.drawable.nature_5 };
}
#Override
public int getCount() {
return images.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
//Context context = container.getContext();
TouchImageView img = new TouchImageView(container.getContext());
img.setImageResource(images[position]);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int imagid=images[position];
System.out.println("Image name " + images[position]);
bm = BitmapFactory.decodeStream(v.getResources().getDrawable(imagid));// here i need to pass my resId, i can't able to pass
}
});
//img.setScaleType(TouchImageView.ScaleType.CENTER_CROP);
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
create a String[] which contains file name and set it's itme to img as tag and in onClick get the tag. do something like this
private static String[] imagesName = {"fiel1","file2",.....};
.
.
img.setImageResource(images[position]);
img.setTag(imagesName[position]);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String filename = v.getTag().toString();
}
}
Edit
If you don't want to create String[] then set the images[position] as Tag of img and in onClick get it from tag like getResources().getResourceName((Integer)v.getTag());
This helps me.