Failed to pass image to another class - java

I'm trying to pass an image to another class through intent, but it only works for captured image, not for image selected from gallery.
This is where the camera function get started.In ImageFitScreen.java, it has a ok button used to return back to the previous activity.
ImageFitScreen.java
public void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(ImageFitScreen.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 intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
//pic = f;
// Toast.makeText(getApplicationContext(), Uri.fromFile(f) +"", Toast.LENGTH_LONG).show();
startActivityForResult(intent, 1);
} 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, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
finish();
}
}
});
builder.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK){
dialog.dismiss();
finish();
}
return true;
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
//h=0;
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
//pic = photo;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOptions.inDither = true;
bitmapOptions.inSampleSize=8;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
Global.img = bitmap;
b.setImageBitmap(bitmap);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
//p = path;
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
//pic=file;
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
// h=1;
//imgui = selectedImage;
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 ******", picturePath + "");
b.setImageBitmap(thumbnail);
}
}
else
{
finish();
}
ok.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Previous Activity
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); // image can be displayed
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
b.setOnClickListener(new View.OnClickListener() { // save button
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
returnIntent.putExtra("c",c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
**The image can be returned to Previous Activity ** since it can display in viewImage. In previous activity, it also has a button back to Activity A.
Activity A
c = (TextView) claims.findViewById(R.id.textView49);
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((name != null && name.trim().length() > 0) && (result != null && result.trim().length() > 0)) {
Toast.makeText(getActivity().getApplicationContext(), "not null", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), EditClaims.class);
intent.putExtra("name", name);
intent.putExtra("result", result);
intent.putExtra("description", description);
byte[]data=getBitmapAsByte(getActivity(), Global.img);
intent.putExtra("data",data);
startActivity(intent);
}
else {
Toast.makeText(getActivity().getApplicationContext(), "null", Toast.LENGTH_LONG).show();
}
}
} );
public static byte[]getBitmapAsByte(final Context context,Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, outputStream);
return outputStream.toByteArray();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
int button = data.getIntExtra("k1", 0);
if (button == 1) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description=data.getStringExtra("c");
if (Global.img != null) {
v.setImageBitmap(Global.img);
}
as=Long.parseLong(result);
c.setText(" " + name + "------" + "RM " + result);
break;
}
}
else if(requestCode==CAMERA_REQUEST_CODE)
{
}
Activity B (Activity)
if(getIntent().hasExtra("data")) {
// ImageView previewThumbnail = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("data"),0,getIntent().getByteArrayExtra("data").length);
viewImage.setImageBitmap(b);
}
Global.java
public class Global {
static Bitmap img;
}
When it intent to Activity B, my app will exit automatically. But it will works if the image is captured image. Is it because the size too large? I have no ide on this.Can someone help me? Thanks a lot!

You shouldn't put bitmap into Bundle. The best way is saving image on storage and pass path uri between activities.

byte [] recieve = getIntent().getByteArrayExtra("key",defaultValue);

Related

Upload a photo from camera or gallery in android

Having the following error:
android.os.FileUriExposedException: file:///storage/emulated/0/temp.jpg exposed beyond app through ClipData.Item.getUri()
when I choose Option Camera from chosen AlertDialog
And the following error when I try to choose a photo from Gallery:
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0 (Is a directory)
The Gallery opens up, but I can't choose an image to set it to my ImageView
Here is the code:
public class MainActivity extends AppCompatActivity {
private Button contactsButton, galleryButton;
public static final int Gallery_Code = 100;
public static final int Contacts_Code = 101;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsButton = findViewById(R.id.buttonContacts);
galleryButton = findViewById(R.id.buttonGallery);
imageView = findViewById(R.id.imageView);
contactsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkPermission(Manifest.permission.READ_CONTACTS, Contacts_Code);
}
});
galleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
}
private void uploadImage() {
final String[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Upload Photo");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 1);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
File[] files = f.listFiles();
if (files != null) {
for (File temp : files) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
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));
imageView.setImageBitmap(thumbnail);
}
}
}
private void checkPermission(String readContacts, int contacts_code) {
if (ContextCompat.checkSelfPermission(MainActivity.this, readContacts)
== PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{readContacts},
contacts_code);
} else {
Toast.makeText(MainActivity.this,
"Permission already granted",
Toast.LENGTH_SHORT)
.show();
if (contacts_code == Contacts_Code) {
Intent i = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(i);
} else {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super
.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
if (requestCode == Gallery_Code) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Gallery Permission Granted",
Toast.LENGTH_SHORT)
.show();
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 1);
} else {
Toast.makeText(MainActivity.this,
"Gallery Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == Contacts_Code) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Contacts Permission Granted",
Toast.LENGTH_SHORT)
.show();
Intent i = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(i);
} else {
Toast.makeText(MainActivity.this,
"Contacts Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
}
} }

image taken from gallery is unable to set in image view

I am taking image from camera as well as from gallery,after getting the image, I want to show the image in imageview.
Image that is captured by camera successfully is shown in imageview but when I want to select it from gallery it does not show the image and it also does not show any error. It was working properly but later I add camera feature in activity, it's not working well.
public class DoReport extends AppCompatActivity {
private EditText subject,detail;
private ImageView pic;
private ImageView iv;
private Spinner depart;
private String depat,sub,det;
//for image
private Bitmap selectedImage;
public static String image;
private Uri imageUri;
public final static int PHOTO_FROM_MEMORY_REQUESTED = 10;
static final int REQUEST_IMAGE_CAPTURE = 1;
String userChoosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_do_report);
subject = (EditText) findViewById(R.id.subject);
detail = (EditText) findViewById(R.id.detail);
depart = (Spinner) findViewById(R.id.Depat_Edit);
iv=(ImageView)findViewById(R.id.ImgView);
}
public void onBackClick(View v) {
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
//to pic the image from galery
//this is new <code>
public void imgBtn(View v) {
selectImage();
}
private void updateSelectedPicture(Uri uri) {
try {
imageUri = uri;
InputStream imageStream = getContentResolver().openInputStream(imageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
iv.setImageDrawable(new BitmapDrawable(selectedImage));
image=encode(selectedImage);
} catch(FileNotFoundException ex) {
Log.e("File not found", "Cannot find background file under received URI");
}
}
public static String encode(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public void submit(View v) {
depat=depart.getSelectedItem().toString();
sub=subject.getText().toString();
det=detail.getText().toString();
if(sub.isEmpty()) {
subject.setError("subject is required");
} else if(det.isEmpty()) {
detail.setError("subject is required");
} else {
login_database(depat, sub, det, image);
}
}
private void login_database(final String depat, final String sub,final String det,final String pic) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, Static.user_connect,//changes required
new Response.Listener<String>() {
public void onResponse(String response) {
if ((response.contains("successful"))) {
Toast.makeText(DoReport.this, "Successful Submitted",Toast.LENGTH_LONG).show();
Intent i = new Intent (DoReport.this,UserView.class);
startActivity(i);
finish();
} else {
Toast.makeText(DoReport.this, "Some error occured", Toast.LENGTH_LONG).show();//changes required
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DoReport.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.d("ERROR", toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("key", "3");//changes required
map.put("Depat", depat);
map.put("Detail", det);
map.put("Pic", pic);
map.put("Subject", sub);
map.put("U_id",Static.id);
return map;
}
};
queue.add(request);
}
/*//////////////////////////////////////////////////////////////////////////////////////////
code for selecting image from camera or gallery
*////////////////////////////////////////////////////////////////////////////////////////
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
}
///////////////it will show the dialogue box
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(DoReport.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(DoReport.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
dispatchTakePictureIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
gallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void gallery() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PHOTO_FROM_MEMORY_REQUESTED);
}
}
only change onActivityResult method remove else if block form id condition like below code...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
selectedImage = BitmapFactory.decodeStream(imageStream);
You should check if selectedImage -the bitmap- is null.
I bet selectedImage==null.
This happens if the bitmap would become too big for available memory.
You should scale it down while loading from stream.
Remember: from the camera you only obtain a thumbnail. Thats the difference.
Here's my code to set a rounding photo from gallery or camera into ImageButton and it works perfectly :
public class EditProfileActivity extends AppCompatActivity {
ImageButton btnValidate,btnCancel,imgProfile;
TextView tvEditPhoto;
RoundImage roundedImage;
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnCancel = findViewById(R.id.toolbar_back_btn);
btnValidate = findViewById(R.id.toolbar_validate_btn);
imgProfile = findViewById(R.id.user_profile_photo_edit);
tvEditPhoto = findViewById(R.id.user_profile_name_edit);
//Rounding image
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.profile);
roundedImage = new RoundImage(bm);
imgProfile.setImageDrawable(roundedImage);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
btnValidate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
imgProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
tvEditPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PictureUtility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
Toast.makeText(EditProfileActivity.this, "Oups ! vous n'avez pas la permission.", Toast.LENGTH_LONG).show();
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= PictureUtility.checkPermission(EditProfileActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//resize picture
Bitmap bmw = Bitmap.createScaledBitmap(thumbnail, 120, 120, false);
//rounding picture
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap bmw = Bitmap.createScaledBitmap(bm, 120, 120, false);
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
}
In your code, try to add createScaledBitmap to resize your photo like this:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//add this line and use the new bitmap resized
Bitmap imageBitmapResized = Bitmap.createScaledBitmap(imageBitmap , 120, 120, false);
iv.setImageBitmap(imageBitmapResized );
image = encode(imageBitmapResized );//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}

Android - Cannot resolve method 'onActivityResult(int, int, android.content.Intent)

I need to set/add a photo/movie as an attachment to ToDo App.
Unfortunately the word: onActivityResult in line super.onActivityResult(requestCode, resultCode, data); is highlighted in red and i'm getting an error:
"Cannot resolve method 'onActivityResult(int, int, android.content.Intent)' "
AddActivity.java
Button button_z = (Button) findViewById(R.id.button_z);
button_z.setonclickListener(new View.onclickListener() {
#Override
public void onclick(View view2) {
selectImage();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
90, bytes);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(thumbnail);
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(AddActivity.this, selectedImageUri, projection, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
imageView.setImageBitmap(bm);
}
}
private void selectImage() {
final CharSequence[] items = { "Zrób zdjęcie lub nagranie", "Wybierz istniejące", "Anuluj" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddActivity.this);
builder.setTitle("Dodaj załącznik");
builder.setItems(items, new DialogInterface.onclickListener() {
#Override
public void onclick(DialogInterface dialog, int item) {
if (items[item].equals("Zrób zdjęcie lub nagranie")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Wybierz istniejące")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Wybierz plik"),
SELECT_FILE);
} else if (items[item].equals("Anuluj")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
You are missing ); in your code.
Button button_z = (Button) findViewById(R.id.button_z);
button_z.setonclickListener(new View.onclickListener() {
#Override
public void onclick(View view2) {
selectImage();
}
}); //here

Cannot take picture or choose image from gallery

Sorry guys, I'm very new to android and now need to create a simple camera in my android studio.
When I choose an image from gallery or take a picture, it will crashed.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.camera_main, container, false);
b=(Button)claims.findViewById(R.id.btnSelectPhoto);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
return claims;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Claims.this.getActivity());
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 intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
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, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity. RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().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 ", picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
LogCat Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=2, result=-1, data=Intent { dat=content://com.sec.android.gallery3d.provider/picasa/item/5843197728949359042 (has extras) }} to activity {com.example.project.project/com.example.project.project.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3752)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3795)
Can someone explain to me why would this happen and how to fix it?
Thanks a lot :)
you can using this method
public class MainActivity extends AppCompatActivity {
private static final int IMAGE_REQUEST_CODE = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private static final String IMG_FILE_NAME = "tempImg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// From Gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), IMAGE_REQUEST_CODE);
// Take a Picture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(GetOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public static File GetOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory() + "/" + HConstants.IMG_FILE_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ IMG_FILE_NAME + ".jpg");
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == IMAGE_REQUEST_CODE){
fileUri = data.getData();
Log.i(getClass().getName(), "fileUri" + fileUri);
}else{
Log.i(getClass().getName(), fileUri);
}
}
}
}
Getting Image from Gallery.
Try the following code.Hopefully it will work
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#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) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
Taking Picture
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
Also add the permissions in Manifest File:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Android image is not uploading in ftp server

Uploading image from android phone to Ftp server, It is not uploading my image into Ftp server it shows windows leaked error,it shows sdcard path but the image is not uploading into the ftp folder can anyone please help me.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivImage = (ImageView) findViewById(R.id.ivImage);
btnSetImage = (Button) findViewById(R.id.btnSelectPhoto);
upload = (Button) findViewById(R.id.upload_btn);
btnSetImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Uploading",
"Please wait...", true);
dialog.setCancelable(true);
//File f = new File("file:///android_asset/launcher.png");
// Log.i("do in image ", tempPath);
new doFileUpload().execute();
}
});
}
class doFileUpload extends AsyncTask<Void, Void, String> {
// Log.i("do in image ", path);
String hostName = "xxxxx";
String username = "dsdadg";
String password = "adasdh";
InputStream in = null;
protected String doInBackground(Void... unsued) {
String loc = tempPath.toString();
Log.i("location in async ", loc);
try {
FTPClient ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory("/ftp/gallery/"); // FTP folder path
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Success");
}
File f1 = new File("/sdcard/Image/003.JPG");
in = new FileInputStream(f1);
ftp.storeFile("/ftp/gallery/", in);
ftp.enterLocalPassiveMode();
System.out.println("SUCCESS");
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return hostName;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
ivImage.setImageBitmap(bm);
path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
tempPath = getPath(selectedImageUri, MainActivity.this);
Log.i("temporary path", tempPath);
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
ivImage.setImageBitmap(bm);
}
}
//return urlPosting;
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}

Categories

Resources