Android Share Intent not working - java

Im trying to share an image, it seems to work only when the SD card is mounted or when the phone doesn't have a SD card slot. But when I dismount the SD card, it wouldn't share and it gives me two errors.
FATAL EXCEPTION: main java.lang.NullPointerException: uriString
Failed to insert image java.io.FileNotFoundException: No such file or directory
And for some reason it also saves the image that is being shared, can't seem to figured out why.
private Button button;
public void onCreate {
init();
setupView();
}
public void setupView(){
button.setOnClickListener(this);
}
public void init() {
button = (Button) findViewById(R.id.button);
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.button: {
startShare();
break;
}
public void startShare() {
Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.m1);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Share"));
}

try this code for share drawable image:
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
getResources().getResourcePackageName(R.drawable.ic_launcher) + '/' +
getResources().getResourceTypeName(R.drawable.ic_launcher) + '/' +
getResources().getResourceEntryName(R.drawable.ic_launcher));
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Share"));

Related

How to play recorded video in another Activity by passing in intent in android studio?

I am recording a video and passing its path into VideoView Activity. But the video can't be opened. Can anyone please help?
RecordActivity - video path function-:
public static String getVideoFilePath() {
return getAndroidMoviesFolder().getAbsolutePath() + "/" + new SimpleDateFormat("yyyyMM_dd-HHmmss").format(new Date()) + "rangeela.mp4";
}
Its returning ->
file:///storage/emulated/0/DCIM/202209_02-231740rangeela.mp4
File mediaFile = new File(getVideoFilePath());
Uri uri= Uri.fromFile(mediaFile);
Intent intent=new Intent(this,VideoEditorActivity.class);
intent.putExtra("uri",uri.toString());
startActivity(intent);
VideoViewActivity
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
Uri uri=Uri.parse(bundle.getString("uri"));
Log.e("video path = ", String.valueOf(uri));
binding.videoView.setVideoURI(uri);
binding.videoView.start();
}
But I am getting an error
Can't play this video
How to pass the recorded video in intent and play in another activity?
Try this
String path = getAndroidMoviesFolder().getAbsolutePath() + "/" + new SimpleDateFormat("yyyyMM_dd-HHmmss").format(new Date()) + "rangeela.mp4";
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this,VideoEditorActivity.class);
intent.putExtra("video",path);
}
});
VideoViewActivity
VideoView view = findViewById(R.id.videoview);
String path = getIntent().getStringExtra("video");
view.setVideoPath(path);
view.start();

"file:///storage/emulated/0/screenshot.png exposed beyond app through ClipData.Item.getUri()"

I'm trying to set up a share button on my app. The button is supposed to take a screenshot of a particular list view, and then allow the user to share this image via whatever means they want. To do this, I created three methods:
Take the screenshot
Save it in my storage
Share it to the user.
To do this I've written the following code:
public class ViewPlayerHistoryContents extends AppCompatActivity {
public static File imagePath;
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void shareIt() {
Uri uri = Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "In Tweecher, My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_player_history);
shareButton = findViewById(R.id.shareButton);
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
shareIt();
}
});
}
}
With this code I keep getting the following error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.transfergame, PID: 18477
android.os.FileUriExposedException: file:///storage/emulated/0/screenshot.png exposed beyond app through ClipData.Item.getUri()
Which to me sounds like it's because I'm using Uri and not FileProvider?
How should I be incorporating FileProvider in this?
I added the following permissions to my Android manifest file, but it hasn't done anything:
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
How can I fix this error?
Thanks everyone
You can go through this
You have add provider in android manifest and also create the a File Provider in xml/provider.xml as the answer in thus link suggests.
public void captureImage() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
activity.startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

How can I share images from an Array that uses ImageView feature?

I have a doubt.
How can I share images from an Array that uses ImageView feature?
My array has more than 100 images, an example:
Final int [] photos = {
R.drawable.abrir_a_boca,
R.drawable.rooms,
R.drawable.firmly,
R.drawable.agradeca,
R.drawable.alfaiate,
R.drawable.ancora,
}
To share I'm trying to use Intent.ACTION_SEND
Set.setOnClickListener (new View.OnClickListener () {
#Override
Public void onClick (View v)
{
Intent sharingIntent = new Intent (Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse (photos???);
SharingIntent.setType ("image / *");
SharingIntent.putExtra (Intent.EXTRA_STREAM, screenshotUri);
StartActivity (Intent.createChooser (sharingIntent, "Share image using"));
}
});
How can I share the images?
Thank you so much!!!
You have to do some operations before you share your image, so add the permission in your Manifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Fist, create a Bitmap object from your drawable resource:
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.xxxx);
Then, get the path for you share your image
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/yourImage.jpg";
OutputStream out = null;
File file=new File(path);
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path=file.getPath();
Uri uri = Uri.parse("file://"+path);
And finally, create your intent:
Intent intent = new Intent();
intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/jpg");
startActivity(Intent.createChooser(intent,"Share with..."));

Android. Crop images from Gallery

In my app i'm trying to crop images. I find some code that can crop images when a'm taking photo from camera, but i can't crop photos from gallery, cause:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=0, data=null} to activity {....MainActivity}: java.lang.NullPointerException "
in this line: Bundle extras = data.getExtras();
This is myActivity's code:
public class MainActivity extends Activity {
ImageView imVCature_pic;
Button btnCapture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeControls();
}
private void initializeControls() {
imVCature_pic=(ImageView)findViewById(R.id.imVCature_pic);
btnCapture=(Button)findViewById(R.id.btnCapture);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
/*create instance of File with name img.jpg*/
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img.jpg");
/*put uri as extra in intent object*/
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
/*start activity for result pass intent as argument and request code */
startActivityForResult(intent, 1);
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2 = new Intent();
intent2.setType("image/*");
intent2.setAction(Intent.ACTION_GET_CONTENT);
File file2 = new File(Environment.getExternalStorageDirectory() + File.separator + "img2.jpg");
/*put uri as extra in intent object*/
intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file2));
/*start activity for result pass intent as argument and request code */
startActivityForResult(intent2, 3);
}} );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if request code is same we pass as argument in startActivityForResult
if(requestCode==1){
//create instance of File with same name we created before to get image from storage
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
//Crop the captured image using an other intent
try {
/*the user's device may not support cropping*/
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
//display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
if(requestCode==2){
//Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
//set image bitmap to image view
imVCature_pic.setImageBitmap(thePic);
}
if(requestCode==3){
//create instance of File with same name we created before to get image from storage
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
//Crop the captured image using an other intent
try {
/*the user's device may not support cropping*/
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
//display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
//create helping method cropCapturedImage(Uri picUri)
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 256);
cropIntent.putExtra("aspectY", 256);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 2);
}
Where's a mistake?

Avoiding FAILED BINDER TRANSACTION error using intent

In my costum camera app I need to transfer a bitmap and a Uri from one activity to another. For some reason I'm getting the FAILED BINDER TRANSACTION error on most phones(I get the error on newer phones but don't on Nexus4 and Galaxy3). I get the same error even when I only try to transfer the Bitmap through an intent(I also tried transfering only the Uri and got the error). From what I've read online the error comes from a memory problem but I don't know how to fix it. I would appreciate any kind of help.
My first Activity:
...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
tv.setVisibility(View.INVISIBLE);
btn.setVisibility(View.INVISIBLE);
selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
ok.setVisibility(View.VISIBLE);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==btn.getId())
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
if(v.getId()==ok.getId())
{
String stringUri;
stringUri = selectedImageUri.toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent .setClass(MainActivity.this, SecondMain.class);
intent .putExtra("KEY", stringUri);
startActivity(intent );
}
}
}
Second Activity:
public static Camera isCameraAvailiable(){
Camera object = null;
try {
object = Camera.open();// attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return object; // returns null if camera is unavailable
}
private Camera.PictureCallback capturedIt = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if(bitmap==null){
Toast.makeText(getApplicationContext(), "not taken", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "taken", Toast.LENGTH_SHORT).show();
}
cameraObject.release();
}
};
...
String stringUri = null;
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("KEY")) {
stringUri= extras.getString("KEY");
}
selectedImageUri = Uri.parse(extras.getString("KEY"));
float alpha=(float)1/2;
img.setAlpha(alpha);
img.setImageURI(selectedImageUri);
cameraObject = isCameraAvailiable();
showCamera = new ShowCamera(this, cameraObject);
frame.addView(showCamera);
}
public void snapIt(View view){
redo.setVisibility(View.VISIBLE);
ok.setVisibility(View.VISIBLE);
snap.setVisibility(View.INVISIBLE);
cameraObject.takePicture(null, null, capturedIt);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==ok.getId())
{
Intent intent = new Intent(SecondMain.this, Blend.class);
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]byteArray=stream.toByteArray();
intent.putExtra("image", byteArray);
String stringUri;
stringUri = selectedImageUri.toString();
intent .putExtra("KEY", stringUri);
startActivity(intent);
It is not a memory problem, it's a problem with transferring your image with your intent. You see, Bundle has a limit of how much data it can transfer from one end to the other, currently it's only 1MB. You will problems on all modern phones with a decent camera, as the image exceeds 1MB limit, some old phones with low end camera will work. You need to rethink on how you are going to be transfering the image.
You can
Save it to a file first, send the only the path to it (that's how selecting an image from the gallery works)
Save it to SQL and retrive it on the other end
Make a hodler class with a static variable of image (the most simple)
Make a custom class of Application and put it there for the time being.
Downscale and compress the image before it's transferred

Categories

Resources