I have a download button in my app.When I press the download button it downloads an audio file from provided url.But the problem is I want to save the file in my internal storage folder called "DownloadTestFolder",it is showing an error.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download"
android:onClick="Download"
android:id="#+id/download"/>
</LinearLayout>
public class DownloadTest extends Activity {
DownloadManager downloadManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_test);
}
public void Download(View view){
downloadManager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri=Uri.parse("My Url");
DownloadManager.Request request = new DownloadManager.Request(uri);
try{
request.setDestinationInExternalPublicDir(getFilesDir()+"/DownloadTestFolder","/");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
}catch (Exception e){
/* Error
}
}
}
The DownloadManager can only download to external storage, you need to implement your own download manager.
Use this method to save file:
// DownloadFile AsyncTask
private class DownloadFile extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(URL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(mContext.getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
selectedFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Usage:
new DownloadFile().execute("url_here");
Note: I have added code for image type file
Related
How to handle full-sized photo using MediaStore.EXTRA_OUTPUT? First, I need to put the picture AS FULL-SIZED NOT THUMBNAIL on a layout and put text below it like this:
The idea I am using is that I am using layout.getDrawingCache to make it as bitmap.
Below is my camera button:
private void SelectImage(){
final CharSequence[] items={"Camera", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(PickupDrop.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager())!= null){
File imageFile = null;
try {
imageFile = getImageFile();
} catch (Exception e) {
e.printStackTrace();
}
if(imageFile!= null){
imageUri =FileProvider.getUriForFile(context, "com.example.android.fileprovider", imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(cameraIntent,REQUEST_CAMERA);
}
}
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
The getImageFile() method:
private File getImageFile(){
String imageName = "test";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = null;
try {
imageFile = File.createTempFile(imageName,".jpg",storageDir);
} catch (IOException e) {
e.printStackTrace();
}
currentImagePath = imageFile.getAbsolutePath();
return imageFile;
}
As you can see above, I am using EXTRA_OUTPUT with fileprovider to get FULL-SIZED bitmap.
Below is my manifests, provider.
Manifest:
<application ...
<provider
android:authorities="com.example.android.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_path"/>
</provider>
file_path.xml:
<?xml version="1.0" encoding="utf-8"?>
<external-path
name="my images"
path="Android/data/com.example.luckypasabayapp/files/Pictures"/>
My onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode,data);
if(resultCode== Activity.RESULT_OK){
if(requestCode==REQUEST_CAMERA){
Bitmap bitmap = BitmapFactory.decodeFile(currentImagePath);
populateScreenshot(bitmap);
}
}
}
Now here is where my problem occurs when I try to save the relative layout screenshot to my storage:
public void populateScreenshot(Bitmap bitmapFromPhone){
LayoutInflater inflater = LayoutInflater.from(PickupDrop.this);
View v = inflater.inflate(R.layout.information_dialog, null);
ImageView imageView_profilePic = v.findViewById(R.id.imageview_image);
TextView txt_item_data = v.findViewById(R.id.txt_item_data);
Button btn_cancel = v.findViewById(R.id.btn_cancel);
Button btn_download = v.findViewById(R.id.btn_download);
screenShot = v.findViewById(R.id.screenShot);
screenShot.setDrawingCacheEnabled(true);
screenShot.buildDrawingCache();
final AlertDialog alertDialog = new AlertDialog.Builder(PickupDrop.this)
.setView(v)
.create();
alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// Prevent dialog close on back press button
return keyCode == KeyEvent.KEYCODE_BACK;
}
});
//alertDialog.setCanceledOnTouchOutside(false);
//SETTING THE IMAGEVIEW OF LAYOUT TAKEN FROM CAMERA
imageView_profilePic.setImageBitmap(bitmapFromPhone);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//GETTING THE RELATIVELAYOUT AS BITMAP
Bitmap bitmap = screenShot.getDrawingCache();
File filePath = Environment.getExternalStorageDirectory();
File dir = new File(filePath.getAbsolutePath()+"/qrcode/");
dir.mkdirs();
File file = new File(dir, "str_specialNumber" + ".png");
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//HERE IS WHERE THE ERROR OCCURS, IT SAYS BITMAP IS NULL!!!
bitmap.setHasAlpha(true);
bitmap.compress(Bitmap.CompressFormat.PNG, 100,outputStream);
Toast.makeText(PickupDrop.this,"SCREENSHOT Downloaded",Toast.LENGTH_LONG).show();
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//notify gallery for a new picture
galleryAddPic(filePath.getAbsolutePath()+"/qrcode/"+"str_specialNumber"+".png");
}
});
alertDialog.show();
}
Here in bitmap.setHasAlpha(true); it says bitmap is null from screenshot.getDrawingCache I don't understand why.
How do I handle the EXTRA_OUTPUT properly to be able to do whatever I want with the bitmap?
You can give this answer a try :)
If you want to take the screenshot of any view or your RelativeLayout you can create this method takeScreenShot() : it will return a Bitmap
in #Param or parameter in this method, you can pass RelativeLayout
public static Bitmap takeScreenShot(#NonNull View view) {
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);
view.buildDrawingCache();
if (view.getDrawingCache() == null) return null;
Bitmap snapshot;
try {
snapshot = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
view.destroyDrawingCache();
} catch (Exception e) {
snapshot = null;
}
return snapshot;
}
tell me if this helps you :)
1) I'd like to download a image whose URL has been provided, save it to the SD card/internal memory. (lower quality and resize to say 100x100px)
2) use the downloaded image as a google maps marker
I have done the download image part but i need to resize it, and then somehow retrieve it in another activity as a google maps marker. any help on this?
this is the code i have so far for downloading (permissions are granted, code mostly taken form various sources):
private class DownloadTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
return Download(urls[0]);
}
protected void onPostExecute(Bitmap picture) {
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
// the File to save
File file = new File(path, "picture.jpg");
fOut = new FileOutputStream(file);
// saving the Bitmap to a file compressed as a JPEG with 85% compression rate
picture.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.close(); // do not forget to close the stream
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),
file.getName(),file.getName());
} catch (IOException e) {
Log.d("Download", e.getLocalizedMessage());
}
}
}
SOLVED
1)
private class DownloadTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
return Download(urls[0]);
}
protected void onPostExecute(Bitmap picture) {
try {
picture = Bitmap.createScaledBitmap(picture, 100, 100, true);
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
// the File to save
File file = new File(path, "picture.jpg");
fOut = new FileOutputStream(file);
// saving the Bitmap to a file compressed as a JPEG with 85% compression rate
picture.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.close(); // do not forget to close the stream
} catch (IOException e) {
Log.d("Download", e.getLocalizedMessage());
}
}
}
2)
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path, "picture.jpg");
Bitmap slikaweb = BitmapFactory.decodeFile(String.valueOf(file));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
pictureweb = BitmapFactory.decodeStream(new FileInputStream(file),
null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions().position(poz).title("")
.icon(BitmapDescriptorFactory.fromBitmap(pictureweb)));
As a preface, I am familiar with coding (2 years in highschool) but am a complete novice when it comes to Android Studio (and Java, in general). I've been searching for solutions for my problem, but due to my inexperience I have no idea how to implement the solutions to my project.
In short, I need to download a pdf from some external URL, store it into external storage, and display it using some pdf-viewer application. I've been getting error:
...
android.os.FileUriExposedException: file:///storage/emulated/0/pdf/Read.pdf exposed beyond app through Intent.getData()
...
I've been using this source on using an intent to open a pdf-viewer and this source on "File Provider" as references.
Below is what I have so far:
Fire (with a clickable TextView that should download and display the pdf)
public class Fire extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fire);
final TextView testButton = findViewById(R.id.testPDF);
// File file = getFilesDir();
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Fire.this, pdfView.class);
startActivity(intent);
}
});
pdfView activity
public class pdfView extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_view);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile(__PDF_URL___, file);
showPdf();
}
public void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
Downloader class
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
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) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
From my research, it seems that my problem stems from my usage of URI instead of a "File provider." Also, it seems the solution that implements a "File Provider" uses Context in some form or another, and I'm confused on what the purpose of context is and how to implement it.
If you do not have answers that is fine. Any information on how to figure this out or even understand the concept is good enough for me.
If your targetSdkVersion >= 24, then we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.
1) First Add a FileProvider tag in AndroidManifest.xml under tag as below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name=".GenericFileProvider"
android:authorities="${applicationId}.my.package.name.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
</manifest>
2) Then create a provider_paths.xml file in res/xml folder. Folder may be needed to created if it doesn't exist.
<paths>
<external-path name="external_files" path="."/>
</paths>
3) Now create PdfDownload.java class file and paste below code:
public class PdfDownload extends Activity {
TextView tv_loading;
Context context;
int downloadedSize = 0, totalsize;
float per = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
isStoragePermissionGranted();
super.onCreate(savedInstanceState);
tv_loading = new TextView(this);
tv_loading.setGravity(Gravity.CENTER);
tv_loading.setTypeface(null, Typeface.BOLD);
setContentView(tv_loading);
downloadAndOpenPDF();
}
public static String getLastBitFromUrl(final String url) {
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
void downloadAndOpenPDF() {
final String download_file_url = getIntent().getStringExtra("url");
new Thread(new Runnable() {
public void run() {
Uri path = Uri.fromFile(downloadFile(download_file_url));
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = FileProvider.getUriForFile(PdfDownload.this, BuildConfig.APPLICATION_ID, downloadFile(download_file_url));
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
finish();
} catch (ActivityNotFoundException e) {
tv_loading
.setError("PDF Reader application is not installed in your device");
}
}
}).start();
}
File downloadFile(String dwnload_file_path) {
File file = null;
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.connect();
String test = getLastBitFromUrl(dwnload_file_path);
String dest_file_path = test.replace("%20", "_");
// set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
// // create a new file, to save the downloaded file
file = new File(SDCardRoot, dest_file_path);
if (file.exists()) {
return file;
}
FileOutputStream fileOutput = new FileOutputStream(file);
// Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
// this is the total size of the file which we are
// downloading
totalsize = urlConnection.getContentLength();
setText("Starting PDF download...");
// create a buffer...
byte[] buffer = new byte[1024 * 1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
per = ((float) downloadedSize / totalsize) * 100;
if ((totalsize / 1024) <= 1024) {
setText("Total PDF File size : " + (totalsize / 1024)
+ " KB\n\nDownloading PDF " + (int) per + "% complete");
} else {
setText("Total PDF File size : " + (totalsize / 1024) / 1024
+ " MB\n\nDownloading PDF " + (int) per + "% complete");
}
// setText("configuring your book pleease wait a moment");
}
// close the output stream when complete //
fileOutput.close();
// setText("Download Complete. Open PDF Application installed in the device.");
setText("configuaration is completed now your book is ready to read");
} catch (final MalformedURLException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final IOException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final Exception e) {
setTextError(
"Failed to download image. Please check your internet connection.",
Color.RED);
}
return file;
}
void setTextError(final String message, final int color) {
runOnUiThread(new Runnable() {
public void run() {
tv_loading.setTextColor(color);
tv_loading.setText(message);
}
});
}
void setText(final String txt) {
runOnUiThread(new Runnable() {
public void run() {
tv_loading.setText(txt);
}
});
}
private static final String TAG = "MyActivity";
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG, "Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission: " + permissions[0] + "was " + grantResults[0]);
}
}
}
I am implementing a button which lets you take a screenshot, but I want to save it on the Android Internal Storage not in the External Storage (SD Card).
I tried this:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
return directory.getAbsolutePath();
}
I've started this method with an OnClick method of a button:
private void takeScreenshot(View v) {
v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
saveToInternalStorage(bitmap)
}
But this didn't work. Instead, when I click the button, an error message appears on my cell phone: "Application has stopped".
Hope you can help me.
I think you need to use openFileOutput to get a FileOutputStream, try following the example in the doc https://developer.android.com/training/basics/data-storage/files.html
What's the error in the logcat?
/**
* This function captures any Android views to a bitmap shapshot
* and save it to a file path
* and optionally open it with android pciture viewer
*/
public void CaptureView(View view, String filePath, boolean bOpen) {
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
try {
b.compress(CompressFormat.JPEG, 95, new FileOutputStream(filePath));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bOpen) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath), "image/*");
startActivity(intent);
}
}
Usage:
File sdcard = Environment.getExternalStorageDirectory();
String path = sdcard + "/demo.jpg";
CaptureView(someViewInstace, path, false);
You can use Context.getFilesDir() method to get the path to the internal storage:
String path = yourActivity.getFilesDir() + "/" + name);
Add permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
add this line manifest file application tag
android:requestLegacyExternalStorage="true"
In activity
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int permission = ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
MainActivity.this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
} else {
takeScreenshot();
}
}
});
}
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
Toast.makeText(MainActivity.this, "Successfully saved", Toast.LENGTH_SHORT).show();
//**if you want to open this screenshot
openScreenshot(imageFile);
} catch (Throwable e) {
e.printStackTrace();
}
}
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
}
im making an app consist of some pdf file but i dont know how i can work with that
1- where i should copy my pdf files in resource ? (which folder?)
2- what code needed to open its ? (what codes need to write in onClick method ? )
3- what class and methods is usfull for this procedure ?
leave this below codes ( they are for body error ignoring )
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);}
If you want to open the PDF from a webview you can use the following code:
public class ActivityName extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView mWebView=new WebView(MyPdfViewActivity.this);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
setContentView(mWebView);
}
}
If you would like to open the PDF locally, you can an place it in either the res/raw folder or the assets folder(in the following example the assets folder is used). Then you need to place the file locally using the following code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Then you can use the following code to access the PDF, again assuming the user has a PDF viewer installed:
public class OpenPdf extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.OpenPdfButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File("/sdcard/example.pdf");
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) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
If you want to open it from your application you can try this