Exporting to Excel using an intent and directly opening it - android

I made a code to export excel from intent android, but this code didn't work and show this alert .
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
Uri fileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", dir);
intent.setDataAndType(fileUri,"application/*");
} else {
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(Uri.fromFile(dir),"application/*");
}
try {
context.startActivity(intent);
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(context, "You need to have Microsoft Office Excel Installed here", Toast.LENGTH_LONG).show();
} finally {
Toast.makeText(context, "Success create report on " + dir.getPath() , Toast.LENGTH_LONG).show();
}

Related

Unable to open PDF file through intent programmatically in android

I have an app where on button click, access should be provided to browse and open the PDF files stored in the internal memory of the device.I tried various codes but i get an toast saying "Cannot display PDF". I don't get any errors in logs. I use android version 7.0 device. Attached my code below: please help:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
I have included this in Oncreate:
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
This is how called the method:
linear_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdf.setTextColor(getActivity().getResources().getColor(R.color.colorWhite));
openPdf(getContext(), Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
communication.dismiss();
}
});
Try this one...
public void openPdf(Context context, String path){
File file = new File(path);
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
PackageManager pm = context.getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setType("application/pdf");
Intent openInChooser = Intent.createChooser(intent, "Choose");
List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
if (resInfo.size() > 0) {
try {
context.startActivity(openInChooser);
} catch (Throwable throwable) {
Toast.makeText(context, "PDF apps are not installed", Toast.LENGTH_SHORT).show();
// PDF apps are not installed
}
} else {
Toast.makeText(context, "PDF apps are not installed", Toast.LENGTH_SHORT).show();
}
}
}
Call this method:
openPdf(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
For opening one specific file:
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/your_directory/" + "your_file_name" + ".pdf");
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(getContext(), "No required app", Toast.LENGTH_SHORT).show();
}
Check directory, this one works.
For opening pdf file from local storage add prefix in url.
private void openPdf(File file) {
try {
String url = file.getAbsolutePath();
String u = "file:///" + url;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(u));
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}

How to make my share intent support whatsapp and google+

I am using this code to share an image:
File file = ImageLoader.getInstance().getDiskCache().get(imageUrl);
if (file != null && file.exists()) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(Intent.createChooser(intent, "Send"));
} else {
Toast.makeText(context, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
I used UIL to load the image previously, so mageLoader.getInstance().getDiskCache().get(imageUrl); returns the image file from disk cache.
Gmail, Hangouts, Messages, Drive etc can grab the file but on Google+, the grabbed is not gotten while Whatsapp says "This format is not supported". However if I save the file to Downloads folder and share via Gallery app, the same image is picked by both Google+ and Whatsapp.
You can try to save the file to the external cache, it's working for me. Example with Glide:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("image/*");
Glide.with(getContext())
.load("http://...url.here...")
.asBitmap()
.into(new SimpleTarget<Bitmap>(500, 500) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
try {
File file = new File(getContext().getExternalCacheDir(), "file_to_share.png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
resource.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().startActivity(Intent.createChooser(sendIntent, ""));
} catch (IOException e) {
Log.e("Share", e.getMessage(), e);
} finally {
}
}
});
In case you're using Universal Image Loader, I applied the accepted answer to save the image and delete it as soon as the user returns from sharing:
private File saveImage(String imageUri, String fileName) {
File file = new File(this.getExternalCacheDir(), fileName);
InputStream sourceStream = null;
File cachedImage = ImageLoader.getInstance().getDiskCache().get(imageUri);
if (cachedImage != null && cachedImage.exists()) {
Log.d(TAG, "Cache exists");
try {
sourceStream = new FileInputStream(cachedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Cache doesn't exist");
}
if (sourceStream != null) {
Log.d(TAG, "SourceStream is not null");
try {
OutputStream targetStram = new FileOutputStream(file);
try {
try {
IoUtils.copyStream(sourceStream, targetStram, null);
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
targetStram.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
sourceStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.d(TAG, "SourceStream is null");
Toast.makeText(this, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
return file;
}
private void shareImage(String imageUrl, String fileName) {
if (isSDReadableWritable()) {
file = saveImage(imageUrl, fileName);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(Intent.createChooser(intent, "Send"), 20);
} else {
Toast.makeText(this, "Storage cannot be accessed", Toast.LENGTH_SHORT).show();
}
}
To delete the file just override onActivityResult and it'll be deleted immediately after sharing
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 20 && file != null) {
boolean isDelete = file.delete();
Log.d(TAG, "isDelete is " + isDelete);
}
}

Android open XLSX file

I'm trying to open an XLSX file within my Android App.
I'm aware that the Intent type I have to fire is application/excel, but despite I've installed Google Sheets, my code says that no application can open my excel file.
This is the code I use to fire the Intent:
private void openXLS(){
File xls = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "prova.xlsx");
Uri path = Uri.fromFile(xls);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/excel");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No Application available to view XLS", Toast.LENGTH_SHORT).show();
}
}
Note: prova.xlsx exists, and I'm able to reach it and open it.
SOLVED
Using the MIME type application/vnd.ms-excel, *.xls and *.xlsx files can be opened.
private void openXLS(final String path) {
File file = new File(path);
Uri uri ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/vnd.ms-excel");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}

add image to twitter share intent android

I'm trying to add an image to my twitter share intent. I save an image locally in one class and then in another I get the image and try to attach to my intent.
Here is my code
private void shareTwitter(){
try {
FileInputStream fis;
fis = getActivity().openFileInput("photo.jpg");
Bitmap shot = BitmapFactory.decodeStream(fis);
File file = new File(MapView.path, "snapshot.jpg");
if(file.exists()){
Log.i("FILE", "YES");
}else{
Log.i("FILE", "NO");
}
Uri uri = Uri.parse(file.getAbsolutePath());
//Uri uri = Uri.parse("android.resource://com.gobaby.app/drawable/back");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("/*");
intent.setClassName("com.twitter.android", "com.twitter.android.PostActivity");
intent.putExtra(Intent.EXTRA_TEXT, "Thiws is a share message");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(intent);
} catch (final ActivityNotFoundException e) {
Toast.makeText(getActivity(), "You don't seem to have twitter installed on this device", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
At the moment there is no exception in my logcat my app just displays a toast saying image failed to load.
Please what an I doing wrong?
This is what you need
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file);
This might be helpful for somebody:
private void sendShareTwit() {
try {
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
String filename = "twitter_image.jpg";
File imageFile = new File(Environment.getExternalStorageDirectory(), filename);
tweetIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.twitter_share_text));
tweetIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
tweetIntent.setType("image/jpeg");
PackageManager pm = getActivity().getPackageManager();
List<ResolveInfo> lract = pm.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for (ResolveInfo ri : lract) {
if (ri.activityInfo.name.contains("twitter")) {
tweetIntent.setClassName(ri.activityInfo.packageName,
ri.activityInfo.name);
resolved = true;
break;
}
}
startActivity(resolved ?
tweetIntent :
Intent.createChooser(tweetIntent, "Choose one"));
} catch (final ActivityNotFoundException e) {
Toast.makeText(getActivity(), "You don't seem to have twitter installed on this device", Toast.LENGTH_SHORT).show();
}
}
Here is solution:
private fun shareOnTwitter() {
val file = File(context!!.filesDir, FILENAME_SHARE_ON_TWITTER)
val uriForFile = FileProvider.getUriForFile(context!!, com.yourpackage.activity.YourActivity, file)
val intent = Intent(Intent.ACTION_SEND).apply {
type = "image/jpeg"
putExtra(Intent.EXTRA_STREAM, uriForFile)
}
startActivity(intent)
}

Capturing image from gallery & camera in android

First thing I know this is repeated question but I don't have problem in capturing image from gallery or camera. I created on dummy project to check my code here it's working fine
But when I used same code in my project & here it's not working even I didn't get any error
as soon as I start activity for result it get cancelled but still I can see images from gallery & I can capture image from camera.
When I checked logcat I found following warning don't know why it's coming & how I can fix this thing
W/NetworkConnectivityListener(2399): onReceived() called with CONNECTED and Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x10000000 (has extras) }
Edit:-- Added Code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
//define the file-name to save photo taken by Camera activity
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
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;
}
#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;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
Toast.makeText(this, "Picture was taken", Toast.LENGTH_SHORT).show();
Uri selectedImageUri = imageUri;
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);
}
} 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;
}
}
Thank You
Take a look at LinderdaumEngineActivity.java from my project Linderdaum Engine:
Capture image from camera:
public void CapturePhoto( String FileName )
{
try
{
File f = new File(FileName);
if ( f.exists() && f.canWrite() ) f.delete();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_CALLBACK);
}
catch ( ActivityNotFoundException e )
{
Log.e( TAG, "No camera: " + e );
}
catch ( Exception e )
{
Log.e( TAG, "Cannot make photo: " + e );
}
}
Open image from gallery:
public static void OpenImage()
{
try
{
Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
intent.setType( "image/*" );
startActivityForResult( intent, SELECT_PICTURE_CALLBACK );
}
catch ( ActivityNotFoundException e )
{
Log.e( TAG, "No gallery: " + e );
}
}
Also, do not forget to add permissions to your manifest:
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-permission android:name="android.permission.CAMERA" android:required="false"/>
Please check your AndroidManifest, make sure you have all the right permissions.
See official documentation with file provider for above android 7
getUriForFile(Context, String, File) which returns a content:// URI. For
more recent apps targeting Android 7.0 (API level 24) and higher, passing a
file:// URI across a package boundary causes a FileUriExposedException.
Therefore, we now present a more generic way of storing images using a
FileProvider.
<application>
...
<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>
...
Official doc

Categories

Resources