Android open downloaded file - java

I have a question about downloading a pdf file and opening it with an pdf reader application installed on the phone. I'm new to android and working my way up but got stuck on this part.
So what i have now:
I have an activity that for now starts downloading a pdf file and tries to open is with an intent. For now everything is static so thats why i have a set url.
private void DownloadFile(){
DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse("http://awebiste.adomain/afile.pdf");
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("My Data Download");
request.setDescription("Android Data download using DownloadManager.");
request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,"test.pdf");
Long downloadReference = downloadManager.enqueue(request);
if (downloadReference != null){
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.parse(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/test.pdf"), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Log.v("OPEN_FILE_PATH", getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/test.pdf");
startActivity(target);
} else {
//TODO something went wrong error
}
}
Now the file is downloaded and saved in the application folder under /storage.sdcard0/Android/data/<application>/files/download and from the documents browser the file can be opent. But when i use the intent at the button of my code i get a toast that the file can not be opent. After some searching on google i think its a permission problem because these files are private to the application. So how do I make these files public?

Here's How I did it after a long day of search,Your code helped me a little to solve it:
String name;
DownloadManager mManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_interview);
Button down = (Button) findViewById(R.id.download);
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
down();
}
});
}
public void down() {
mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(DOWNLOAD_FILE);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri)
.setAllowedOverRoaming(false)
.setTitle("Downloading")
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, name + "CV.pdf")
.setDescription("Download in progress").setMimeType("pdf");
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(broadcast, intentFilter);
}
public void showPdf() {
try {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Download/" + name + "CV.pdf");//name here is the name of any string you want to pass to the method
if (!file.isDirectory())
file.mkdir();
Intent testIntent = new Intent("com.adobe.reader");
testIntent.setType("application/pdf");
testIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
testIntent.setDataAndType(uri, "application/pdf");
startActivity(testIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadcastReceiver broadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
showPdf();
}
};

Related

Check if a file exists in Android

Android/Java, API level 12.
I'm trying to check if a .zip file exists in the Downloads folder. If it doesn't exist then I'm downloading it from the internet using DownloadManager. For the purposes of testing I'm running my checkIfFileExists immediately after the onReceive method of the DownloadManager, subject to the download being successful. My issue is that checkIfFileExists is returning false every time, even after I've just downloaded the file and I've checked manually that it does exist.
The relevant code is below.
DownloadManager dm;
long queueid;
String filename = "myfile.zip", url = "http://myurl/", uriString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
{
DownloadManager.Query req_query = new DownloadManager.Query();
req_query.setFilterById(queueid);
Cursor c = dm.query(req_query);
if (c==null)
{
Toast.makeText(context, "Download not found!", Toast.LENGTH_SHORT).show();
}
else
{
if (c.moveToFirst())
{
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c.getInt(columnIndex))
{
uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Toast.makeText(context, "Download finished.", Toast.LENGTH_SHORT).show();
Toast.makeText(context, uriString, Toast.LENGTH_LONG).show();
checkIfFileExists();
}
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClickDownload(View v) // this method seems to be working with no issues.
{
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, filename);
queueid = dm.enqueue(request);
}
private boolean checkIfFileExists()
{
File file = new File(uriString);
if(file.exists())
{
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}
I was expecting if(file.exists()) to evaluate to true since the file does exist.
What actually happens is if(file.exists()) always evaluates as false.
Can anyone see what I'm doing wrong?
Change your method like this.:
private boolean checkIfFileExists(String zipName /*ex: fileName.zip*/) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), zipName);
if(file.exists()) {
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}

Reading Database File from External Storage

So, this program downloads a file from firebase storage,
my downloading code is:
private void downloadFiles(Context context, String fileName, String destinationDirectory, String url) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, String.valueOf(destinationDirectory), fileName);
downloadManager.enqueue(request);
}
public void downloading(final String name) {
downloadRef = storage.getInstance().getReference().child(name);
downloadRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
downloadFiles(Main2Activity.this, name, getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main2Activity.this, "Failed!!!", Toast.LENGTH_LONG).show();
}
});
}
and then I want to use this database so I tried to open it with:
database = SQLiteDatabase.openDatabase(myPath, null, 0);
How can I solve this one? It would be really helpful guys.
I thought your problem was accessibility.
That's why I brought a activity back to get permission from the user.
You test this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("name", arrayList.get(position));
startActivity(intent);
}
}
});
You are using Environment.getExternalStorageState() which returns the current state of the primary shared/external storage media. It cannot be used to get the path as string of any file. Use context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) to get the string value of the path to the Download directory.

Is there a way to attach any type of file to an email using intents?

I'm trying to create a small app where the user can type in recepient, subject, the message and if they want to, also attach a file. I ran in to a minor issue, I can't choose any file freely. I go through my folders and find images and PDF files but none of them are clickable, I can't choose any (They're greyed out for some reason).
I was able to choose a file once(don't remember what type it was) but I got an IO error from the outlook app, it couldn't handle the file for some reason.
public class MainActivity extends AppCompatActivity {
private static final int PICKFILE_REQUEST_CODE = 8778;
private EditText mEditTextTo;
private EditText mEditTextSubject;
private EditText mEditTextMessage;
private Button sendBtn;
private Button fileBtn;
private String filePath = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditTextTo = (EditText)findViewById(R.id.edit_text_to);
mEditTextSubject = (EditText)findViewById(R.id.edit_text_subject);
mEditTextMessage = (EditText)findViewById(R.id.edit_text_message);
sendBtn = (Button)findViewById(R.id.sendBtn);
fileBtn = (Button)findViewById(R.id.fileBtn);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMail();
}
});
fileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);
}
});
}
private void sendMail() {
String recepientList = mEditTextTo.getText().toString();
String[] recepient = recepientList.split(",");
String subject = mEditTextSubject.getText().toString();
String message = mEditTextMessage.getText().toString();
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, recepient);
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, message);
sendEmailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new
File(filePath)));
sendEmailIntent.setType("text/plain");
startActivity(Intent.createChooser(sendEmailIntent, "Choose email
client"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
filePath = data.getDataString();
super.onActivityResult(requestCode, resultCode, data);
}
}
You can use below code:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"email#example.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
intent.putExtra(Intent.EXTRA_TEXT, "body text");
File root = Environment.getExternalStorageDirectory();
File file = new File(root, xmlFilename);
if (!file.exists() || !file.canRead()) {
Toast.makeText(this, "Attachment Error", Toast.LENGTH_SHORT).show();
finish();
return;
}
Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Send email..."));

Java: How to automatically open pdf after Download

I've been looking for various tutorials but no one can solve my case. I hope here is something that can make me understand, about how to open PDF file automatically after finished download from database to android.
This is my download script.
#Override
public void onBindViewHolder(HolderData holder, int position) {
final ModelData md = mItems.get(position);
holder.txtname.setText(md.getName());
holder.txtwaktu.setText(md.getWaktu());
//Proses Downloading
holder.relativeLayoutMateri.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uri = String.valueOf(Uri.parse("http://192.168.43.144/MLearning/crud/"+md.getPath()));
dm = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uri));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
longid = dm.enqueue(request);
Toast.makeText(context, md.getName()+" Berhasil Di Download"+md.getPath(), Toast.LENGTH_SHORT).show();
}
});
}
Here is the solution please use ACTION_VIEW Intent to open all you need the path of downloaded pdf.
private static String filepath = Environment.getExternalStorageDirectory().getPath()+"/myfile.pdf";
File file = new File(filepath);
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Log.d(TAG,e.getMessage());
}
}

Error when trying to play audio file from URI

So I'm completely new to Android programming and I'm starting off by trying to make an app that allows users to edit audio files. Here is my code so far, which makes a user upload an audio file and play it:
public class MainActivity extends Activity {
final int ACTIVITY_CHOOSE_FILE = 1;
public String filePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.uploadbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("audio/mpeg");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
});
Button playButton = (Button)findViewById(R.id.playbutton);
playButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(getApplicationContext(), Uri.parse(filePath));
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
filePath = uri.getPath();
getFilePath(filePath);
TextView URI_Text = (TextView)findViewById(R.id.file_URI);
URI_Text.setText(filePath);
}
}
}
}
public String getFilePath (String filePath) {
return filePath;
}
}
However, I'm getting the error code E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab756e00
What am I doing wrong?
That error is not related to any of your code from your question. However, you are going wrong in other places.
getPath() is useless. The Uri should be treated as an opaque handle. Calling getPath() on a Uri, and expecting a file to be at that path, is akin to expecting there to be a /questions/33843271/error-when-trying-to-play-audio-file-from-uri path on your computer's hard drive, just because your browser happens to be showing a URL with that path.
Also, your access to the data represented by that Uri is short-lived. This is reminiscent of Web development, where you might be able to stream data from some URL for a while, but eventually your session times out. Saving the Uri is pointless. Either consume the data now (via a ContentResolver and openInputStream()), or don't bother with the data at all.

Categories

Resources