How to show transparent image with instructions over my activity? - java

I have an activity with some photos, and I'm using ViewPager for swiping those photos. How can I show some transparent image at the activity start, just to show some instructions for swipe and stuff, like ES File Explorer did it on the image below? I have and image, transparent like the one below. I want to show it on top of my first image, and the user can swipe it.
Here's my class:
public class Photo_gallery extends Activity implements OnClickListener{
Button save;
Context mContext;
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Images/");
boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
save = (Button) findViewById(R.id.bSave);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "StyleMe-" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
int currentItem = viewPager.getCurrentItem();
Drawable drawable = mContext.getResources().getDrawable(adapter.mImages[currentItem]);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success at /sdcard/Pictures/SexyImages",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse
("file://"
+ Environment.getExternalStorageDirectory())));
}
});
}
public class ImagePagerAdapter extends PagerAdapter {
public int[] mImages = new int[] {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
.
.
.
R.drawable.p108
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Photo_gallery.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}

The simplest solution is probably to use the ShowcaseView library for this.

Related

How to open multiple images from sd card in viewpager using fragment?

I am new to android, I am making an app which can select and open multiple images from the gallery and can be viewed as slides. Then use paint canvas to draw on the images and record the whole screen.
I have managed to do all the parts except loading multiple images from the gallery into my app.
I can open images from drawable but finding difficulty to open from the gallery.
I am using ViewPager and fragment to open images from drawable, plz let me know a way to open multiple images from the gallery and show in my ViewPager.
page fragment class
package com.example.test2;
public class PageFragment extends Fragment {
private int imageResource;
private Bitmap bitmap;
public static PageFragment getInstance(int resourceID) {
PageFragment f = new PageFragment();
Bundle args = new Bundle();
args.putInt("image_source", resourceID);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageResource = getArguments().getInt("image_source");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 4;
o.inDither = false;
bitmap = BitmapFactory.decodeResource(getResources(), imageResource, o);
imageView.setImageBitmap(bitmap);
}
#Override
public void onDestroy() {
super.onDestroy();
bitmap.recycle();
bitmap = null;
}
}
viewPagerAdapter class
package com.example.test2;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Integer> images;
public ViewPagerAdapter(FragmentManager fm, List<Integer> imagesList) {
super(fm);
this.images = imagesList;
}
#Override
public Fragment getItem(int position) {
return PageFragment.getInstance(images.get(position));
}
#Override
public int getCount() {
return images.size();
}
}
MainActivity
package com.example.test2;
public class MainActivity extends AppCompatActivity {
ImageButton draw;
RelativeLayout relativeLayout;
Paint paint;
View view;
Path path2;
Bitmap bitmap;
Canvas canvas;
private ArrayList<Integer> images;
private BitmapFactory.Options options;
private ViewPager viewPager;
private View btnNext, btnPrev;
private FragmentStatePagerAdapter adapter;
private LinearLayout thumbnailsContainer;
private final static Integer[] resourceIDs = new Integer[]{R.mipmap.image7,R.mipmap.image6,R.mipmap.image5
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
images = new ArrayList<>();
//find view by id
viewPager = (ViewPager) findViewById(R.id.view_pager);
thumbnailsContainer = (LinearLayout) findViewById(R.id.container);
btnNext = findViewById(R.id.next);
btnPrev = findViewById(R.id.prev);
btnPrev.setOnClickListener(onClickListener(0));
btnNext.setOnClickListener(onClickListener(1));
setImagesData();
// init viewpager adapter and attach
adapter = new ViewPagerAdapter(getSupportFragmentManager(), images);
viewPager.setAdapter(adapter);
inflateThumbnails();
relativeLayout = (RelativeLayout) findViewById(R.id.layout);
draw= findViewById(R.id.b);
draw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setTitle("");
dialog.setContentView(R.layout.menu);
dialog.show();
Button black = dialog.findViewById(R.id.Black);
Button blue = dialog.findViewById(R.id.Blue);
Button red = dialog.findViewById(R.id.Red);
black.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
color();
paint.setColor(Color.parseColor("black"));
dialog.dismiss();
}
});
blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
color();
paint.setColor(Color.parseColor("blue"));
dialog.dismiss();
}
});
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
color();
paint.setColor(Color.parseColor("red"));
dialog.dismiss();
}
});
}
});
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i > 0) {
//next page
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
} else {
//previous page
if (viewPager.getCurrentItem() > 0) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
}
};
}
private void setImagesData() {
for (int i = 0; i < resourceIDs.length; i++) {
images.add(resourceIDs[i]);
}
}
private void inflateThumbnails() {
for (int i = 0; i < images.size(); i++) {
View imageLayout = getLayoutInflater().inflate(R.layout.item_image, null);
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.img_thumb);
imageView.setOnClickListener(onChagePageClickListener(i));
options = new BitmapFactory.Options();
options.inSampleSize = 3;
options.inDither = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),images.get(i),options);
imageView.setImageBitmap(bitmap);
//set to image view
imageView.setImageBitmap(bitmap);
//add imageview
thumbnailsContainer.addView(imageLayout);
}
}
private View.OnClickListener onChagePageClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(i);
}
};
}
public void color()
{
view = new SketchSheetView(MainActivity.this);
paint = new Paint();
path2 = new Path();
relativeLayout.addView(view, new ViewGroup.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
paint.setDither(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(6);
}
class SketchSheetView extends View {
public SketchSheetView(Context context) {
super(context);
bitmap = Bitmap.createBitmap(820, 480, Bitmap.Config.ARGB_4444);
canvas = new Canvas(bitmap);
this.setBackgroundColor(Color.TRANSPARENT);
}
private ArrayList<DrawingClass> DrawingClassArrayList = new ArrayList<DrawingClass>();
#Override
public boolean onTouchEvent(MotionEvent event) {
DrawingClass pathWithPaint = new DrawingClass();
canvas.drawPath(path2, paint);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
path2.moveTo(event.getX(), event.getY());
path2.lineTo(event.getX(), event.getY());
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
path2.lineTo(event.getX(), event.getY());
pathWithPaint.setPath(path2);
pathWithPaint.setPaint(paint);
DrawingClassArrayList.add(pathWithPaint);
}
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (DrawingClassArrayList.size() > 0) {
canvas.drawPath(
DrawingClassArrayList.get(DrawingClassArrayList.size() - 1).getPath(),
DrawingClassArrayList.get(DrawingClassArrayList.size() - 1).getPaint());
}
}
}
public class DrawingClass {
Path DrawingClassPath;
Paint DrawingClassPaint;
private Path getPath() {
return DrawingClassPath;
}
private void setPath(Path path) {
this.DrawingClassPath = path;
}
private Paint getPaint() {
return DrawingClassPaint;
}
private void setPaint(Paint paint) {
this.DrawingClassPaint = paint;
}
}
}
I'm not sure it's possible directly since to reach the gallery, you need to call an intent.
I suggest you to launch a method to retrieve photos in the gallery, following this example: enter link description here, to save all images into a list, and to display pictures in viewpager like you've aldready done.

View Pager showing the same Images on swipe

I have a relative layout which contains a viewpager to enable to me swipe images fetched from my web service.The fetched images are then stored in a ArrayList which contains a HashMap. I've logged the fetching part of from web service and the log indicates that I am indeed fetching different images. However, whenever I'm swiping from image to image, the viewpager displays the same image which is always the last image saved. I've logged the ArrayList of images in the Pager Adapter and it seems that I am getting the correct arraylist size but I'm getting the same bitmap in all sizes.
This is my PagerAdapter class:
public class ImageAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<HashMap<String, Object>> images;
public ImageAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
this.context = context;
this.images = images;
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_image_video, null);
RelativeLayout rlAttach = (RelativeLayout) view.findViewById(R.id.rl_attach);
ImageView imgAttach = (ImageView) view.findViewById(R.id.img_attach);
VideoView vvAttach = (VideoView) view.findViewById(R.id.vv_attach);
LinearLayout llOverlay = (LinearLayout) view.findViewById(R.id.ll_video_overlay);
ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
LinearLayout llUnsupportFile = (LinearLayout) view.findViewById(R.id.ll_unsupport_file);
Log.d(TAG, "image: " + images.size() + " " + images);
Bitmap image = (Bitmap) images.get(position).get("image");
image = CommonUtilities.checkBitmapRotation(bmp);
imgAttach.setVisibility(View.VISIBLE);
vvAttach.setVisibility(View.GONE);
llOverlay.setVisibility(View.GONE);
llUnsupportFile.setVisibility(View.GONE);
imgAttach.setImageBitmap(image);
pBar.setVisibility(View.GONE);
setPreviewClick(imgAttach, position, rlAttach);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
This is where I set the adapter and set notifidydatasetchange:
if (galleryList.size() > 0) {
llNoGallery.setVisibility(View.GONE);
rlHasGallery.setVisibility(View.VISIBLE);
pbGallery.setVisibility(View.GONE);
vpGallery.setVisibility(View.VISIBLE);
tvPageCount.setVisibility(View.VISIBLE);
mImageAdapter = new ImageAdapter(getActivity(), galleryList);
for (HashMap getList : galleryList) {
Log.d(TAG, "onMe: " + getList.toString());
}
vpGallery.setAdapter(mImageAdapter);
vpGallery.addOnPageChangeListener(viewPagerPageChangeListener);
vpGallery.setOffscreenPageLimit(galleryList.size());
mImageAdapter.notifyDataSetChanged();
tvPageCount.setText("1/" + galleryList.size());
} else {
rlHasGallery.setVisibility(View.GONE);
llNoGallery.setVisibility(View.VISIBLE);
}
This is the function to save the images fetched to the arraylist:
private void saveImagesToArrayList(String photo) {
bmp = null;
if (!photo.isEmpty()) {
bmp = imageLoader.loadImageSync(photo);
// tmp hashmap for single image
HashMap<String, Object> hmImage = new HashMap<String, Object>();
// adding each child node to HashMap key => value
hmImage.put("image", bmp);
galleryList.add(hmImage);
// tmp hashmap for single image
HashMap<String, Object> hmImageInString = new HashMap<String, Object>();
// adding each child node to HashMap key => value
hmImageInString.put("image", photo);
galleryListInString.add(hmImageInString);
}
}
This is my ViewPagerChangeListener which shows the position of the image swipped to :
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
tvPageCount.setText(position + 1 + "/" + (galleryList.size()));
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
Here I have the setPreviewClick method to open up the image in full screen via intent. The images show here are correct here which displays different images on swipe.
private void setPreviewClick(View view, int imagePosition, RelativeLayout rlAttach) {
final int mPosition = imagePosition;
rlAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intentViewActivity(mPosition);
}
});
ImageView mImg = (ImageView) view;
mImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intentViewActivity(mPosition);
}
});
}
The intentViewActivity method is as follows:
public void intentViewActivity(int position) {
Intent intent = new Intent(getActivity(), ViewImageViewPagerActivity.class);
intent.putExtra("images", galleryListInString);
intent.putExtra("image_position", position);
getActivity().startActivity(intent);
}
The one of the parameter of the intentViewActivity method is the ViewImageViewPagerActivity which is this:
package com.epicamera.vms.i_neighbour.activity;
public class ViewImageViewPagerActivity extends AppCompatActivity {
private String TAG = "ViewImageViewPagerActivity";
Toolbar toolbar;
private View temp_view;
private VideoView vv;
private TextView toolbar_title;
private ViewPager insideViewPager;
private MyViewPagerAdapter myViewPagerAdapter;
ArrayList<HashMap<String, Object>> imageList = new ArrayList<>();
Bitmap bmp = null;
ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
private String username, companyname, usertype, companylogo, userid, token, userphoto, usergender;
private String android_id;
private String regId;
private Bitmap attachment = null;
private int imagePosition = 0, actualPosition = 0;
private int onPageScrollPosition = 0;
private boolean isVideo = false;
private Handler fileCheckerHandler = new Handler();
private Runnable fileCheckerRunnable = null;
private Uri uri;
// AsyncTask
AsyncTask<Void, Void, Boolean> task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_image_video_viewpager);
CommonUtilities.toggleRotationAdvance(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar_title = (TextView) findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//remove the tittle
getSupportActionBar().setDisplayShowTitleEnabled(false);
SessionManager session = new SessionManager(this.getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// session id
username = user.get(SessionManager.KEY_USERNAME);
// user id
companyname = user.get(SessionManager.KEY_COMPANYNAME);
// company id
usertype = user.get(SessionManager.KEY_USERTYPE);
// company id
companylogo = user.get(SessionManager.KEY_COMPANYLOGO);
// user id
userid = user.get(SessionManager.KEY_USERID);
// session token
token = user.get(SessionManager.KEY_TOKEN);
// session user photo
userphoto = user.get(SessionManager.KEY_USERPHOTO);
usergender = user.get(SessionManager.KEY_USERGENDER);
android_id = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
insideViewPager = (ViewPager) findViewById(R.id.inside_view_pager);
imageList = (ArrayList<HashMap<String,Object>>) getIntent().getExtras().getSerializable("images");
imagePosition = getIntent().getExtras().getInt("image_position");
actualPosition = imagePosition;
myViewPagerAdapter = new MyViewPagerAdapter(ViewImageViewPagerActivity.this, imageList);
insideViewPager.setAdapter(myViewPagerAdapter);
insideViewPager.addOnPageChangeListener(viewPagerPageChangeListener);
insideViewPager.setOffscreenPageLimit(imageList.size());
insideViewPager.setCurrentItem(actualPosition, false);
myViewPagerAdapter.notifyDataSetChanged();
toolbar_title.setText(actualPosition + 1 + " / " + (imageList.size()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// return super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_image_menu, menu);
return true;
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "id: " + item.getItemId());
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_savetogallery:
String[] count = toolbar_title.getText().toString().split("/");
int value = Integer.parseInt(count[0].trim()) - 1;
HashMap<String, String> child = new HashMap<>();
child.put("image", (String) imageList.get(value).get("image"));
saveToGallery(child, "File");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void saveToGallery(HashMap<String, String> item, final String type) {
//take the current position
final String select_document_link = item.get("image");
final String select_document_name = item.get("image");
final String selected_document = select_document_name.substring(select_document_name.lastIndexOf('/') + 1, select_document_name.length());
final String document_download_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").getPath() + File.separator + selected_document;
final File file = new File(document_download_path);
Log.d(TAG, "path: " + document_download_path + " " + select_document_link);
// Check is the file is exist
// if (file.exists()) {
// //Open the file if exist
// openFile(file);
// } else {
//Download and open the file, if does not exist
try {
Toast.makeText(ViewImageViewPagerActivity.this, "Downloading...", Toast.LENGTH_SHORT).show();
// final ProgressDialog progDailog = ProgressDialog.show(this,
// this.getResources().getString(R.string.txt_title_downloading),
// this.getResources().getString(R.string.txt_document_downloading), true);
new Thread() {
public void run() {
try {
//Download the document
final DownloadManager downloadManager;
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").mkdirs();
downloadManager = (DownloadManager) ViewImageViewPagerActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
// have to replace space to %20
String url = select_document_link.replace(" ", "%20");
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri)
.setTitle(selected_document)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DCIM + "/i-Neighbour",
selected_document)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
//ADDED LOOP HERE UNTIL FILE DOWNLOAD IS COMPLETE
fileCheckerRunnable = new Runnable() {
public void run() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PENDING);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_PAUSED:
//download is waiting to retry or resume
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_PENDING:
//download is waiting to start
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_RUNNING:
//download is currently running
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_SUCCESSFUL:
//download has successfully completed
//Open the document
// openFile(file);
Toast.makeText(ViewImageViewPagerActivity.this, type + " saved to Gallery->i-
Neighbour", Toast.LENGTH_SHORT).show();
// progDailog.dismiss();
//STOP REPEATING TASK
fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
break;
case DownloadManager.STATUS_FAILED:
//download has failed (and will not be retried)
// progDailog.dismiss();
//STOP REPEATING TASK
fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
break;
}
}
}
};
fileCheckerHandler.postDelayed(fileCheckerRunnable, 1000);
} catch (Exception e) {
Log.d(TAG, "Error: " + e);
}
}
}.start();
} catch (Exception e) {
Log.e("ERROR", "Error -> " + e.getMessage());
}
}
// outside viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
toolbar_title.setText(position + 1 + " / " + (imageList.size()));
onPageScrollPosition = position;
Log.d(TAG, "onpagescrollposition: " + onPageScrollPosition);
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<HashMap<String, Object>> images;
public MyViewPagerAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
this.context = context;
this.images = images;
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_image_video2, null);
final VideoView vvFullScreen = (VideoView) view.findViewById(R.id.vv_full_screen);
final TouchImageView imgFullScreen = (TouchImageView) view.findViewById(R.id.img_full_screen);
final ImageView imgVideoBg = (ImageView) view.findViewById(R.id.img_video_bg);
final ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
final LinearLayout llVideoPlay = (LinearLayout) view.findViewById(R.id.ll_video_play);
view.setTag("pos" + position);
//Bitmap image = (Bitmap) images.get(position).get("image");
String image_url = (String) images.get(position).get("image");
imgFullScreen.setVisibility(View.VISIBLE);
vvFullScreen.setVisibility(View.GONE);
llVideoPlay.setVisibility(View.GONE);
Glide.with(context).load(image_url)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgFullScreen);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
}

dynamically change list view images in android from memory

I have a list view with image.I want to change list item image on onActivityResult
of image capturing .I get the image file bitmap but when I change the list items image the list view image does not change.
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView1.setImageBitmap(bitmap);//there a bitmap exist---
dataAdapter.taskList.get(0).setImgBitmap(bitmap);
//this is not changing list image.why???????
dataAdapter.notifyDataSetChanged();
here the imageview1 has a bitmap and I set it to first item of list using CustomAdapter class's ArrayList<Task> taskList parameter.
here full sample code
NotifyAcitivity.java
package com.aci.notification;
public class NotifyActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView imageView1;
Bitmap bm, bm2;
private Button btnCapturePicture;
ArrayList<Task> taskList = new ArrayList<Task>();
TextView tv;
CustomAdapter dataAdapter = null;
Button btnSave;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notify);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
imageView1 = (ImageView) findViewById(R.id.imageView1);
tv = (TextView) findViewById(R.id.textViewtest);
btnSave = (Button) findViewById(R.id.button1);
listView = (ListView) findViewById(R.id.listView1);
new BitmapFactory();
bm = BitmapFactory.decodeResource(getApplicationContext()
.getResources(), R.drawable.ic_launcher);
bm2 = BitmapFactory.decodeResource(getApplicationContext()
.getResources(), R.drawable.bydefault);
Task task;
task = new Task(0, "This is task1", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(1, "This is task2", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(0, "This is task3", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(0, "This is task4", "/pictures/hello camera/", bm2,false);
taskList.add(task);
task = new Task(0, "This is task5", "/pictures/hello camera/", bm,false);
taskList.add(task);
dataAdapter = new CustomAdapter(this, R.layout.list_style, taskList);
listView.setAdapter(dataAdapter);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
imageView1.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView1.setImageBitmap(bitmap);
dataAdapter.taskList.get(0).setImgBitmap(bitmap);
dataAdapter.notifyDataSetChanged();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<Task> {
public ArrayList<Task> taskList;
Context context;
public CustomAdapter(Context context, int resource, ArrayList<Task> taskList) {
super(context, resource, taskList);
this.context=context;
// TODO Auto-generated constructor stub
this.taskList = new ArrayList<Task>();
this.taskList.addAll(taskList);
}
private class ViewHolder {
CheckBox task;
ImageView imageView;
int task_id;
Button imageCaptureBtnButton;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_style, null);
viewHolder = new ViewHolder();
viewHolder.task_id=taskList.get(position).getTask_id();//set task id of that task
viewHolder.task = (CheckBox) convertView.findViewById(R.id.checkBox1);
viewHolder.imageView=(ImageView) convertView.findViewById(R.id.imgPreview);
viewHolder.imageCaptureBtnButton=(Button) convertView.findViewById(R.id.btnCapturePicture);
viewHolder.imageView.setImageBitmap(taskList.get(position).getImgBitmap());
convertView.setTag(viewHolder);
viewHolder.task.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task aTask =(Task) cb.getTag();
Toast.makeText(context,
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show();
aTask.setSelected(cb.isChecked());
}
});
viewHolder.imageCaptureBtnButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "dddd", Toast.LENGTH_LONG).show();
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Task aTask = taskList.get(position);
viewHolder.task.setText(taskList.get(position).getTask());
viewHolder.task.setChecked(taskList.get(position).isSelected());
viewHolder.task.setTag(aTask);
return convertView;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public int getCount() {
return taskList.size();
}
#Override
public Task getItem(int arg0) {
return null;
}
}
Task.java
public class Task {
int task_id = 0;
String task = null;
String imageURL=null;
Bitmap imgBitmap;
boolean selected=false;
public Task(int task_id, String task, String imageURL,Bitmap imgBitmap, boolean selected) {
super();
this.task_id = task_id;
this.task= task;
this.imageURL=imageURL;
this.imgBitmap=imgBitmap;
this.selected = selected;
}
//all getters and setters here
}
I have lost my days .please help me.
After a long time I found my own question answer.
The code is not fully matched to this question because answer is from my another project.I am just giving the way I succeeded.
Step 1:
When an image is captured I call imagedata(Bitmap bitmap).It convert each bitmap to base_64 string and this method adds new image to a list as array element of type ByteDrawable.
I create new adapter object again and set that adapter to the
listview.
private void imagedata(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
image_data = Base64.encodeToString(byte_arr, 0);
byteDrawableList.add(new ByteDrawable(image_data));
listAdapter = new CustomAdapter(this);
listView.setAdapter(listAdapter );
}
public class ByteDrawable {
String imageAsBytes;
public ByteDrawable(String imageAsBytes) {
this.imageAsBytes = imageAsBytes;
}
}
Step 2:
Then I populate my list from that arraylist and in Adapter class's constructor I convert the base_64 string to bitmap and add element to a local arraylist items<Item>, then in getview() method I used items to create listview.
private class CustomAdapter extends ArrayAdapter<ByteDrawable>{
public CustomAdapter(Context context, int resource, ArrayList<ByteDrawable > byteDrawableList) {
super(context, resource, byteDrawableList);
this.context=context;
this.byteDrawableList= new ArrayList<ByteDrawable >();
this.byteDrawableList.addAll(byteDrawableList);
inflater = LayoutInflater.from(context);
long k = 0;
for (ByteDrawable bd : byteDrawableList) {
String base = bd.getImageByteString();
byte[] imageAsBytes = Base64.decode(base.getBytes(),
Base64.DEFAULT);
items.add(new Item(k, BitmapFactory.decodeByteArray(
imageAsBytes, 0, imageAsBytes.length)));
k++;
}
}
private class Item {
final long itmeid;
final Bitmap drawabledata;
Item(long id, Bitmap bitmap) {
this.itmeid = id;
this.drawabledata = bitmap;
}
}
public View getView(final int position, View view, ViewGroup viewGroup) {
/* follow normal way to set data to list item*/
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).itmeid;
}
}
Hope this will help someone if they face same problem.

How to share full screen image android?

I am displaying image in the view pager by fetching from the server.I am not displaying the full screen image.I have added the feature to share the image via email or many other options.
code to share image
imageView = (TouchImageView) viewpager.findViewWithTag(viewpager
.getCurrentItem());
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
String path = Images.Media.insertImage(getContentResolver(), bitmap,
"description", null);
uri = Uri.parse(path);
Intent send_report = new Intent(Intent.ACTION_SEND);
send_report.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
send_report.putExtra(Intent.EXTRA_SUBJECT, "Give Me That Picture");
send_report.putExtra(Intent.EXTRA_STREAM, uri);
send_report.putExtra(Intent.EXTRA_TEXT, "cool picture");
send_report.setType("text/plain");
send_report.setType("image/png");
startActivityForResult(
Intent.createChooser(send_report, "Choose an Email client"), 77);
But the image which is shared is not a full screen image.But i want to share the actual size image.Please help me out on this.
UPDATE
view pager adapter
public class ImagePagerAdapter extends PagerAdapter {
LayoutInflater inflater;
PhotoViewAttacher attacher;
PhotoViewAttacher pic;
private DisplayImageOptions options;
private List<Wallpaper> IMAGES_LIST = AppController.getInstance()
.getPrefManger().getAllImages();
public ImagePagerAdapter(Context context) {
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.resetViewBeforeLoading(true).cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300)).build();
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final View imageLayout = inflater.inflate(
R.layout.item_pager_image, container, false);
assert imageLayout != null;
pos = position;
imageView = (TouchImageView) imageLayout.findViewById(R.id.image);
// pic=new PhotoViewAttacher(imageView);
imageView.setTag(position);
imageView.setOnDoubleTapListener(new OnDoubleTapListener() {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// TODO Auto-generated method stub
Log.i("hello", "sinfle");
mHandler.removeCallbacks(r);
share.setVisibility(View.VISIBLE);
done.setVisibility(View.VISIBLE);
gimmy.setVisibility(View.VISIBLE);
comment.setVisibility(View.VISIBLE);
mHandler.postDelayed(r, 5 * 1000);
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
// TODO Auto-generated method stub
Log.i("hello", "donl");
return false;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
});
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showShareDialog();
}
});
final ProgressBar spinner = (ProgressBar) imageLayout
.findViewById(R.id.loading);
ImageLoader.getInstance().displayImage(
IMAGES_LIST.get(position).getUrl(), imageView, options,
new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(view.getContext(), message,
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES_LIST.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
You've already set cacheOnDisk(true), so now you want to take an image from it by:
File cachedImage = imageLoader.getDiscCache().get(imageUrl);
if (cachedImage.exists()) {
/// get your image from file
}
If you take the cache of the current image in view pager then you will get the view which is being displayed on view pager with margins.You need to download the image from the server.Get the url of current displayed image in view pager & download the image from the server.This will solve your problem.

capturing images from camera and setting into listview in android

What i am doing::
I am opening a camera onclick of item from actionbar menu
I am capturing the image and setting it in a listview
What is happening::
Say i have captured 10 images and set it in listview
next time i run my code, i am able to find the images i took last
time, and it dosen't start from groundup
What i am trying to do:
say i captured 10 images and set in listview
next time i start the app and start capturing the image it should add
freshly captured images to listview and not display the old images
i am not telling i have to delete these images but i the app i want
to show newly captured images everytime
MainActivity.java
public class MainActivity extends ListActivity {
private static final int CAMERA_CAPTURE = 20;
ArrayList<String> listOfImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayCapturedImagesFromCamera();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_camera) {
startCameraCapture();
return true;
}
return super.onOptionsItemSelected(item);
}
private void startCameraCapture() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = CreateImageFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(photoFile != null)
{
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
}
}
}
private File CreateImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "Image_" + timeStamp + "_";
File storageDirectory = getExternalFilesDir("");
File image = File.createTempFile(imageFileName, ".jpg",storageDirectory);
return image;
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
switch(requestCode)
{
case CAMERA_CAPTURE:
if(resultCode == RESULT_OK)
{
DisplayCapturedImagesFromCamera();
}
break;
}
}
private void DisplayCapturedImagesFromCamera() {
// TODO Auto-generated method stub
File myPath = getExternalFilesDir(null);
listOfImages = new ArrayList<String>();
try
{
for(File f: myPath.listFiles()) {
listOfImages.add(f.getAbsolutePath());
}
AdptAddjobsGallery adapter = new AdptAddjobsGallery(MainActivity.this,listOfImages);
setListAdapter(adapter);
}
catch(Exception ex)
{
Log.w("Error", ex.getMessage());
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cust_dialog);
dialog.setTitle("Image ");
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
// set the custom dialog components - text, image and button
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageBitmap(bitmap);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
dialog.show();
}
}
AdptAddjobsGallery.java
public class AdptAddjobsGallery extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> listOfImages;
public AdptAddjobsGallery(Activity context, ArrayList<String> listOfImages) {
super(context, R.layout.adpt_addjobs_gallery, listOfImages);
// TODO Auto-generated constructor stub
this.context=context;
this.listOfImages = listOfImages;
}
public View getView(int position,View view,ViewGroup parent) {
ViewHolder holder;
if(view == null)
{
LayoutInflater inflater=context.getLayoutInflater();
view =inflater.inflate(R.layout.adpt_addjobs_gallery, null,true);
holder = new ViewHolder();
holder.imageView = (ImageView) view.findViewById(R.id.selfie);
holder.txtTitle = (TextView) view.findViewById(R.id.fileName);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
File f = new File(listOfImages.get(position));
holder.txtTitle.setText(f.getName());
holder.imageView.setImageBitmap(bitmap);
return view;
};
}
class ViewHolder {
TextView txtTitle;
ImageView imageView;
}
try this, using file.lastmodified() method.
private ArrayList<String> getRecentImages(long from, long to,
ArrayList<String> list) {
ArrayList<String> sortedList = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
File file = new File(list.get(i));
long modified = file.lastModified();
if (modified > from && modified <= to) {
sortedList.add(list.get(i));
}
}
return sortedList;
}

Categories

Resources