i am trying to implement a pdf reader via a pdf library from git hub https://github.com/jblough/Android-Pdf-Viewer-Library but when i implement the code.. all i am getting is a blank page.. the url is correct the pdf has content and this is similar to this q .. Example of code to implement a PDF reader
my code consist of multiple methods, the main method is used to select the which pdf should be chosen to display. then the pdf name is passed on to method "copyreadassets"
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getApplicationContext().getFilesDir() + "/"+url;
openPdfIntent(path); }
the openpdfintentmethod is used to open the values
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
pdf.class contains the following..
public class Pdf extends Activity{
public int getPreviousPageImageResource() {
return R.drawable.left_arrow; }
public int getNextPageImageResource() {
return R.drawable.right_arrow; }
public int getZoomInImageResource() {
return R.drawable.zoom_in; }
public int getZoomOutImageResource() {
return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() {
return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() {
return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() {
return R.id.etPassword; }
public int getPdfPasswordOkButton() {
return R.id.btOK; }
public int getPdfPasswordExitButton() {
return R.id.btExit; }
public int getPdfPageNumberEditField() {
return R.id.pagenum_edit; }
}
In your AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<activity android:name="com.example.readassetpdf.myPDFActivity"></activity>
in your case activity is pdf class
<activity android:name="com.example.readassetpdf.pdf"></activity>
and use following method
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
//out = getApplicationContext().openFileOutput(file.getName(),
//Context.MODE_WORLD_READABLE);
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf";
openPdfIntent(path);
}
and call it as below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
CopyReadAssets("mypdf.pdf");
}
And the function copyfile is as below
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);
}
}
The replacement is
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
to
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");
Related
This question already has answers here:
How to download and save an image in Android
(10 answers)
Closed 3 years ago.
I want to download an image from url. if the url does not have an image format at the end of the link? Example of url:
https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=1937530436393797&height=200&width=200&ext=1579152762&hash=AeQEq164H_oXIMjx
Try this code :
Create LocalImageSaver.java :
public class LocalImageSaver extends AsyncTask<Void, String, Boolean> {
private final SaveCompletionInterface saveCompletionInterface;
private final String originalImageUrl;
private final Context context;
private String savedImagePath;
private String fUrl;
public LocalImageSaver(Context context, String originalImageUrl, SaveCompletionInterface saveCompletionInterface) {
this.context = context;
this.saveCompletionInterface = saveCompletionInterface;
this.originalImageUrl = originalImageUrl;
}
/**
* Downloading file in background thread
*/
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected Boolean doInBackground(Void... f_url) {
this.fUrl = originalImageUrl;
FileOutputStream output = null;
InputStream is = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(fUrl);
HttpContext context = new BasicHttpContext();
HttpResponse response = client.execute(get, context);
is = response.getEntity().getContent();
int status = response.getStatusLine().getStatusCode();
if (status == 200 && is != null) {
String imageNameToSave;
String extension = originalImageUrl.substring(originalImageUrl.lastIndexOf(".") + 1); // Without dot jpg, png
if (extension.contains("mp4")) {
extension = "mp4";
}
String fileName = "";//originalImageUrl.substring(originalImageUrl.lastIndexOf("/") + 1); // Without dot jpg, png
fileName = "05Media_" + Calendar.getInstance().getTimeInMillis() + "." + extension;
imageNameToSave = fileName;
Uri savedImagePathUri = CommonImageUtil.createImageFile(imageNameToSave);
savedImagePath = savedImagePathUri.getPath();
// Output stream to write file
output = new FileOutputStream(savedImagePathUri.getPath());
int read = 0;
byte[] buffer = new byte[32768];
while ((read = is.read(buffer)) > 0) {
output.write(buffer, 0, read);
}
// flushing output
output.flush();
// closing streams
output.close();
is.close();
return true;
}
} catch (ClientProtocolException e) {
Lg.printStackTrace(e);
} catch (IOException e) {
Lg.printStackTrace(e);
} catch (Exception e) {
Lg.printStackTrace(e);
} finally {
// flushing output
try {
if (output != null) {
output.flush();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
saveCompletionInterface.onSaved(result, savedImagePath);
}
public interface SaveCompletionInterface {
public void onSaved(boolean result, String imageNameToSave);
}
}
and call this :
LocalImageSaver localImageSaver = new LocalImageSaver(getActivity(), url, new LocalImageSaver.SaveCompletionInterface() {
#Override
public void onSaved(boolean result, String savedImagePath) {
if (result) {
//showToast(getActivity(), (R.string.image_save_succesfull));
// refresh gallery
try {
MediaScannerConnection.scanFile(getActivity(), new String[]{savedImagePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
}
} else {
//showToast(getActivity(), (R.string.error_saving_image));
}
}
});
localImageSaver.execute();
I'm nearly finished with my App!
It's working fine, but there's a little mistake in it..
My App is an "Note"-App with some notes that are prefabricated and are the first opening of the app.
Therefore I save this notes at the first start and get them everytime I start the app again.
Unfortunately I'm have 66 prefabricated notes and they are all saved, but in the ListView there are only 45 or so in it..
I don't think it's something with syntax because the app works fine except the loss of 21 prefabricated notes
Here's my MainActivity Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean useDarkTheme = preferences.getBoolean(PREF_DARK_THEME, false);
SharedPreferences prefers = getApplicationContext().getSharedPreferences("prefs_daten", MODE_PRIVATE);
if (useDarkTheme) {
setTheme(R.style.AppTheme_dark);
}
super.onCreate(savedInstanceState);
if (VERBOSE) Log.v(TAG, "+ ON CREATE +");
setContentView(layout.activity_hauptmenu);
mListNotes = findViewById(id.listview);
itemTitel = new ArrayList<>();
itemTitel.addAll(Arrays.asList(string.Titel1, string.Titel2, string.Titel3, ...
string.Titel66));
itemStory = new ArrayList<>();
itemStory.addAll(Arrays.asList(string.Blackstory1, ...));
itemLosung = new ArrayList<>();
itemLosung.addAll(Arrays.asList(string.Losung1, ..));
}
private void StandardBS() {
if (Listensize==0){
anzahl_BS=66;
int a;
for(a=0; a<anzahl_BS; a++){
try{
tempTitel = getResources().getString(itemTitel.get(a));
tempStory = getResources().getString(itemStory.get(a));
tempLosung = getResources().getString(itemLosung.get(a));
Blackstory blackstory = new Blackstory(System.currentTimeMillis(), tempTitel, tempStory, tempLosung);
Log.w("Blackstory", ""+tempTitel);
Utilities.saveBlackstory(this, blackstory);
//Toast.makeText(this, "Blackstory wurde gespeichert!", Toast.LENGTH_SHORT).show();
}
catch (NullPointerException e){
//Toast.makeText(this, "Standard wurde falsch ausgeführt", Toast.LENGTH_SHORT).show();
}
}
Log.w("Anzahl", ""+a);
}
#Override
protected void onResume() {
super.onResume();
try{
mListNotes.setAdapter(null);
}
catch (NullPointerException e){
Toast.makeText(this, "not null", Toast.LENGTH_SHORT).show();
}
final ArrayList<Blackstory> blackstories = Utilities.getAllSavedBlackstory(getApplicationContext());
Listensize=blackstories.size();
anzahl_BS=Listensize;
if(blackstories != null && blackstories.size() > 0) { //check if we have any notes!
na = new BlackstoryAdapter(this, layout.item_layout1, blackstories);
try{
mListNotes.setAdapter(na);
}
catch (NullPointerException e){
Toast.makeText(this, "Irgendwas ist falsch2", Toast.LENGTH_SHORT).show();
}
//set click listener for items in the list, by clicking each item the note should be loaded into NoteActivity
try{
mListNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//run the NoteActivity in view/edit mode
fileName = ((Blackstory) mListNotes.getItemAtPosition(position)).getDateTime()
+ Utilities.FILE_EXTENSION;
Intent viewBlackstoryIntent = new Intent(getApplicationContext(), number1.class);
viewBlackstoryIntent.putExtra(Utilities.EXTRAS_NOTE_FILENAME, fileName);
startActivity(viewBlackstoryIntent);
}
});
mListNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//ask user if he really wants to delete the note!
Dialog_delete(position, id);
return true;
}});}
catch (NullPointerException e){
Toast.makeText(this, "Irgendwas ist falsch3", Toast.LENGTH_SHORT).show();
}}
else { //remind user that we have no notes!
Toast.makeText(getApplicationContext(), "you have no saved notes!\ncreate some new notes :)"
, Toast.LENGTH_SHORT).show();
}
firstOpen=false;
}
My Utilities (to save and load notes):
public class Utilities {
public static final String FILE_EXTENSION = ".bin";
public static final String EXTRAS_NOTE_FILENAME = "EXTRAS_NOTE_FILENAME";
public static boolean saveBlackstory(Context context, Blackstory blackstory){
String fileName = String.valueOf(blackstory.getDateTime()) + FILE_EXTENSION;
FileOutputStream fos;
ObjectOutputStream oos;
try{
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(blackstory);
oos.close();
}
catch (IOException e) {
e.printStackTrace();
Log.w("Failed","");
return false;
}
return true;
}
public static ArrayList<Blackstory> getAllSavedBlackstory(Context context) {
ArrayList<Blackstory> blackstories = new ArrayList<>();
File filesDir = context.getFilesDir();
ArrayList<String> blackstoryFiles = new ArrayList<>();
int size = blackstoryFiles.size();
//add .bin files to the noteFiles list
for(String file : filesDir.list()) {
if(file.endsWith(FILE_EXTENSION)) {
blackstoryFiles.add(file);
Log.w("Included", ""+file);
}
}
//read objects and add to list of notes
FileInputStream fis;
ObjectInputStream ois;
for (int i = 0; i < blackstoryFiles.size(); i++) {
try{
fis = context.openFileInput(blackstoryFiles.get(i));
ois = new ObjectInputStream(fis);
blackstories.add((Blackstory)ois.readObject());
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
return blackstories;
}
public static Blackstory getBlackstoryByFileName(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
if(file.exists() && !file.isDirectory()) { //check if file actually exist
Log.v("UTILITIES", "File exist = " + fileName);
FileInputStream fis;
ObjectInputStream ois;
try { //load the file
fis = context.openFileInput(fileName);
ois = new ObjectInputStream(fis);
Blackstory note = (Blackstory) ois.readObject();
fis.close();
ois.close();
return note;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
public static boolean deleteFile(Context context, String fileName) {
File dirFiles = context.getFilesDir();
File file = new File(dirFiles, fileName);
if(file.exists() && !file.isDirectory()) {
return file.delete();
}
return false;
}
And my Adapter:
public class BlackstoryAdapter extends ArrayAdapter<Blackstory> {
public static final int WRAP_CONTENT_LENGTH = 50;
public BlackstoryAdapter(Context context, int resource, List<Blackstory> blackstories) {
super(context, resource, blackstories);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_layout1, null);
}
Blackstory blackstory = getItem(position);
if(blackstory != null) {
TextView title = convertView.findViewById(R.id.single_titel);
title.setText(blackstory.getTitel());
}
return convertView;
}
My Blackstory.java:
public class Blackstory implements Serializable {
private String mTitel;
private String mStory;
private String mLosung;
private long mDateTime;
public Blackstory(long dateInMills, String titel, String story, String losung) {
mDateTime = dateInMills;
mTitel = titel;
mStory = story;
mLosung = losung;
}
public void setDateTime(long dateTime) {
mDateTime = dateTime;
}
public long getDateTime() {
return mDateTime;
}
public String getDateTimeFormatted(Context context) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"
, context.getResources().getConfiguration().locale);
formatter.setTimeZone(TimeZone.getDefault());
return formatter.format(new Date(mDateTime));
}
public String getTitel() {
return mTitel;
}
public void setTitel(String titel) {
mTitel = titel;
}
public String getStory() {
return mStory;
}
public void setStory(String story) {
mStory = story;
}
public String getLosung() {
return mLosung;
}
public void setLosung(String losung) {
mLosung = losung;
}
}
There need not be getCount() method as pointed out by AguThadeus. The array data is passed to the superclass so that will take care of the number of views.
I examined similar subjects, but I couldn't do it. I'm trying to share .mp3 file with LongClick button. I found it for JPEG files. One guy created method for sharing jpeg file. How can I convert it for .mp3 files?
package com.example.tunch.trap;
import...
public class sansar extends AppCompatActivity {
private String yardik;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_sansar);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
yardik = createImageOnSDCard(R.raw.yardik_denizi);
final MediaPlayer yardikdenizi = MediaPlayer.create(this, R.raw.yardik_denizi);
Button btnYardik = (Button) findViewById(R.id.btnSansar_1);
btnYardik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yardikdenizi.isPlaying()){
yardikdenizi.seekTo(0);
}
yardikdenizi.start();
}
});
btnYardik.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Uri path= FileProvider.getUriForFile(sansar.this, "com.example.tunch.trap", new File(yardik));
Intent shareYardik = new Intent();
shareYardik.setAction(Intent.ACTION_SEND);
shareYardik.putExtra(Intent.EXTRA_TEXT,"Bu ses dosyasını gönderiyorum");
shareYardik.putExtra(Intent.EXTRA_STREAM, path);
shareYardik.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareYardik.setType("audio/mp3");
startActivity(Intent.createChooser(shareYardik, "Paylas.."));
return true;
}
});
}
private String createImageOnSDCard(int resID) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resID);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + resID +".mp3";
File file = new File(path);
try {
OutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e){
e.printStackTrace();
}
return file.getPath();
}
}
This is all Java code. createImageOnSDCard method is for images. I want to use it for my audio file (yardik_denizi.mp3). When I run this, it works but program is trying to send jpeg file. So it doesn't work literally :) How should I change that last part?
You need a method that copies a private raw resource content (R.raw.yardik_denizi) to a publicly readable file such that the latter can be shared with other applications:
public void copyPrivateRawResuorceToPubliclyAccessibleFile(#RawRes int resID,
#NonNull String outputFile) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resID);
outputStream = openFileOutput(outputFile, Context.MODE_WORLD_READABLE
| Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
and then:
copyPrivateRawResuorceToPubliclyAccessibleFile(R.raw.yardik_denizi, "sound.mp3");
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/*");
Uri uri = Uri.fromFile(getFileStreamPath("sound.mp3"));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Sound File"));
You should change the path for uri at
Uri path= FileProvider.getUriForFile(sansar.this, "com.example.tunch.trap", new File(change_it_path_to_yardik_denizi.mp3));
Finally i got the answer. I can send mp3 files to other apps with this code.
copyFiletoExternalStorage(R.raw.yardik_denizi, "yardik_denizi.mp3");
Uri path= FileProvider.getUriForFile(sansar.this,
"com.example.tunch.trap", new File(Environment.getExternalStorageDirectory() +
"/Android/data/yardik_denizi.mp3"));
Intent shareYardik = new Intent();
shareYardik.setAction(Intent.ACTION_SEND);
shareYardik.putExtra(Intent.EXTRA_TEXT,"Bu ses dosyasını gönderiyorum");
shareYardik.putExtra(Intent.EXTRA_STREAM, path);
shareYardik.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareYardik.setType("audio/mp3");
startActivity(Intent.createChooser(shareYardik, "Paylas.."));
And need to create a method to save data in external store.
private void copyFiletoExternalStorage (int resourceId, String resourceName){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/"
+ resourceName;
try{
InputStream in = getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am writing a mobil application which contains Dynamic Report part. I'm making it with Java ItextPdf Library but when I sent it to printer printer don't accept my file and giving a notification "File Type is not supported by this device." But When I send normal pdf file which is created by pc it is printing.
Printing Class
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
// Set job name, which will be displayed in the print queue
String jobName = " Document";
// Start a print job, passing in a PrintDocumentAdapter implementation
// to handle the generation of a print document
File path = context.getFilesDir();
File file = new File(path,"ss.pdf");
FileOutputStream os = null;
FileInputStream is = null;
try {
os = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Adisyon a = new Adisyon(os);
a.createFile();
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
printManager.print(jobName, new printAdapter(Siparis.this,is),
PrintAdapter Class
#TargetApi(Build.VERSION_CODES.KITKAT)
public class printAdapter extends PrintDocumentAdapter
{
Context context;
InputStream input;
public printAdapter(Context context,FileInputStream input)
{
this.context = context;
this.input = input;
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
OutputStream output = null;
try {
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee){
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("deneme.txt").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
callback.onLayoutFinished(pdi, true);
}
}
Itext Class
public class Adisyon {
FileOutputStream stream;
Context appContext = LoginActivity.getContextOfApplication();
public Adisyon(FileOutputStream stream) {
this.stream = stream;
}
public void createFile() {
try {
Document document = new Document();
PdfWriter.getInstance(document, stream);
document.open();
//addMetaData(document);
//addTitlePage(document);
//addContent(document);
createAdisyon(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
...
hello i'm trying to save pictures taken from url on my application, but when i try to access the memory to place the data, an error comes out
unable to decode stream java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory)
this is my DownloadManager Class
public static ArrayList<String> urls = new ArrayList<String>();
public static OnDownloadCompleteListener downloadCompleteListener;
public static void copyFile(String sourceFile, String destinationFile) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void initialize() {
downloadCompleteListener = new OnDownloadCompleteListener() {
#Override
public void onDownloadComplete(String url, String localPath) {
Log.i("LOG", "Image Download Complete, Original URL: " + url + ", Save Path: " + localPath);
String newPath = localPath.replace("/temp/", "/final/");
copyFile(localPath, newPath);
String filename = HelperString.getFileName(localPath);
new File(localPath).delete();
Set<ImageView> imageViews = AdapterSerials.imageMap.keySet();
for (ImageView imageView: imageViews) {
if (AdapterSerials.imageMap.get(imageView).equals(filename)) {
if (imageView != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(newPath, options);
imageView.setImageBitmap(bitmap);
}
}
}
}
};
}
public static void addToDownloadList(String url, ImageView imgLogo) {
String filename = HelperString.getFileName(url);
AdapterSerials.imageMap.put(imgLogo, filename);
if (urls.contains(url)) {
return;
}
if (new File(G.DIR_FINAL + "/" + filename).exists()) {
return;
}
urls.add(url);
DownloadRequest downloadRequest = new DownloadRequest()
.downloadPath("http://87.236.215.180/mazi/" + url)
.filepath(G.DIR_TEMP + "/" + filename)
.listener(downloadCompleteListener)
.download();
}
this is my DownloadRequest Class :
public class DownloadRequest {
private int downloadedSize;
private int totalSize;
private int percent;
public int getDownloadedSize() {
return downloadedSize;
}
public int getTotalSize() {
return totalSize;
}
public int getPercent() {
return percent;
}
public DownloadRequest download() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
totalSize = connection.getContentLength();
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = new FileOutputStream(filepath);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;
percent = (int) (100.0f * (float) downloadedSize / totalSize);
if (percent == 100 && listener != null) {
G.HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onDownloadComplete(downloadPath, filepath);
}
});
}
if (simulate) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
outputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return this;
}
private String downloadPath;
private String filepath;
private OnDownloadCompleteListener listener;
private boolean simulate;
public DownloadRequest downloadPath(String value) {
downloadPath = value;
return this;
}
public DownloadRequest filepath(String value) {
filepath = value;
return this;
}
public DownloadRequest listener(OnDownloadCompleteListener value) {
listener = value;
return this;
}
public DownloadRequest simulate(boolean value) {
simulate = value;
return this;
}
And this is my G class :
public class G extends Application {
public static Context context;
public static final String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_APP = SDCARD + "/serial";
public static final String DIR_CACHE = DIR_APP + "/cache";
public static LayoutInflater inflater;
public static final Handler HANDLER = new Handler();
public static Activity currentActivity;
public static StructSerials selectedSerials;
public static StructFavSerials selectedFavSerials;
public static ArrayList<StructComment> rates = new ArrayList<StructComment>();
public static final int DOWNLOAD_BUFFER_SIZE = 8 * 1024;
public static final String DIR_FINAL = DIR_APP + "/final";
public static final String DIR_TEMP = DIR_APP + "/temp";
public static String android_id;
public static SharedPreferences preferences;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
preferences = PreferenceManager.getDefaultSharedPreferences(context);
initImageLoader(getApplicationContext());
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
android_id = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
new File(DIR_APP).mkdirs();
new File(DIR_CACHE).mkdirs();
new File(DIR_TEMP).mkdirs();
new File(DIR_FINAL).mkdirs();
DownloadManager.initialize();
}
remember add this permission into your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />