How to save Image captured from camera in gallery as well as in backup folder - image

In My application I am capturing image from camera and storing it in folder created by me. This folder is getting created in Pictures. Now I wants to save same image in my local storages's /BackUp folder.
This is code for
public class MainActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private MultipartEntity multipartEntity;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "FORMS";
private Bitmap bitmap1;
private Uri fileUri; // file url to store image/video
private static String output;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/*
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
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();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
private void previewCapturedImage() {
try {
imgPreview.setVisibility(View.VISIBLE);
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap1);
//imgPreview.setImageBitmap(result);
} catch (NullPointerException e) {
e.printStackTrace();
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}
return mediaFile;
}
Right Now this image is getting save at PICTURES/FORMS Folder. I wants to save it to FORMSBACKUP/IMAGES Folder as well.

Related

How About onActivityResult when I want to read multiple file from storage

How About onActivityResult when I want to read multiple file form storage
In this xml form I have to take multiple image file by clicking different different button from the app external storage but their is a difficulties on ActivityResult override method calling , because it call automatically and can't be call multiple time for for different different button
It's working fine for single file picking and get image URI.
So how can I fix the ActivityResult override method for different different button in a single activity
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static final int PICK_PHOTO = 1958;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, PICK_PHOTO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
}
}
Taking a array to pick photo then check with if else statement by array index
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static int[] PICK_PHOTO={0,1,2,3,4,5} ;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.appBar.title.setText("লাইসেন্সের জন্য আবেদন করুন");
binding.appBar.back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 0);
}
});
binding.form4.chooseBankCertificate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[0]) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[1]) {
Uri imageUri = data.getData();
binding.form4.selectedBankCertificate.setText("" + imageUri.getLastPathSegment());
}
}
}

How to get the file path of an image in Camera2Basic api?

this must be a stupid question but please help me. How can we get the image file path in camera2basic api and display the image on the other activity's imageview? I have been trying to get the "Absolutepath" of the mFile in the project but not getting anything.
As Camera2 api is relatively complex to understand for me. Please help me.
public override void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
mFile = new Java.IO.File(Activity.GetExternalFilesDir(null), "pic.jpg");
mCaptureCallback = new CameraCaptureListener(this);
mOnImageAvailableListener = new ImageAvailableListener(this, mFile);
}
when we press the button, it evokes takepicture(); which has lockfocus();
private void LockFocus()
{
try
{
// This is how to tell the camera to lock focus.
mPreviewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Start);
// Tell #mCaptureCallback to wait for the lock.
mState = STATE_WAITING_LOCK;
mCaptureSession.Capture(mPreviewRequestBuilder.Build(), mCaptureCallback,
mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
I have showCapturePhoto which is getting the image from ImageAvailableListener
using Android.Media;
using Java.IO;
using Java.Lang;
using Java.Nio;
using Android.Util;
namespace Camera2Basic.Listeners
{
public class ImageAvailableListener : Java.Lang.Object,
ImageReader.IOnImageAvailableListener
{
private readonly File file;
private Camera2BasicFragment owner;
public ImageAvailableListener(Camera2BasicFragment fragment, File
file)
{
if (fragment == null)
throw new System.ArgumentNullException("fragment");
if (file == null)
throw new System.ArgumentNullException("file");
owner = fragment;
this.file = file;
}
//public File File { get; private set; }
//public Camera2BasicFragment Owner { get; private set; }
public void OnImageAvailable(ImageReader reader)
{
owner.mBackgroundHandler.Post(new ImageSaver(reader.AcquireNextImage(), file));
}
// Saves a JPEG {#link Image} into the specified {#link File}.
private class ImageSaver : Java.Lang.Object, IRunnable
{
// The JPEG image
private Image mImage;
// The file we save the image into.
private File mFile;
public ImageSaver(Image image, File file)
{
if (image == null)
throw new System.ArgumentNullException("image");
if (file == null)
throw new System.ArgumentNullException("file");
mImage = image;
mFile = file;
}
public void Run()
{
ByteBuffer buffer = mImage.GetPlanes()[0].Buffer;
byte[] bytes = new byte[buffer.Remaining()];
buffer.Get(bytes);
using (var output = new FileOutputStream(mFile))
{
try
{
output.Write(bytes);
}
catch (IOException e)
{
e.PrintStackTrace();
}
finally
{
mImage.Close();
}
}
Camera2BasicFragment.showCapturedPhoto(mImage);
}
}
}
}
ShowcapturePhoto
public static void showCapturedPhoto(Image img)
{
ByteBuffer buffer;
byte[] bytes;
MemoryStream memStream = new MemoryStream();
buffer = img.GetPlanes()[0].Buffer;
bytes = new byte[buffer.Capacity()];
buffer.Get(bytes);
Activity activity= new Activity();
Intent showPhoto = new Intent(activity, typeof(RetryOK));
showPhoto.PutExtra("savedImg", bytes);
showPhoto.PutExtra("zoomAmount", 1.7f / 1.4f);
showPhoto.PutExtra("focusDistance", -1.0f);
activity.StartActivity(typeof(RetryOK));
}

Whatsapp implicit intent not working

I am trying to share image and text via whatsapp using implicit intent but I'm not able to share. I have searched the net but could not find any proper explanation. I have attached the code below.
... the code works without errors.but it dose not share content with whatsapp. i have searched all the places in google and on stackoverflow .but could not encounter with any proper explanation
public class MainActivity extends Activity implements View.OnClickListener {
TextView title_text,text_description;
ImageButton main_image;
Button button;
private static String url = "random url ";
private static final String TAG_ID = "title";
private static final String TAG_IMAGE = "image_url";
private static final String TAG_DESC = "product_desc";
String id;
String name;
String image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_description=(TextView)findViewById(R.id.text_description);
title_text=(TextView)findViewById(R.id.text_title);
main_image=(ImageButton)findViewById(R.id.image_main);
button= (Button) findViewById(R.id.button);
button.setOnClickListener(this);
new GetContacts().execute();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"whatsappsharing",Toast.LENGTH_SHORT).show();
Intent whatsappintent=new Intent();
whatsappintent.setAction(Intent.ACTION_SEND);
Uri uri= Uri.parse(TAG_IMAGE);
whatsappintent.setType("text/plain");
whatsappintent.putExtra(Intent.EXTRA_TEXT, "hello nathar");
whatsappintent.setType("image/jpeg");
whatsappintent.putExtra(Intent.EXTRA_STREAM,uri);
whatsappintent.setPackage("com.whatsapp");
startActivity(whatsappintent);
}
private class GetContacts extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
id = jsonObj.getString(TAG_ID);
Log.d(TAG_ID,"title");
name = jsonObj.getString(TAG_DESC);
Log.d(TAG_DESC,"name");
image=jsonObj.getString(TAG_IMAGE);
Log.d(TAG_IMAGE,"image");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (image!=null && !image.equalsIgnoreCase(""))
Picasso.with(MainActivity.this).load(image).fit().into(main_image);
title_text.setText(id);
text_description.setText(name);
}
}
}
Try this piece of code:
Uri imageUri = Uri.parse(TAG_IMAGE);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
// Target whatsapp:
shareIntent.setPackage("com.whatsapp");
// Add text and then Image URI
shareIntent.putExtra(Intent.EXTRA_TEXT, <Message_text>);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(shareIntent);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
where Message_text will be sent as a image caption

Continously updating marker on running Google Map v2

I am making a tracking app that receive data(longitude and latitude) from the user via SMS and display on the googlemapv2. I want my application to work continously and the marker update on new location when a new message is received.But the marker doesn't move to new location.
I have made 2 java files. One is "IncomingSms" that receives new SMS and other is "MainActivity" that display google map and show marker.It show marker on defaultposition but don't update on new coordinates.
Please help me...here is my code..
package com.example.chck;
public class MainActivity extends Activity {
public static LatLng point;
GoogleMap gMap;
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Log.d("Activity","Got new Data again");
Toast.makeText(getApplicationContext(),"In NEW-INTENT", Toast.LENGTH_SHORT).show();
initializeMap();
drawMarker();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.MyMap)).getMap();
initializeMap();
Toast.makeText(getApplicationContext(),"In CREATE", Toast.LENGTH_SHORT).show();
// Enabling MyLocation Layer of Google Map
gMap.setMyLocationEnabled(true);
}
private void drawMarker(){
// Clears all the existing coordinates
String LON="72.99056966";
String LAT="33.64272895";
gMap.clear();
if(IncomingSms.chk==1){
Intent i1 = getIntent();
LAT = i1.getExtras().getString("NewLat");
LON = i1.getExtras().getString("NewLon");
}
Toast.makeText(getBaseContext(),LAT + LON , Toast.LENGTH_SHORT).show();
point = new LatLng(Double.parseDouble(LAT), Double.parseDouble(LON));
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
gMap.clear();
markerOptions.position(point);
// Setting title for the InfoWindow
markerOptions.title("Position");
// Setting InfoWindow contents
markerOptions.snippet("Latitude:"+point.latitude+",Longitude"+point.longitude);
// Adding marker on the Google Map
gMap.addMarker(markerOptions);
// Moving CameraPosition to the user input coordinates
gMap.moveCamera(CameraUpdateFactory.newLatLng(point));
}
private void initializeMap() {
if (gMap == null) {
gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.MyMap)).getMap();
// check if map is created successfully or not
if (gMap == null)
Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
#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;
}
}
========================
IncomingSms.java
package com.example.chck;
public class IncomingSms extends BroadcastReceiver {
public static double latitude;
public static double longitude;
public static int chk =0;
public static String la;
public static String lo;
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage
.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage
.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
String[] columns = message.split(",");
assert columns.length == 2;
longitude = Double.parseDouble(columns[0]);
latitude = Double.parseDouble(columns[1]);
la= columns[1];
lo= columns[0];
Log.i("SmsReceiver", "senderNum: " + senderNum
+ "; message: " + message);
int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, "Latitude: "+
//longitude + ", Longitude: " + latitude, duration);
//toast.show();
} // end for loop
chk=1;
//New Location fetched
Toast.makeText(context,la + lo , Toast.LENGTH_SHORT).show();
final Intent i1 = new Intent(context, MainActivity.class);
i1.putExtra("NewLat", la);
i1.putExtra("NewLon", lo);
int duration1 = Toast.LENGTH_LONG;
//Toast toast1 = Toast.makeText(context, "Check Latitude: "+
// lo + ", Longitude: " + la, duration1);
//toast1.show();
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}

display image in GWT

I have created a widget to display the slideshow.In firefox,everything is fine but in chrome nothing happens. After I refresh with many times, the slideshow is displayed. I don't know Why. Can you give me some ideas? Tks
This is my GWT client:
public SlideClient() {
super();
setStyleName("flexslider");
setHeight("100%");
setWidth("100%");
}
#Override
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
this.paintableId = uidl.getId();
listImage = Arrays.asList(uidl.getStringArrayAttribute("listImage"));
listUrl = Arrays.asList(uidl.getStringArrayAttribute("listUrl"));
loadImage();
checkImagesLoadedTimer.run();
}
public void display() {
m.setStyleName("slides");
m.setHeight("100%");
m.setWidth("100%");
add(m);
}
public native void slideshow() /*-{
$wnd.$('.flexslider').flexslider({slideshowSpeed: 2000});
}-*/;
public native String getURL(String url)/*-{
return $wnd.open(url,
'target=_blank')
}-*/;
private Timer checkImagesLoadedTimer = new Timer() {
#Override
public void run() {
if (loadedImageElements.size() == toLoad) {
display();
} else {
add(new Label("đang load "+loadedImageElements.size()));
checkImagesLoadedTimer.schedule(2000);
}
}
};
private void loadImage() {
for (String tmp : listImage) {
AbsolutePanel panel = new AbsolutePanel();
final Image ima = new Image(tmp);
add(new Label("before put"));
ima.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
loadedImageElements.put(toLoad+"", ima);
slideshow();
add(new Label("đang put "+loadedImageElements.size()));
}
});
add(new Label("after put"));
panel.add(ima);
m.add(panel);
if (toLoad != 0) {
panel.setVisible(false);
}
toLoad++;
}
}
}
Did you implement an Image Loader to prepare your images before they are displayed? A clean solution would be to add the image elements to your page root as an invisible istance, wait for them to load and then use them elsewhere.
You should check out the tutorials about ImageBundling as well: ImageResource
Here's a little extract from one of my image loader classes as you requested, altough there are different ways to realize that:
private HashMap<String,ImageElement> loadedImageElements = new HashMap<String,ImageElement>();
private int toLoad = 0;
private void loadImage(final String name, String url){
final Image tempImage = new Image(url);
RootPanel.get().add(tempImage);
++toLoad;
tempImage.addLoadHandler(new LoadHandler(){
public void onLoad(LoadEvent event) {
loadedImageElements.put(name,ImageElement.as(tempImage.getElement()));
tempImage.setVisible(false);
}
});
}
The image url is retrieved via a ClientBundle-Interface pointing towards the real positions of the images.
I also implemented a timer running in the background to check if all the images have been loaded:
private Timer checkImagesLoadedTimer = new Timer(){
public void run() {
System.out.println("Loaded " + loadedImageElements.size() + "/" + toLoad + " Images.");
if(loadedImageElements.size() == toLoad){
buildWidget();
}else{
checkImagesLoadedTimer.schedule(50);
}
}
};
After everythign is ready, the original widget/page is created.
But as I said there are many ways to implement image loaders. Try out different implementations and select one that suits your needs best.

Resources