android image upload to the server by a multipartentity - android

I wrote a code which takes picture from android device and then upload it on server.Can also upload pic from gallery. Uploading from gallery works perfectly.It is able to intent to mobile camera when clicked on capture button but when i return i didn't got any image and when i checked the gallery no image was captured.
Got menifest permission also
android.permission.WRITE_EXTERNAL_STORAGE"
android.permission.READ_EXTERNAL_STORAGE"
android.permission.CAMERA"
This is code in my Fragments onCreateView() class:
mTakePhoto = (Button) rootView.findViewById(R.id.take_photo);
mselectPhoto = (Button) rootView.findViewById(R.id.select_photo);
mImageView = (ImageView) rootView.findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
TAKE_PICTURE);
}
});
mselectPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,
IMAGE_PICKER_SELECT);
}
});
In the above code i think intents works perfectly
In bellow code, the (requestCode == IMAGE_PICKER_SELECT) condition works perfectly. But it seems like i didn't get any data when i took PICTURE
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICKER_SELECT
&& resultCode == Activity.RESULT_OK) {
Bitmap bitmap = getBitmapFromCameraData(data, getActivity());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(bitmap);
}
if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK
&& data != null) {
// get bundle
Bundle extras = data.getExtras();
// get bitmap
cameraBitmap = (Bitmap) extras.get("data");
int nh = (int) (cameraBitmap.getHeight() * (512.0 / cameraBitmap
.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(cameraBitmap, 512, nh,
true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(cameraBitmap);
// setPic();
}
}
I m also giving the Code of my Multipartentity class
public class MultipartEntity implements HttpEntity {
enter code here
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
I m stuck for almost the fullday. Help!!

Open your camera with below code and check with it:
private Uri mImageCaptureUri;
mImageCaptureUri = Uri.parse("content://YOUR PACKAGE NAME/");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent,TAKE_PICTURE);

I created a method to call whn button is clicked
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
takePhoto();
}
});
method to intent and getTempFile() to keel temporary file..
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getActivity())) );
startActivityForResult(intent, TAKE_PICTURE);
}
private File getTempFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
this link help me
http://www.tutorialforandroid.com/2010/10/take-picture-in-android-with.html

Related

Unable to download and share only 1st image from list of images in ViewPager [Strange Problem]

Hello I am facing Strange Problem I am making an gallery App which download images using volley and showing them to Viewpager called SlideActivity everything is working properly. Problem:- when I try to Download & share 1st image from viewpager nothing happens but when swipe and go to 2nd image share and download is working for 2nd image and when i swipe back to 1st image now share and download works? This is what i have done till now want some advice on this issue.Thank you in Advance!
SlideActivity.Java
public class TrendingSlideActivity extends AppCompatActivity {
private static final String URL = "API";
private ViewPager viewPager;
private Context context = TrendingSlideActivity.this;
private TrendingViewPagerAdapter adapter;
private int position;
private int currentImage;
private List<Trending> data;
private ImageView shareIcon, shareImage, downloadImage;
private int mAdCounter = 0;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trending_slide_activity);
viewPager = findViewById(R.id.viewPager);
ProgressBar progressBar = findViewById(R.id.progress);
shareIcon = findViewById(R.id.shareviewpager);
downloadImage = findViewById(R.id.iv_download_slide);
//final String fileName = getIntent().getStringExtra("filename");
position = getIntent().getIntExtra("pos", 0);
progressBar.setVisibility(View.VISIBLE);
StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("CODE", response);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
TrendingData users = gson.fromJson(response, TrendingData.class);
data = users.getData();
adapter = new TrendingViewPagerAdapter(context, data);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(1);
viewPager.setCurrentItem(position);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TrendingSlideActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
currentImage = viewPager.getCurrentItem();
final String fileName1 = data.get(currentImage).getFileName();
Toast.makeText(TrendingSlideActivity.this, "===========" + fileName1, Toast.LENGTH_SHORT).show();
final String url2 = "API" + fileName1;
new LoadImage(TrendingSlideActivity.this).execute(url2);
shareIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onShareItem(shareImage);
}
});
downloadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveImageToGallery(shareImage);
}
});
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private static class LoadImage extends AsyncTask<String, Integer, Drawable> {
private WeakReference<TrendingSlideActivity> activityWeakReference;
LoadImage(TrendingSlideActivity context) {
activityWeakReference = new WeakReference<>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Drawable doInBackground(String... strings) {
Bitmap bmp = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(strings[0]).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
bmp = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return new BitmapDrawable(bmp);
}
#Override
protected void onPostExecute(Drawable result) {
TrendingSlideActivity activity = activityWeakReference.get();
if (activity == null) return;
activity.shareImage = new ImageView(activity);
//Add image to ImageView
activity.shareImage.setImageDrawable(result);
}
}
public void onShareItem(View v) {
// Get access to bitmap image from view
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri((ImageView) v);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
context.startActivity(Intent.createChooser(shareIntent, "Share TrendingData"));
} else {
// ...sharing failed, handle error
}
}
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
// Use methods on Context to access package-specific directories on external storage.
// This way, you don't need to request external read/write permission.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
// **Warning:** This will fail for API >= 24, use a FileProvider as shown below instead.
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission is granted");
return true;
} else {
Log.i(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.i(TAG, "Permission is granted");
return true;
}
}
public void saveImageToGallery(ImageView iv) {
// //to get the image from the ImageView (say iv)
// BitmapDrawable draw = (BitmapDrawable) iv.getDrawable();
// Bitmap bitmap = draw.getBitmap();
if (iv != null) {
Drawable drawable = iv.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) iv.getDrawable()).getBitmap();
} else {
}
FileOutputStream outStream = null;
String sdCard = Environment.getExternalStorageDirectory().toString();
if (isStoragePermissionGranted()) {
File dir = new File(sdCard, "/GalleryApp");
if (!dir.exists()) {
dir.mkdirs();
}
try {
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
assert bmp != null;
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(TrendingSlideActivity.this, "Saved", Toast.LENGTH_SHORT).show();
Log.i("TAAAAAAAAAAAAG", "onPictureTaken - wrote to " + outFile.getAbsolutePath());
String filePath = outFile.getPath();
MediaScannerConnection.scanFile(this,
new String[]{filePath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
Toast.makeText(TrendingSlideActivity.this,"Please Wait Image is Loading...",Toast.LENGTH_SHORT).show();
}
}
}
UPDATED ANSWER:
Reason why it isn't working is that you're setting image view inside onPageSelected() , and that method is not called for the first page, it's activated just after swiping.
Solution for this is move the entire code from onPageSelected() into function selectImage(int position) and call that function inside onPageSelected() as
selectImage(i).
This would be an improved version for code above, and will do the same as before, but now it's possible to set default state for the first view by calling
selectImage(0) after viewPager.setCurrentItem(position)

How to save the captured image from camera in the phone memory to check the file size?

I am testing a camera application which captures high quality images. I want the captured image to be saved in the mobile memory (Internal or external) to check the details of the image.
I've the below code for capturing the image.
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Toast;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraLogger;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.SessionType;
import com.otaliastudios.cameraview.Size;
import java.io.File;
public class CameraActivity extends AppCompatActivity implements View.OnClickListener, ControlView.Callback {
private CameraView camera;
private ViewGroup controlPanel;
private boolean mCapturingPicture;
private boolean mCapturingVideo;
// To show stuff in the callback
private Size mCaptureNativeSize;
private long mCaptureTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
setContentView(R.layout.activity_camera);
CameraLogger.setLogLevel(CameraLogger.LEVEL_VERBOSE);
camera = findViewById(R.id.camera);
camera.addCameraListener(new CameraListener() {
public void onCameraOpened(CameraOptions options) { onOpened(); }
public void onPictureTaken(byte[] jpeg) { onPicture(jpeg); }
#Override
public void onVideoTaken(File video) {
super.onVideoTaken(video);
onVideo(video);
}
});
findViewById(R.id.edit).setOnClickListener(this);
findViewById(R.id.capturePhoto).setOnClickListener(this);
findViewById(R.id.captureVideo).setOnClickListener(this);
findViewById(R.id.toggleCamera).setOnClickListener(this);
controlPanel = findViewById(R.id.controls);
ViewGroup group = (ViewGroup) controlPanel.getChildAt(0);
Control[] controls = Control.values();
for (Control control : controls) {
ControlView view = new ControlView(this, control, this);
group.addView(view, ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
controlPanel.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
BottomSheetBehavior b = BottomSheetBehavior.from(controlPanel);
b.setState(BottomSheetBehavior.STATE_HIDDEN);
}
});
}
private void message(String content, boolean important) {
int length = important ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
Toast.makeText(this, content, length).show();
}
private void onOpened() {
ViewGroup group = (ViewGroup) controlPanel.getChildAt(0);
for (int i = 0; i < group.getChildCount(); i++) {
ControlView view = (ControlView) group.getChildAt(i);
view.onCameraOpened(camera);
}
}
private void onPicture(byte[] jpeg) {
mCapturingPicture = false;
long callbackTime = System.currentTimeMillis();
if (mCapturingVideo) {
message("Captured while taking video. Size="+mCaptureNativeSize, false);
return;
}
// This can happen if picture was taken with a gesture.
if (mCaptureTime == 0) mCaptureTime = callbackTime - 300;
if (mCaptureNativeSize == null) mCaptureNativeSize = camera.getPictureSize();
PicturePreviewActivity.setImage(jpeg);
Intent intent = new Intent(CameraActivity.this, PicturePreviewActivity.class);
intent.putExtra("delay", callbackTime - mCaptureTime);
intent.putExtra("nativeWidth", mCaptureNativeSize.getWidth());
intent.putExtra("nativeHeight", mCaptureNativeSize.getHeight());
startActivity(intent);
mCaptureTime = 0;
mCaptureNativeSize = null;
}
private void onVideo(File video) {
mCapturingVideo = false;
Intent intent = new Intent(CameraActivity.this, VideoPreviewActivity.class);
intent.putExtra("video", Uri.fromFile(video));
startActivity(intent);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.edit: edit(); break;
case R.id.capturePhoto: capturePhoto(); break;
case R.id.captureVideo: captureVideo(); break;
case R.id.toggleCamera: toggleCamera(); break;
}
}
#Override
public void onBackPressed() {
BottomSheetBehavior b = BottomSheetBehavior.from(controlPanel);
if (b.getState() != BottomSheetBehavior.STATE_HIDDEN) {
b.setState(BottomSheetBehavior.STATE_HIDDEN);
return;
}
super.onBackPressed();
}
private void edit() {
BottomSheetBehavior b = BottomSheetBehavior.from(controlPanel);
b.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
private void capturePhoto() {
if (mCapturingPicture) return;
mCapturingPicture = true;
mCaptureTime = System.currentTimeMillis();
mCaptureNativeSize = camera.getPictureSize();
message("Capturing picture...", false);
camera.capturePicture();
}
private void captureVideo() {
if (camera.getSessionType() != SessionType.VIDEO) {
message("Can't record video while session type is 'picture'.", false);
return;
}
if (mCapturingPicture || mCapturingVideo) return;
mCapturingVideo = true;
message("Recording for 8 seconds...", true);
camera.startCapturingVideo(null, 8000);
}
private void toggleCamera() {
if (mCapturingPicture) return;
switch (camera.toggleFacing()) {
case BACK:
message("Switched to back camera!", false);
break;
case FRONT:
message("Switched to front camera!", false);
break;
}
}
#Override
public boolean onValueChanged(Control control, Object value, String name) {
if (!camera.isHardwareAccelerated() && (control == Control.WIDTH || control == Control.HEIGHT)) {
if ((Integer) value > 0) {
message("This device does not support hardware acceleration. " +
"In this case you can not change width or height. " +
"The view will act as WRAP_CONTENT by default.", true);
return false;
}
}
control.applyValue(camera, value);
BottomSheetBehavior b = BottomSheetBehavior.from(controlPanel);
b.setState(BottomSheetBehavior.STATE_HIDDEN);
message("Changed " + control.getName() + " to " + name, false);
return true;
}
//region Boilerplate
#Override
protected void onResume() {
super.onResume();
camera.start();
}
#Override
protected void onPause() {
super.onPause();
camera.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
camera.destroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean valid = true;
for (int grantResult : grantResults) {
valid = valid && grantResult == PackageManager.PERMISSION_GRANTED;
}
if (valid && !camera.isStarted()) {
camera.start();
}
}
//endregion
}
I've also added the permissions to read and write the external storage.
But I just want to know the size of the picture once it is saved.
Adding the code to save the image -
public void KickOut(String filename,Bitmap bitmap){
ActivityCompat.requestPermissions(PicturePreviewActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
OutputStream outputStream;
File filepath=Environment.getExternalStorageDirectory();
// File dir=new File(filepath+"/Olaa/");
File dir=new File("/Environment.getExternalStoragePublicDirectory/Imgs/");
dir.mkdirs();
File file=new File(dir,"filename.png");
Toast.makeText(PicturePreviewActivity.this, file + " -> saved" , Toast.LENGTH_SHORT).show();
try{
outputStream=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Toast.makeText(PicturePreviewActivity.this, filepath + " -> path" , Toast.LENGTH_SHORT).show();
}
You can check the size of the captured image you can also save the file in your custom folder.
you can get the result in onActivityResult() and get the image from the bundle and convert it into the byte and lengthbmp_KB will give you size in kb.
if (resultCode == RESULT_OK) {
//Image capture
if (requestCode == 1) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
byte[] imageInByte = bytes.toByteArray();
long lengthbmp = imageInByte.length;
// save on custom folder
File destination1 = createDirectoryAndSaveFile(thumbnail, System.currentTimeMillis() + ".jpg");
/* File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");*/
picturePath = "" + destination1;
// show image on gallery
scanGallery(getActivity(), picturePath);
long lengthbmp_KB = lengthbmp / 1024;
long length_MB = lengthbmp_KB / 1024;
}
you can save the file at your own folder
private File createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/My Images");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/MYfolder Images/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/Myfolder Images/"), fileName);
/* if (file.exists()) {
file.delete();
}*/
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
You can see your images in Gallery by using this MediaScannerConnection
private void scanGallery(Context cntx, String path) {
try {
MediaScannerConnection.scanFile(cntx, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
and use this method in onActivityResult()
To check the size of image saved in phone memory , you could use Bitmapfactory.option
**BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;**
You can use this to save the file provided you've given the permissions in the manifest.
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Take a look at the docs too over here.

Android hide images only from gallery

I have created an application where one can view images. The problem I am facing is that when I use ".nomedia" in folder it hides images from gallery and images are also hidden in my application. I need a method with help of which images can remain hidden from gallery but shown in my application. I am accessing images using path of folder.
Code:
public class SdActivity extends Activity implements
MediaScannerConnectionClient {
public String[] allFiles;
private String SCAN_PATH;
private static final String FILE_TYPE = "*/*";
private MediaScannerConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File folder = new File("/sdcard/DCIM");
allFiles = folder.list();
// uriAllFiles= new Uri[allFiles.length];
for (int i = 0; i < allFiles.length; i++) {
Log.d("all file path" + i, allFiles[i] + allFiles.length);
}
// Uri uri= Uri.fromFile(new
// File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
SCAN_PATH = Environment.getExternalStorageDirectory().toString()
+ "/yourfoldername/" + allFiles[0];
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
Button scanBtn = (Button) findViewById(R.id.buttonLoadPicture);
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startScan();
}
});
}
private void startScan() {
Log.d("Connected", "success" + conn);
if (conn != null) {
conn.disconnect();
}
conn = new MediaScannerConnection(this, this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
Log.d("onMediaScannerConnected", "success" + conn);
conn.scanFile(SCAN_PATH, FILE_TYPE);
}
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted", uri + "success" + conn);
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally {
conn.disconnect();
conn = null;
}
}
}

Converting Activity To Fragment

i want to Convert My Activity To fragment can any One help to Convert Activity to Fragment..i have created Pdf
reader (Click On Button It Will Open Pdf File In Another Activty using pdfviwer.jar library..and I want When I click On Button Pdf Open On Same Screen on Right Side )
i need Help please Solve My Problem
i m posting my Activity
maiinActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn =(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "ABC.pdf");
try
{
in = assetManager.open("ABC.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(getApplicationContext(), MyPdfViewerActivity.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, getFilesDir()+"/ABC.pdf");
startActivity(intent);
/*
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/ABC.pdf"),
"application/pdf");
startActivity(intent);*/
}
});
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
PdfviwerActivty.java
public class MyPdfViewerActivity extends PdfViewerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
}
public int getPreviousPageImageResource() { return R.drawable.left_arrow; }
public int getNextPageImageResource() { return R.drawable.right_arrow; }
public int getZoomInImageResource() { return R.drawable.zoom_in; }
public int getZoomOutImageResource() { return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() { return R.id.etPassword; }
public int getPdfPasswordOkButton() { return R.id.btOK; }
public int getPdfPasswordExitButton() { return R.id.btExit; }
public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }
}
Try "extends FragmentActivity" instead of "extends Activity"..
You should use FragementActivity instead of Activity and paste your ui-components into the fragment's onCreateView()-Method. For further information look at this tutorial: http://www.vogella.com/tutorials/AndroidFragments/article.html

Custom Gallery App does not return to calling App

I'm creating a Fake Camera/Gallery app that just automatically return a random image. I tied it to the ACTION_PICK & IMAGE_CAPTURE intent filters.
However for the Gallery (PICK) code, after calling finish, it doesn't seem to be returning to the calling app.
Here's my code:
public class MainActivity extends Activity {
final static int[] photos = { R.drawable.android_1, R.drawable.android_2,
R.drawable.android_3 };
static int lastPhotoIndex = -1;
private final static String TAG = "FakeCameraGallery";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String action = getIntent().getAction();
if (action.contains("PICK")) {
//Act as Gallery
InputStream in = getResources().openRawResource(getNextPhoto());
Bitmap bm = BitmapFactory.decodeStream(in);
Bundle extras = new Bundle();
extras.putParcelable("data", bm);
Intent result = getIntent().putExtras(extras);
if (getParent() == null) {
setResult(Activity.RESULT_OK, result);
} else {
getParent().setResult(Activity.RESULT_OK, result);
}
} else {
//act as Camera
prepareToSnapPicture();
}
finish();
}
private void prepareToSnapPicture() {
checkSdCard();
Intent intent = getIntent();
if (intent.getExtras() != null) {
snapPicture(intent);
setResult(RESULT_OK);
} else {
Log.i(TAG, "Unable to capture photo. Missing Intent Extras.");
setResult(RESULT_CANCELED);
}
}
private void checkSdCard() {
if (!Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
Toast.makeText(this, "External SD card not mounted",
Toast.LENGTH_LONG).show();
Log.i(TAG, "External SD card not mounted");
}
}
private void snapPicture(Intent intent) {
try {
this.copyFile(getPicturePath(intent));
Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.i(TAG, "Can't copy photo");
e.printStackTrace();
}
}
private File getPicturePath(Intent intent) {
Uri uri = (Uri) intent.getExtras().get(MediaStore.EXTRA_OUTPUT);
return new File(uri.getPath());
}
private void copyFile(File destination) throws IOException {
InputStream in = getResources().openRawResource(getNextPhoto());
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
if (in != null) {
Log.i(TAG, "Input photo stream is null");
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
}
out.close();
}
private int getNextPhoto() {
if (lastPhotoIndex == photos.length - 1) {
lastPhotoIndex = -1;
}
return photos[++lastPhotoIndex];
}
}
Your code looks fine: are you calling it using startActivityForResult?

Categories

Resources