I want to download a file from URL and save it to the internal memory. Once file is saved in internal memory I want to fire an Intent to open it in apps.
**Following is the code to download the file and save in internal memory:**
private void getPDFContent(String myUrl, String sfilename) {
try {
FileOutputStream fos = this.openFileOutput(sfilename,Context.MODE_PRIVATE);
URL u = new URL(myUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
**Following is the code to read:**
public void readInternalStorageOption() {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
String filePath = getApplication().getFilesDir().getAbsolutePath()
+ File.separator + "test.pdf";
File f = new File(filePath);
if (f.exists()) {
Uri internal = Uri.fromFile(f);
intent.setDataAndType(internal, "application/pdf");
}
startActivity(intent);
} catch (NullPointerException ex) {
}
}
Issue is that file is saved successfully but when I try to open it via intent I got an error that file cannot be opened. Please suggest any solution for the same.
Related
Uri uri = Uri.parse("content://" + context.getPackageName() + "/" + R.raw.audio);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM, uri);
view.getContext().startActivity(Intent.createChooser(share, "Share Sound File"));
Use this Code instead of Above.
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = context.getResources().openRawResource(R.raw.audio);
fileOutputStream = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "audio.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse(Environment.getExternalStorageDirectory() + "/audio.mp3"));
intent.setType("audio/*");
context.startActivity(Intent.createChooser(intent, "Share sound"));
i want to share an audio when a button is hold, i save the mp3 to the external storage and then share it but i have an error "failed to send, please try again" (something like that, the original is in spanish). what can i do?
the code:
b0.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
File dest = Environment.getExternalStorageDirectory();
InputStream in = getApplicationContext().getResources().openRawResource(R.raw.teagachas);
try
{
OutputStream out = new FileOutputStream(new File(dest, "lastshared.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch (Exception e) {}
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/lastshared.mp3"));
share.setType("audio/*");
getApplicationContext().startActivity(Intent.createChooser(share, "compartiendo \"" + b0.getText() + "\""));
return true;
}
});
PD: the code is in the onCreate method
I have audio mp3 in res/raw/suono1.mp3 and i need share(in my app) on whatapp my code is it, but when i send, don t share HELP ME PLS.
pulsante2.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//condividere
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.suono2);
fileOutputStream = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/mpeg");
startActivity(Intent.createChooser(intent, "Share audio"));
return false;
}
});
send code for android studio i need them
Have you asked permission in the manifest.xml file?
I need the File object of an image on an Android device.
I'm using a function to get a FileInputStream given a URI.
FileInputStream getSourceStream(Uri u) throws FileNotFoundException {
FileInputStream out = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(u, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
out = new FileInputStream(fileDescriptor);
} else {
out = (FileInputStream) getContentResolver().openInputStream(u);
}
return out;
}
This returns a FileInputStream. What I need is a File object of the image. How can I get a File from FileInputStream?
update
This is how I am getting my URI:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
and on onActivityResult I get the URI of the image.
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(resultCode == RESULT_OK){
String uri = data.getData();
}
}
You can use below code to convert your FileInputStream to File object.
try {
File outputFile = new File("YOUR DESIRED FILE PATH");
FileOutputStream fos = new FileOutputStream(outputFile);
int c;
while ((c = fileInputStream.read()) != -1) {
fos.write(c);
}
fileInputStream.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
System.err.println("FileStreamsTest: " + e);
}
here 'fileInputStream' is your object returned by getSourceStream()
i am new in android. i want to save image from url into SDcard.
File direct = new File(Environment.getExternalStorageDirectory()
+ "/.imgapp");
if (!direct.exists()) {
direct.mkdirs();
}
Calendar c = Calendar.getInstance();
int d = c.get(Calendar.DATE);
int d1 = c.get(Calendar.MONTH)+1;
File file = new File(Environment.getExternalStorageDirectory()
+ "/.imgapp/"+d+""+d1+".png" );
if (!file.exists()) {
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()
+ "/.imgapp/"+d+""+d1+".png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally { output.close(); }
} finally { input.close(); }
}else{
Toast.makeText(getApplicationContext(), "No Error", Toast.LENGTH_SHORT).show();
}
manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
i try This Code But App Stop and Crash please Help Me.
i want download image onCreate when user open App.
finally Done!!.
DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
String uRl = "http://bitsparrow.altervista.org/wp-content/uploads/2013/04/5.jpg";
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/.appimg", "test.jpg");
mgr.enqueue(request);
This Work For me..!