Sharing an Image - android

When I click the share button, it opens and shows some apps, but I click one app, for eg, WhatsApp it open and I choose the contact but when clicking the send button it shows "file can't be send". where I made a mistake, please help me to solve this code.
here I attached code for the share button.
//get an image from imageview
Drawable drawable = imageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
//sharing image
try {
File file = new File(MainActivity.this.getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
//sharing intent
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file);
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share via"));
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}

Try adding
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

here is my android manifest file,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.photoeditor">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:name="android-hardware.camera"
android:required="false" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationID}.provider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_path"
tools:replace="android:resource"/>
</provider>
</application>

Related

Camera intent failing

i am using this code to run a camera intent to take a photo. All being taken from HERE step by step (full sized camera option)
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(), "com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg",storageDir);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Toast.makeText(getActivity(), mCurrentPhotoPath, Toast.LENGTH_SHORT).show();
return image;
}
This is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.terrormachine.swipeapp">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
    </provider>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and my paths xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
and i am getting this error:
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.terrormachine.swipeapp/files/Pictures/JPEG_20161015_211933_-593154643.jpg
A little surprising since the file "shell" is there(at this location).
I fount THIS thread but i cant understand a thing...can you explain it humanlike? Any solution is welcome! Its an important project and i need to finish as much as possible and this is a huge stop.
In your files_path.xml, you need to replace com.example.package.name with your apps package name, as explained on developers site.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.terrormachine.swipeapp/files/Pictures" />
</paths>
Also add camera permission in your AndroidManifest.xml file.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"
android:required="true" />
I think you are missing "uses-feature android:name="android.hardware.camera" android:required="true"" in your manifest.

FileNotFoundException - Android - Creating and saving a pdf file to external storage

I have a problem in my android app while trying to create a pdf file from view of app.
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Documents/MyList/MyList.pdf: open failed: ENOENT (No such file or directory)
I had an error such like above. What am I missing there?
How can I handle it? Can you help me? Thanks.
Here is the Manifest file of my project.
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.furkan.tercihrehberi">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<!--activities...-->
<activity
android:name=".ListeMyo"
android:label="#string/app_name">
</activity>
<activity
android:name=".PDFGoster"
android:label="#string/app_name">
<intent-filter >
<action android:name="android.intent.action.OPEN_DOCUMENT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".PDFGosterTeog"
android:label="#string/app_name">
<intent-filter >
<action android:name="android.intent.action.OPEN_DOCUMENT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
ImageButton save = (ImageButton) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Toast.makeText(PDFGoster.this,"You cannot do that.",Toast.LENGTH_LONG).show();
}
File pdfDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
"MyList");
if (!pdfDir.exists()){
pdfDir.mkdir();
}
LayoutInflater inflater = (LayoutInflater) PDFGoster.this.getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout root = (RelativeLayout) inflater.inflate(R.layout.pdf, null);
root.setDrawingCacheEnabled(true);
Bitmap screen= getBitmapFromView(PDFGoster.this.getWindow().findViewById(R.id.tabla_cuerpo));
File pdfFile = new File(pdfDir, "MyList.pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
addImage(document,byteArray);
document.close();
}
catch (Exception e){
e.printStackTrace();
}
Intent intent = new Intent("android.intent.action.OPEN_DOCUMENT");
Uri uri = Uri.fromFile(new File(pdfDir, "MyList"));
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Toast.makeText(PDFGoster.this, "List successfully created", Toast.LENGTH_LONG).show();
startActivity(intent);
}
});

How to write text file via emulator?

Yesterday i post this question and some one replied me by peace of codes but the problem is permission denied. i do not know why happen this error because i have allowed permission in my manifest.xml. below is peace of code.
This is java code
public void WriteText() {
EditText txt= (EditText) findViewById(R.id.txtwrite);
try {
BufferedWriter fos = new BufferedWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+"File.txt"));
fos.write(txt.getText().toString().trim());
fos.close();
Toast.makeText(this, "Saved", Toast.LENGTH_LONG);
} catch (Exception e) {
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG);
}
}
This is manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Please any one help me i was so Straggled about it.

StartActivity from broadcastreceiver

Onreceive method will crash app at context.startActivity(Intent.createChooser(sendIntent, "Send"));
It works fine in oncreate method but do not work in broadcastreceiver class.
Can anybody knows reason. I am new android programmer.
Thanks in advance.
public class SMSReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
takePictureNoPreview(context);
String imagePath="test.jpeg";
Intent sendIntent = new Intent(Intent.ACTION_SEND);
// sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("sms_body", "I Send you pic.");
sendIntent.putExtra("address", phoneNumber);
sendIntent.setType("image/png");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(dataFile));
// context.startActivityForResult(sendIntent, 1);
context.startActivity(Intent.createChooser(sendIntent, "Send"));
// context.startActivity(sendIntent);
}
}
}
public void takePictureNoPreview(Context context){
// open back facing camera by default
Camera myCamera= Camera.open();//openFrontFacingCameraGingerbread();
if(myCamera!=null){
try{
//set camera parameters if you want to
//...
// here, the unused surface view and holder
SurfaceView dummy=new SurfaceView(context);
myCamera.setPreviewDisplay(dummy.getHolder());
myCamera.startPreview();
myCamera.takePicture(null, null, photoCallback);
} catch (IOException e) {
e.printStackTrace();
}finally{
// myCamera.close();
}
}else{
Toast toast = Toast.makeText(context, "No front Facing camera", Toast.LENGTH_LONG);
toast.show();
}
}
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Save the image JPEG data to the SD card
FileOutputStream fos = null;
// camera.startPreview();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
StudentDemo.iView.setImageBitmap(bmp);
try {
fos = new FileOutputStream(dataFile,true);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*new SavePhotoTask().execute(data);
camera.startPreview();*/
}
};
}
Android manifest file is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gen.stud"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9"
android:targetSdkVersion="9"
/>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.front" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Demo"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".StudentDemo"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.StudentDemo" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Try:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body", "I Send you pic.");
sendIntent.putExtra("address", phoneNumber);
sendIntent.setType("image/png");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(dataFile));
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(Intent.createChooser(sendIntent, "Send"));
Whenever launching an Activity from outside a UI related context (like a Service or a BroadcastReceiver), you need to attach the FLAG_ACTIVITY_NEW_TASK to the intent.

permissions denied when saving image on sdcard

This function is used to save image on sdcard (I have tested it on the emulator only):
public String SaveImage(String URL,String imagename){
Bitmap bitmap = null;
InputStream in = null;
String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path + "/bh");
if(!dir.exists())
new File(path + "/bh").mkdir();
Log.i("in save()", "after file");
File mImageFile = new File(path+"/bh/"+imagename);
if(mImageFile.exists())
Toast.makeText(mContext, "Saved", Toast.LENGTH_LONG).show();
try{
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
FileOutputStream out = new FileOutputStream(mImageFile);
bitmap.compress(CompressFormat.JPEG, 100,out);
out.flush();
out.close();
in.close();
return imagename+".jpg";
}catch(IOException ex){
Log.e("==== Error in saving image ====",ex.getMessage());
return "";
}
}
I have added the required permissions like below :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mobile.bh"
android:versionCode="4"
android:versionName="1.0.3" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<activity
android:name="mobile.bh.activities.BHActivity"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="mobile.bh.activities.RecipesListActivity"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="mobile.bh.activities.RecipeInfoActivity"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="mobile.bh.activities.IngredientsActivity"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="mobile.bh.activities.MethodActivity"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="mobile.bh.activities.SpicesListActivity"
android:screenOrientation="portrait" >
</activity>
<activity android:name=".activities.SpicesCategoriesActivity" >
</activity>
<activity android:name=".activities.CategoryActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You also need to use the Internet permission since you're connecting to the internet.
<uses-permission android:name="android.permission.INTERNET" />
Does your emulator support SDCard ?
Have a look at this great answer, it might be the issue https://stackoverflow.com/a/11468278/1635817

Categories

Resources