Download and save PDF on sdcard not found - java

I'm trying to download a pdf from an url and then save and read it. But I get the error java.io.IOException: /storage/emulated/0/pdf/menu.pdf not found as file or resource. when I try to read it. Any idea ?
Here is my 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();
}
}
}
And the line to download and read the pdf :
String extStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "menu.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf", file);
PdfReader reader = new PdfReader(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pdf/menu.pdf");
Here is the error :
05-02 13:59:01.138 16747-16747/? I/art: Not late-enabling -Xcheck:jni (already on)
05-02 13:59:01.139 16747-16747/? W/art: Unexpected CPU variant for X86 using defaults: x86
05-02 13:59:01.676 16747-16747/com.example.yohannmbp.ematoufaire I/InstantRun: starting instant run server: is main process
05-02 13:59:01.868 16747-16747/com.example.yohannmbp.ematoufaire W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
05-02 13:59:02.440 16747-16787/com.example.yohannmbp.ematoufaire D/NetworkSecurityConfig: No Network Security Config specified, using platform default
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire I/OpenGLRenderer: Initialized EGL, version 1.4
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire D/OpenGLRenderer: Swap behavior 1
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire D/OpenGLRenderer: Swap behavior 0
05-02 13:59:03.029 16747-16747/com.example.yohannmbp.ematoufaire W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
05-02 13:59:11.011 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: java.io.IOException: No such file or directory
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.File.createNewFile(File.java:948)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.MenuFragment.onCreateView(MenuFragment.java:106)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Looper.loop(Looper.java:154)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
05-02 13:59:11.015 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: java.io.FileNotFoundException: /storage/emulated/0/pdf/menu.pdf (No such file or directory)
05-02 13:59:11.015 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.open(Native Method)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.Downloader.DownloadFile(Downloader.java:18)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.MenuFragment.onCreateView(MenuFragment.java:110)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Looper.loop(Looper.java:154)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
05-02 13:59:11.088 16747-16752/com.example.yohannmbp.ematoufaire I/art: Do partial code cache collection, code=30KB, data=29KB
05-02 13:59:11.089 16747-16752/com.example.yohannmbp.ematoufaire I/art: After code cache collection, code=23KB, data=25KB
05-02 13:59:11.089 16747-16752/com.example.yohannmbp.ematoufaire I/art: Increasing code cache capacity to 128KB
05-02 13:59:11.127 16747-16747/com.example.yohannmbp.ematoufaire I/System.out: java.io.IOException: /storage/emulated/0/pdf/menu.pdf not found as file or resource.

private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
**strong text** #Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(AppConstant.BASE_URL + URLEncoder.encode(sUrl[0], "UTF-8"));
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
fileName = sUrl[0].substring(sUrl[0].lastIndexOf("/") + 1,
sUrl[0].length());
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context, "Download error: File is not Found.", Toast.LENGTH_LONG).show();
else {
new AlertDialog.Builder(context)
//.setTitle("Delete entry")
.setMessage("File Downloaded Successfully. Do you want to open it?")
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "There is no app registered to handle the type of file selected.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
}

try this
downloadTask = new DownloadTask();
downloadTask.execute("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf", "", "");
private class DownloadTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ll_view.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
File sourcePath = Environment.getExternalStorageDirectory();
File path = new File(sourcePath + "/" + Constants.DIR_NAME + "/");
path.mkdir();
File file = new File(path, "/ecute("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf");
if (file.exists()) {
file.delete();
}
output = new FileOutputStream(file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ll_view.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(final Integer... values) {
super.onProgressUpdate(values);
// Log.e("progressing", "" + values[0]);
// edt_search.setText("" + values[0]);
// new Thread(new Runnable() {
// public void run() {
progressBar.setProgress(values[0]);
// tv_downloading.setText("" + values[0] + "%");
// }
// }).start();
}
#Override
protected void onCancelled(String s) {
super.onCancelled(s);
}
#Override
protected void onCancelled() {
super.onCancelled();
}
}
if your target and compile sdk higher than lolipop then you have to add request permission code before download refer this link and read and write external storage permission required

Related

Only the 'Oreo' Version of Android is giving me a java.io.FileNotFoundException

I am downloading images to smartphone. For versions older than Oreo, there's no problem. But for Oreo, my code isn't not working. I tried this code in Emulator:
I implemented a function to save an image to external storage.
private void saveImageToExternalStorage(Bitmap finalBitmap,String name) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/xx");
myDir.mkdirs();
String fname = name + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
I am asking for permission request with Dexter Library. If permission is granted then I run task.
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
if (!prefs.getBoolean("firstTime", false)) {
task.execute();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MainActivity.this, "You need to allow permission if you want to use camera", Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
Toast.makeText(MainActivity.this, "You need to allow permission if you want to use camera", Toast.LENGTH_LONG).show();
}
}).check();
Then I save images with asynctask.
final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog;
#Override
protected void onPreExecute()
{
this.dialog = new ProgressDialog(MainActivity.this);
this.dialog.setMessage(getString(R.string.newfeature));
this.dialog.setCancelable(false);
this.dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
// cancel AsyncTask
cancel(false);
}
});
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
// do your stuff
Bitmap myBitmap2 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im2);
saveImageToExternalStorage(myBitmap2,"imag2");
myBitmap2.recycle();
Bitmap myBitmap3 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im3);
saveImageToExternalStorage(myBitmap3,"image3");
myBitmap3.recycle();
Bitmap myBitmap4 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im4);
saveImageToExternalStorage(myBitmap4,"image4");
myBitmap4.recycle();
Bitmap myBitmap5= BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im5);
saveImageToExternalStorage(myBitmap5,"image5");
myBitmap5.recycle();
Bitmap myBitmap6 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im6);
saveImageToExternalStorage(myBitmap6,"image6");
myBitmap6.recycle();
Bitmap myBitmap7 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im7);
saveImageToExternalStorage(myBitmap7,"image7");
myBitmap7.recycle();
Bitmap myBitmap8 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im8);
saveImageToExternalStorage(myBitmap8,"image8");
myBitmap8.recycle();
Bitmap myBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im1);
saveImageToExternalStorage(myBitmap,"image1");
myBitmap.recycle();
Bitmap myBitmap9 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im9);
saveImageToExternalStorage(myBitmap9,"image9");
myBitmap9.recycle();
Bitmap myBitmap10 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im10);
saveImageToExternalStorage(myBitmap10,"image10");
myBitmap10.recycle();
Bitmap myBitmap11 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im11);
saveImageToExternalStorage(myBitmap11,"image11");
myBitmap11.recycle();
Bitmap myBitmap12 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im12);
saveImageToExternalStorage(myBitmap12,"image12");
myBitmap12.recycle();
Bitmap myBitmap13 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im13);
saveImageToExternalStorage(myBitmap13,"image13");
myBitmap13.recycle();
Bitmap myBitmap14 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.im14);
saveImageToExternalStorage(myBitmap14,"image14");
myBitmap14.recycle();
return null;
}
#Override
protected void onPostExecute(Void result)
{
//called on ui thread
if (this.dialog != null) {
this.dialog.dismiss();
}
}
#Override
protected void onCancelled()
{
//called on ui thread
if (this.dialog != null) {
this.dialog.dismiss();
}
}
};
Finally it gives this error in Oreo emulator:
09-18 12:32:52.167 5818-5936/x.x W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Pictures/xx/imag2.jpg (No such file or directory)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at java.io.FileOutputStream.open0(Native Method)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at java.io.FileOutputStream.open(FileOutputStream.java:308)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:238)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:180)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at x.x.MainActivity.saveImageToExternalStorage(MainActivity.java:776)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at x.x.MainActivity.access$000(MainActivity.java:62)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at x.x.MainActivity$1.doInBackground(MainActivity.java:119)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at x.x.MainActivity$1.doInBackground(MainActivity.java:89)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
09-18 12:32:52.168 5818-5936/x.x W/System.err: at java.lang.Thread.run(Thread.java:764)
For older version emulators or older version smartphones there is no problem. Images are saved correctly. I did not try with real oreo smartphone but for emulator - oreo it gives this problem. As a result, how can I solve my problem? What is the main reason of this situation? Permissions? saving image to external storage? or creating file - folder?

Not moving to profile screen even after giving genuine credentials in login page

In database we have login details {"email":"nagu#gmail.com","pwd":"12345"}.By using REST services I got the URL, I need to validate the credentials and move to next screen. But unable to move to next screen so please help me
public class LoginScreen extends DIBaseActivty {
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
private EditText editTextUsername;
private EditText editTextPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
editTextUsername = (EditText)findViewById(R.id.emaiId);
editTextPassword = (EditText)findViewById(R.id.password);
}
public void buttonLogin (View arg0)
{
final String username = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
new TaskLogin().execute(username,password);
}
public class TaskLogin extends AsyncTask<String,String,String>
{
ProgressDialog pdLoading = new ProgressDialog(LoginScreen.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\t Loading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try{
url = new URL("http://localhost:8080/RestSpring/DialysisInfo/login");
} catch (MalformedURLException e) {
e.printStackTrace();
return "exception";
}
try{
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username",params[0])
.appendQueryParameter("password",params[1]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1)
{
e1.printStackTrace();
return "Exception";
}
try{
int response_code = conn.getResponseCode();
if(response_code==HttpURLConnection.HTTP_OK)
{
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line= reader.readLine())!=null)
{
result.append(line);
}
return (result.toString());
} else { return ("unsuccessful");
}
} catch (IOException e)
{
e.printStackTrace();
return "Exception";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
if(result.equalsIgnoreCase("true"))
{
Intent intent = new Intent(LoginScreen.this,DIUserProfile.class);
startActivity(intent);
LoginScreen.this.finish();
}else if (result.equalsIgnoreCase("false"))
{
Toast.makeText(LoginScreen.this, "Invalid email or password", Toast.LENGTH_LONG).show();
} else if(result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful"))
{
Toast.makeText(LoginScreen.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
}
Here is my error log
02-02 10:42:56.660 25016-27263/com.dialysis
W/System.err: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8080) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
02-02 10:42:56.663 25016-27263/com.dialysis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
02-02 10:42:56.663 25016-27263/com.dialysis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at java.net.Socket.connect(Socket.java:882)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.dialysis.renalteam.app.ui.activities.LoginScreen$TaskLogin.doInBackground(LoginScreen.java:86)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.dialysis.renalteam.app.ui.activities.LoginScreen$TaskLogin.doInBackground(LoginScreen.java:49)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.lang.Thread.run(Thread.java:818)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: ... 20 more
02-02 10:42:56.714 25016-25071/com.dialysis W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 10:42:56.714 25016-25071/com.dialysis W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43cbb00, error=EGL_SUCCESS
02-02 10:42:57.143 25016-25071/com.dialysis W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 10:42:57.144 25016-25071/com.dialysis W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43cbd20, error=EGL_SUCCESS
02-02 10:52:41.787 25016-25030/com.dialysis W/art: Suspending all threads took: 5.515ms
From your logcat:
java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8080) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)
Your Android app failed to connect to the server. Set debug breakpoints and check the following:
Url is correct
Method name is correct
Parameters key and value are correct
Server is working fine or not
Since you have not specified you are connected to a server from the device or emulator so I guess you are using your application in the emulator.
If you are referring your localhost on your system from the Android emulator then you have to use http://10.0.2.2:8080/ Because Android emulator runs in a Virtual Machine therefore here 127.0.0.1 or localhost will be emulator's own loopback address.
Replace: url = http://localhost:8080/RestSpring/DialysisInfo/login"
With : url = "http://10.0.2.2:8080/RestSpring/DialysisInfo/login"

File.createNewFile() method throws exception in Android M

I have a problem to create file in Android M.
I use Nexus 9 with Android 6.0.1. Then I set in my project as below:
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
build.gradle
android {
defaultConfig {
targetSdkVersion 23
...
}
}
MainActivity.Java
public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String rootPath = storagePath + "/test";
String fileName = "/test.zip";
File root = new File(rootPath);
if(!root.mkdirs()) {
Log.i("Test", "This path is already exist: " + root.getAbsolutePath());
}
File file = new File(rootPath + fileName);
try {
if (!file.createNewFile()) {
Log.i("Test", "This file is already exist: " + file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Build was success and application was launched, but I got exception message like this:
IOExceiption
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: java.io.IOException: open failed: ENOENT (No such file or directory)
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: at java.io.File.createNewFile(File.java:939)
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: at com.sample.myapplication.MainActivity.onCreate(MainActivity.java:36)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.Activity.performCreate(Activity.java:6251)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.-wrap11(ActivityThread.java)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.os.Looper.loop(Looper.java:148)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at java.lang.reflect.Method.invoke(Native Method)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at libcore.io.Posix.open(Native Method)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at java.io.File.createNewFile(File.java:932)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: ... 13 more
How can I solve this problem? I don't catch what I miss....
Please help.
Updated
Replace storagePath to access scoped storage, for Android 10.
Refer this document for more detail.
Thanks, laalto.
I didn't know about runtime permission.
I solved exception like this:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Request user permissions in runtime */
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
100);
/* Request user permissions in runtime */
createTestFile();
}
#TargetApi(23)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// User checks permission.
} else {
Toast.makeText(MainActivity.this, "Permission is denied.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void createTestFile() {
// String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
// If Target API level is 29(Android 10),
// you should access local path in scoped storage mode.
File localStorage = getExternalFilesDir(null);
if (localStorage == null) { return; }
String storagePath = localStorage.getAbsolutePath();
String rootPath = storagePath + "/test";
String fileName = "/test.zip";
File root = new File(rootPath);
if(!root.mkdirs()) {
Log.i("Test", "This path is already exist: " + root.getAbsolutePath());
}
File file = new File(rootPath + fileName);
try {
int permissionCheck = ContextCompat.checkSelfPermission(
MainActivity.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
if (!file.createNewFile()) {
Log.i("Test", "This file is already exist: " + file.getAbsolutePath());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
It works!
I was having the same problem. I got an IOException on the file.createNewFile. A closer look at the exception reveals that it was due to "permissions denied". I was writing to my getFilesDir, so I shouldn't need an in the android manifest to accomplish this task. I of course added both READ and WRITE permissions for external storage, and of course, that didn't fix the problem.
I had been testing the code using a NEXUS 6 emulator with sdk 26. Without changing any code, I tried testing using a PIXEL C emulator with sdk 26 and the problem did not occur. So there seems to be some problem with my Nexus 6 emulator.
I suspect that this hasn't always been a problem and that this emulator instance got corrupted, but I haven't verified that. I did take the time to look at the linux file permission on the directories I was creating the file into an it reported "drwxrwxrwx", which is correct. I will add that I've implemented a FileProvider with paths to the directory I'm trying to create the new file at. The code I'm using pretty much looks like the code that Kae10 shows.
I traced the problem down to this code in UnixFileSystem:
public boolean createFileExclusively(String path) throws IOException {
BlockGuard.getThreadPolicy().onWriteToDisk();
return createFileExclusively0(path);
}
the exception is thrown from createFileExlussively0, which I not able to debug into. I haven't investigated this issue any further (i.e. 1.) would deleting the avd instance and recreating it help, my guess is that might, 2.) is there a later system image I should be using?)

Error getting content from .txt file from URL

URL scoreU = null;
try {
scoreU = new URL("http://m.uploadedit.com/b044/1422550899503.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(
scoreU.openStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
That's my code related to getting the text from the URL. It's the first time I have done this and I cannot understand my mistake. (I had to surround almost everything with a try/catch .
ERROR:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wc.gap.worldcupfixture/com.wc.gap.worldcupfixture.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at java.net.URL.openStream(URL.java:470)
at com.wc.gap.worldcupfixture.MainActivity.onCreate(MainActivity.java:102)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
new InputStreamReader(scoreU.openStream()));
Android doesn't allow network requests on the main thread as it can cause UI unresponsiveness. Instead you have to do the work on a background thread, but this is pretty easy with an AsyncTask, for example:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// Start the task here
new URLDataLoader().execute(theURL);
}
private class URLDataLoader extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... params) {
URL theURL = params[0];
// Do your network stuff here to get the data
return theData;
}
#Override
protected void onPostExecute(String data) {
// Use the data here
}
}
}
Use this code:-
try {
URL url = new URL("http://m.uploadedit.com/b044/1422550899503.txt");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
connection = (HttpURLConnection) urlConnection;
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String urlString = "";
String current;
while ((current = in.readLine()) != null) {
urlString += current;
}
System.out.println(urlString);
} catch (IOException e) {
e.printStackTrace();
}

How to implement a internet audio stream buffer?

I have this doInBackground method which records audio streams from the internet. The main work is being done inside while (len != -1) { }. This works fine however the buffer = new byte[] doesn't work as I expected - when the connection is interrupted the IOException is called immidiately and the buffer is not used anymore. How can I make this buffer to "feed" my code till it is empty? I want to have the same behavior like it is in audio players; so first when you connect to the stream (it is buffering), then playing and if the connection is interrupted it is still playing from the buffer (till it is empty).
Recorder:
protected Boolean doInBackground(String... StringUrls) {
boolean fdetermined = false;
Environment env = new Environment();
Calendar c = Calendar.getInstance();
BufferedOutputStream bufOutstream = null;
buffer = new byte[1024 * 10];
int len=-1;
InputStream in = null;
URLConnection conn = null;
try{
conn = new URL(StringUrls[0]).openConnection();
conn.setConnectTimeout(5000);
in = conn.getInputStream();
len = in.read(buffer);
File dir = new File(env.getExternalStorageDirectory() + "/somewhere");
if (!dir.exists()) {
dir.mkdir();
}
filename = env.getExternalStorageDirectory()+"/somewhere/file";
bufOutstream = new BufferedOutputStream(new FileOutputStream(new File(filename)));
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
while (len != -1) {
if(in != null && buffer != null && bufOutstream != null) {
try {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) {
Recorder.this.stopSelf();
break;
}
} catch (IOException e) {
e.printStackTrace();
conn = null;
in = null;
}
}
}
try{
if(bufOutstream != null) {
bufOutstream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
IO Exception:
12-16 14:37:16.999 31950-32021/com.app.example W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-16 14:37:17.059 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:542)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
12-16 14:37:17.119 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
12-16 14:37:17.119 31950-32021/com.app.example W/System.err﹕ at java.io.BufferedInputStream.read(BufferedInputStream.java:304)
12-16 14:37:17.149 31950-32021/com.app.example W/System.err﹕ at libcore.net.http.UnknownLengthHttpInputStream.read(UnknownLengthHttpInputStream.java:41)
12-16 14:37:17.149 31950-32021/com.app.example W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at com.app.example.Recorder$RecordTask.doInBackground(Recorder.java:376)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at com.app.example.Recorder$RecordTask.doInBackground(Recorder.java:288)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:131)
12-16 14:37:17.209 31950-32021/com.app.example W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
12-16 14:37:17.209 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:503)
I have added finally block below:
while (len != -1) {
if(in != null && buffer != null && bufOutstream != null) {
try {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) {
Recorder.this.stopSelf();
break;
}
} catch (IOException e) {
e.printStackTrace();
conn = null;
in = null;
}
finally{
//do your work here. This block will execute no matter of what exception is thrown
try{
if(bufOutstream != null) {
bufOutstream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Categories