java.lang.RuntimeException: Unable to resume activity {packagename.classname}: - android

I am trying to use camera class in my app. I just want to click a picture and set on the imageview and then posting it on some url. Posting on url working fine but sometime problem occurs while clicking any picture and resuming back to same activity from where I am navigating to camera app. It works fine on HTC wildfire (2.2 version) but sometime gives exception (failure chance 1/25) but when i test it on Sony xperia miro or samsung tab (4.0 version) it gives same exception many times (failure chance 20/25). I am not getting where the problem exists because sometimes app runs smoothly without any exception but with 4.0 or above version it force closes many times but sometime works fine on it.
Exception is : java.lang.RuntimeException: Unable to resume activity {fable.eventippo/fable.eventippo.EventsIppoPaymentActivity}:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=tabHome, request=1, result=-1, data=Intent
{ dat=content://media/external/images/media/17271 }} to activity {fable.eventippo/fable.eventippo.EventsIppoPaymentActivity}:
java.lang.ClassCastException: fable.eventippo.Home cannot be cast to fable.eventippo.AddEvent
Complete code is given here.
Button Onclick.
browse = (Button) findViewById(R.id.browse);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] items = { "Camera", "Gallery" };
AlertDialog.Builder builder = new AlertDialog.Builder(
getParent());
builder.setTitle("Browse From");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item] == "Camera") {
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT,
MyFileContentProviders.CONTENT_URI);
getParent().startActivityForResult(i,
CAMERA_REQUEST);
} else {
Toast.makeText(getParent(),
"Camera is not available",
Toast.LENGTH_LONG).show();
}
} else if (items[item] == "Gallery") {
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
getParent().startActivityForResult(
Intent.createChooser(intent,
"Select Picture"), PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getParent(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
On Activity Result:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bundle bn = data.getExtras();
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filepath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
// logo.setImageURI(selectedImageUri);
if (selectedImagePath != null) {
filepath = selectedImagePath;
} else if (filemanagerstring != null) {
filepath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filepath != null) {
// /upload.setText(filepath);
decodeFile(filepath);
} else {
// filePath = null;
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
case CAMERA_REQUEST:
if (resultCode == Activity.RESULT_OK) {
File out = new File(getFilesDir(), "newImage.jpg");
if (!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
String filepath = out.getAbsolutePath().toString();
decodeFile(filepath);
}
break;
default:
}
Complete Exception is shown on following image
If you need anything more please tell me.
Thanks in Advance
Waiting for answer

Takepicture Button onClickListener:
TakePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyPic-"+ System.currentTimeMillis() + ".jpg");
SelectedImage = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, SelectedImage);
startActivityForResult(intent,CAMERA_PIC_REQUEST);
}
});
Select From Gallery Button onClickListener:
SelectfromGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), RESULT_LOAD_IMAGE);
}
});
onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
SelectedImage = data.getData();
String filePath = null;
try {
// IO FILE Manager
String filemanagerstring = SelectedImage.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(SelectedImage);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
FROM_GALLERY = true;
} catch (Exception e) {
Log.e("Uploaderror", e.getLocalizedMessage());
}
}
else if(requestCode==CAMERA_PIC_REQUEST && resultCode == RESULT_OK){
/*//SelectedImage = data.getData();
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ProfilePic.setImageBitmap(thumbnail);*/
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = SelectedImage.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(SelectedImage);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
FROM_GALLERY = false;
} else {
bitmap = null;
}
} catch (Exception e) {
Log.e("error:", e.getLocalizedMessage());
}
}
else if (resultCode == Activity.RESULT_CANCELED)
{
Log.e("STATUS:", "Selecting picture cancelled");
}
}
decodeFile method:
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
ProfilePic.setImageBitmap(bitmap);
}
here you go. My complete code to achieve that objective. I couldn't do thorough testing as i had limited devices. So, can't say for sure that this would work on all devices. if you find out a solution for your issue or if this code works then let me know. Thanks. Happy coding.

Related

issue regarding converting image to Base64 image

This is Image feathing method
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(AddServiceActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 100);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 10);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
This is OnActivityResult code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (data.getData() != null) {
selectedImageUri = data.getData();
} else {
Log.d("selectedPath1 : ", "Came here its null !");
Toast.makeText(getApplicationContext(), "failed to get Image!", Toast.LENGTH_SHORT).show();
}
if (requestCode == 100 && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
selectedPath = getPath(selectedImageUri);
camera.setImageURI(selectedImageUri);
Log.d("selectedPath1 : ", selectedPath);
getimage(selectedImageUri);
}
if (requestCode == 10)
{
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from ", picturePath + "");
camera.setImageBitmap(thumbnail);
getimage(selectedImage);
}
}
}
Image changing code id here
private void getimage(final Uri uri) {
Bitmap image = null;
WeakReference<Bitmap> weakReference = new WeakReference<Bitmap>(new BitmapDrawable(getResources(), uri.getPath()).getBitmap());
int nh = (int) (weakReference.get().getHeight() * (512.0 / weakReference.get().getWidth()));
image = Bitmap.createScaledBitmap(weakReference.get(), 512, nh, true);
Log.e("", "bitmap size is2:" + "" + nh + ":" + image.getByteCount());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.e("", "encoded::" + encoded);
Log.d("", "encoded::" + encoded);
// user_imagebase64 = encoded;
try {
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
the code is crashes in getimage method all time, when i call this method the app crashes at line
"int nh = (int) (weakReference.get().getHeight() * (512.0 / weakReference.get().getWidth()));"
and having error of Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getHeight()' on a null object reference
i dont know what the issue is and i can't use this code too..

unable to decode stream while selecting an image

While selecting an image from a gallery in my application it doesn't crash but instead its unable to decode the stream of the path. Taking the picture directly from the camera is working fine but from the gallery its not here is my code in my activity result .
//enter code here
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImageUri = null;
String filePath = null;
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK)
{
selectedImageUri = data.getData();
name = getPath(selectedImageUri);
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = imageUri;
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
if(selectedImageUri != null)
{
try
{
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null)
{
decodeFile(filePath);
} else {
bitmap = null;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri)
{
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
public void decodeFile(String filePath)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
//imgView.setImageBitmap(bitmap);
}
any help would be appreciated.
In later versions of Android (KitKat and above), the format of Uris returned from the gallery picker has changed, and it's not always possible to get a file path from a Uri without a lot of hassle, and sometimes it's not possible at all. So, it's better just to decode the bitmap using the Uri directly.
Change your decodeFile() function to accept a Uri and decode the image using BitmapFactory.decodeStream(), like this:
public void decodeFile(Uri fileUri)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri), null, o2);
//imgView.setImageBitmap(bitmap);
}
Then you can simplify your onActivityResult() code to this:
if(selectedImageUri != null)
{
try
{
decodeFile(selectedImageUri);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
If you have problems obtaining a valid Uri, see the accepted answer for this question for how to obtain a Uri inside OnActivityResult() with correct permissions on KitKat and above.
Well I choose another approach for this thing. You cannot diffrentiate between you chose a picture from gallery or from a Camera Intent.
Here is my code.
public class Chooser extends Activity {
ImageView imageView1;
private Uri outputFileUri;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
imageView1 = (ImageView) this.findViewById (R.id.imageView1);
Button frag1 = (Button) this.findViewById (R.id.frag1);
frag1.setOnClickListener (new OnClickListener () {
#Override
public void onClick (View v) {
choosePic (null);
}
});
}
public void choosePic (View view) {
// Determine Uri of camera image to save.
final File root = new File (Environment.getExternalStorageDirectory () + File.separator + "DCIM/Camera" + File.separator);
root.mkdirs ();
final String fname = "image_" + getRandomName () + ".jpeg";
final File sdImageMainDirectory = new File (root, fname);
outputFileUri = Uri.fromFile (sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent> ();
final Intent captureIntent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra (MediaStore.EXTRA_OUTPUT, Uri.fromFile (sdImageMainDirectory));
final PackageManager packageManager = getPackageManager ();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities (captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent (captureIntent);
intent.setComponent (new ComponentName (res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage (packageName);
intent.putExtra (MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add (intent);
}
// Filesystem.
final Intent galleryIntent = new Intent ();
galleryIntent.setType ("image/*");
galleryIntent.setAction (Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser (galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra (Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray (new Parcelable[] {}));
startActivityForResult (chooserIntent, 1);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult (requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
final boolean isCamera;
if (data == null) {
isCamera = true;
}
else {
final String action = data.getAction ();
if (action == null) {
isCamera = false;
}
else {
isCamera = action.equals (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
}
else {
selectedImageUri = data == null ? null : data.getData ();
}
imageView1.setImageURI (selectedImageUri);
}
}
}
public String getRandomName () {
Random r = new Random (); // just create one and keep it around
String alphabet = "abcdefghijklmnopqrstuvwxyz1234567890";
final int N = 10;
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < N; i++) {
sb.append (alphabet.charAt (r.nextInt (alphabet.length ())));
}
return sb.toString ();
}

How to send image to FTP Client in android?

I am developing an android application in that i need to send my image to the Specific FTP URL address can any one help me how can I do that please.
URL is:
http://demo1.idevtechnolabs.com/RChatAPI/usrPhotos/
And My Code is:
public class ImageGallery extends Activity
{
private static final int PICK_IMAGE = 1;
private static final int PICK_Camera_IMAGE = 2;
private ImageView imgView;
private Button upload,cancel;
private Bitmap bitmap;
private ProgressDialog dialog;
Uri imageUri;
Uri selectedImageUri = null;
String filePath = null;
MediaPlayer mp=new MediaPlayer();
Handler progressHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.imguploadbtn);
cancel = (Button) findViewById(R.id.imgcancelbtn);
upload.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (bitmap == null)
{
Toast.makeText(getApplicationContext(),"Please select image", Toast.LENGTH_SHORT).show();
}
else
{
dialog = ProgressDialog.show(ImageGallery.this, "Uploading","Please wait...", true);
new ImageGalleryTask().execute();
}
}
});
cancel.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
ImageGallery.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_image_gallery, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.camera:
String fileName = "new-photo-name.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
return true;
case R.id.gallery:
try
{
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gintent, "Select Picture"),PICK_IMAGE);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return true;
}
return false;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK)
{
selectedImageUri = data.getData();
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK)
{
//use imageUri here to access the image
selectedImageUri = imageUri;
/*Bitmap mPic = (Bitmap) data.getExtras().get("data");
selectedImageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mPic, getResources().getString(R.string.app_name), Long.toString(System.currentTimeMillis())));*/
}
else if (resultCode == RESULT_CANCELED)
{
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
if(selectedImageUri != null)
{
try
{
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null)
{
filePath = selectedImagePath;
}
else if (filemanagerstring != null)
{
filePath = filemanagerstring;
}
else
{
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null)
{
decodeFile(filePath);
}
else
{
bitmap = null;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
class ImageGalleryTask extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... unsued)
{
FTPClient ftpClient = new FTPClient();
try
{
ftpClient.connect(InetAddress.getByName("My URL Address"));
ftpClient.login("My Username", "My Password");
ftpClient.changeWorkingDirectory("My Path of URL");
if (ftpClient.getReplyString().contains("250"))
{
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn = null;
String path=selectedImageUri.toString();
Log.v("Image Path:",filePath);
buffIn = new BufferedInputStream(new FileInputStream(filePath));
ftpClient.enterLocalPassiveMode();
ProgressInputStream progressInput = new ProgressInputStream(buffIn, progressHandler);
boolean result=ftpClient.storeUniqueFile(progressInput);
boolean result = ftpClient.storeFile(localAsset.getFileName(), progressInput);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
}
}
catch (Exception e)
{
Log.d("Error in ftp:",e.toString());
}
return "Success";
}
#Override
protected void onProgressUpdate(Void... unsued)
{
}
#Override
protected void onPostExecute(String sResponse)
{
try
{
if (dialog.isShowing())
dialog.dismiss();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null)
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else
return null;
}
public void decodeFile(String filePath)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
imgView.setImageBitmap(bitmap);
}
}
When I use this code and click on upload button
I got the following error:
Could not find class 'org.apache.commons.net.ftp.FTPClient', referenced from method com.androidmyway.demo.imagedemo.ImageGallery$ImageGalleryTask.doInBackground
Try using this simple example to upload any file over webserver from here.
You have to add a dependency for using FTPClient class. You can find it easily on anywhere. it is "commons apache" named dependency.

How to upload multiple images in multiple buttons in android

I have two buttons and two imageview. When I click on first button, it opens and uploads image.How to do for second button click and load image. My code is as follows
private static final int PICK_IMAGE = 1;
upload1=(Button)findViewById(R.id.uploadimage1);
upload2=(Button)findViewById(R.id.uploadimage2);
imgView1=(ImageView)findViewById(R.id.image1);
imgView2=(ImageView)findViewById(R.id.image2);
upload1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"No image found", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
//first image i have uploaded by using first button
imgView1.setImageBitmap(bitmap);
}
Now my question is for second button how to upload in second image. Please help me to solve this issue. Thanks in advance
private static final int PICK_IMAGE = 1;
private static final int PICK_IMAGE_2 = 2;
set click listener for upload2. Then in OnClick()
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE_2);
Finally, In onActivityResult()
case PICK_IMAGE :
imgView1.setImageBitmap(bitmap);
break;
CASE PICK_IMAGE :
imgView2.setImageBitmap(bitmap);
break;
You can simply repeat what you did for the first button, but with a different request code, so you know how to use the data in onActivityResult :
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_2);
}

Select Image From gallery and save it for future use

I am working on application and i want that the user can select images from gallery so that he can apply frames on it. I am successful in accessing mobile gallery, now i want to know how to save the selected image for further processing. The selected image will be used to apply frame on it.
Use the following code for selecting image from gallery :
Intent intent=new Intent();
intent.setType=("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE);
/*Declare PICK_IMAGE globally : private static final int PICK_IMAGE = 1; */
Actual Code starts Here
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
Log.e("file path ","file path "+filePath);
GlobalValues.camefromtw="true";
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
Log.e("result code","result code"+resultCode+" result "+Activity.RESULT_OK);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
Image is recieved in filepath now you can use it ,Here in this code i am using thi sto set ImageView
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
image.setImageBitmap(bitmap);
}
First add this :
ImageView profile;
Bitmap bmp;
SharedPreferences sp;
public static final int PERMISSION_REQUEST_CAMERA = 1;
private static final int PICK_FROM_GALLERY = 1;
Then in onCreate method add these lines of code :
sp=getSharedPreferences("profilePicture",MODE_PRIVATE);
profile=(ImageView)findViewById(R.id.profile);
if(!sp.getString("dp","").equals("")){
byte[] decodedString = Base64.decode(sp.getString("dp", ""), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
profile.setImageBitmap(decodedByte);
}
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
Then add these function openGallery() :
private void openGallery() {
if (ActivityCompat.checkSelfPermission(ProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ProfileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
}else {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
}
Then add this , onRequestPermissionsResult() :
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults)
{
switch (requestCode) {
case PICK_FROM_GALLERY:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
} else {
Toast.makeText(ProfileActivity.this,"Not working",Toast.LENGTH_LONG).show();
//do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
break;
}
}
onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try { // When an Image is picked
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
bmp = BitmapFactory
.decodeFile(imgDecodableString);
profile.setImageBitmap(bmp);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
sp.edit().putString("dp", encodedImage).commit();
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(ProfileActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(ProfileActivity.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
Don't forget to give permission in Manifest file.

Categories

Resources