Android downloading a file getting a FileNotFoundException - java

else if (v.getId() == R.id.update) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File("/sdcard/"+"download/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"test.txt");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this code keeps coming out with the FileNotFoundException, but the file is there, if you follow the url you can see it.
does it have to be hosted in a specific way? or is it something wrong with the way im getting it
EDIT: this is the logcat message
12-14 22:29:19.890: W/System.err(24557): java.io.FileNotFoundException: http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt
12-14 22:29:19.890: W/System.err(24557): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
12-14 22:29:19.890: W/System.err(24557): at com.MasterZangetsu.kentrocksoc.MainActivity.onClick(MainActivity.java:99)
12-14 22:29:19.890: W/System.err(24557): at android.view.View.performClick(View.java:3591)
12-14 22:29:19.890: W/System.err(24557): at android.view.View$PerformClick.run(View.java:14263)
12-14 22:29:19.895: W/System.err(24557): at android.os.Handler.handleCallback(Handler.java:605)
12-14 22:29:19.895: W/System.err(24557): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 22:29:19.895: W/System.err(24557): at android.os.Looper.loop(Looper.java:137)
12-14 22:29:19.895: W/System.err(24557): at android.app.ActivityThread.main(ActivityThread.java:4507)
12-14 22:29:19.895: W/System.err(24557): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 22:29:19.895: W/System.err(24557): at java.lang.reflect.Method.invoke(Method.java:511)
12-14 22:29:19.895: W/System.err(24557): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-14 22:29:19.895: W/System.err(24557): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
12-14 22:29:19.895: W/System.err(24557): at dalvik.system.NativeStart.main(Native Method)
12-14 22:29:20.170: W/WifiStateTracker(2010): getNetworkInfo : NetworkInfo: type: WIFI[], state: DISCONNECTED/DISCONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: false

comment the below piece of line in your code.
urlConnection.setDoOutput(true);

Related

Why does second http request is always null?

When I do http request in the PoolData(), request returns with data, and in AccoutData is always null.
In debugger, if I wait 1-2 sec after PoolData(), next request - returns not null. Method oder doesn't metter. Why is that, and how can I wait for 2nd request?
public void onClick(View v) {
new PoolData().execute();
}
private class PoolData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dataPool.clear();
}
#Override
protected Void doInBackground(Void... arg0) {
PoolData();
AccoutData();
return null;
}
private void PoolData(){
HttpHandler sh = new HttpHandler();
String statsBrowser = "http://api.electroneum.space/v1/stats/nonBrowser";
String browserStr = sh.makeServiceCall(statsBrowser);
//parsing...
}
private void AccoutData(){
HttpHandler sh = new HttpHandler();
String statsAddress = "http://api.electroneum.space/v1/stats/address/" + settings.getString(lp, "n/a");
String addressStr = sh.makeServiceCall(statsAddress);
//parsing...
}
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
Log.e(TAG, "Responce: " + response);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.toString());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
12-14 14:27:18.941 6624-6651/dev.flair.the.electroneumspacepool
I/OpenGLRenderer: Initialized EGL, version 1.4
12-14 14:27:18.956 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Get enable program binary service property (1)
12-14 14:27:18.956 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Initializing program atlas...
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Program binary detail: Binary length is 169916, program map length is 152.
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Succeeded to mmap program binaries. File descriptor is 54, and path is /dev/ashmem .
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: No need to use file discriptor anymore, close fd(54).
12-14 14:27:18.979 6624-6624/dev.flair.the.electroneumspacepool 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
12-14 14:27:19.035 6624-6651/dev.flair.the.electroneumspacepool W/MALI: glDrawArrays:714: [MALI] glDrawArrays takes more than 5ms here. Total elapse time(us): 10394
12-14 14:27:23.448 6624-6672/dev.flair.the.electroneumspacepool I/System.out: url:http://api.electroneum.space/v1/stats/address/hVDo4adTwWsPK1
12-14 14:27:23.452 6624-6672/dev.flair.the.electroneumspacepool I/System.out: open:http://api.electroneum.space/v1/stats/address/hVDo4adTwWsPK1
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk hostname=api.electroneum.space; servname=(null); cache_mode=(null), netid=0; mark=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo( app_uid:10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() uid prop:
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() getuid():10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk hostname=api.electroneum.space; servname=(null); cache_mode=(null), netid=0; mark=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo( app_uid:10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() uid prop:
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() getuid():10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
12-14 14:27:23.457 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo: api.electroneum.space get result from proxy >>
12-14 14:27:23.457 6624-6672/dev.flair.the.electroneumspacepool I/System.out: propertyValue:true
12-14 14:27:23.459 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [CDS]connect[api.electroneum.space/104.27.156.123:80] tm:90
12-14 14:27:23.497 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest>>
12-14 14:27:23.497 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest<<
12-14 14:27:23.612 6624-6672/dev.flair.the.electroneumspacepool E/HttpHandler: MalformedURLException: java.io.BufferedInputStream#3d6a54f5
12-14 14:27:23.613 6624-6672/dev.flair.the.electroneumspacepool I/NetworkManagementSocketTagger: untagSocket(56)
12-14 17:08:49.897 19931-20613/dev.flair.the.electroneumspacepool E/HttpHandler: Responce:
{"stats":{"data...."}}
12-14 17:08:49.899 19931-20613/dev.flair.the.electroneumspacepool I/System.out: url:http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:49.900 19931-20613/dev.flair.the.electroneumspacepool I/System.out: open:http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:49.901 19931-20613/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest>>
12-14 17:08:49.901 19931-20613/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest<<
12-14 17:08:50.008 19931-20613/dev.flair.the.electroneumspacepool E/HttpHandler: IOException: java.io.FileNotFoundException: http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:50.008 19931-20613/dev.flair.the.electroneumspacepool E/MainActivity: Response from browser: null

java.lang.RuntimeException: ImageReaderContext is not initialized

mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 4);
mVirtualDisplay = mMediaProjection.createVirtualDisplay(TAG, mWidth, mHeight, mDPI,DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), getimg(), null);
image = mImageReader.acquireLatestImage();
12-14 13:57:06.893: W/System.err(15177): java.lang.RuntimeException:
ImageReaderContext is not initialized 12-14 13:57:06.927:
W/System.err(15177): at
android.media.ImageReader.nativeImageSetup(Native Method) 12-14
13:57:06.961: W/System.err(15177): at
android.media.ImageReader.acquireNextSurfaceImage(ImageReader.java:298)
12-14 13:57:06.992: W/System.err(15177): at
android.media.ImageReader.acquireNextImage(ImageReader.java:344) 12-14
13:57:07.024: W/System.err(15177): at
com.zed1.luaservice.ScreenService.acquireLatestImage(ScreenService.java:109)
12-14 13:57:07.056: W/System.err(15177): at
com.top.colour.ColorUtil.snap(ColorUtil.java:89) 12-14 13:57:07.087:
W/System.err(15177): at
com.top.colour.FindImageFuzzy.execute(FindImageFuzzy.java:55) 12-14
13:57:07.111: W/System.err(15177): at
org.keplerproject.luajava.LuaState._call(Native Method) 12-14
13:57:07.138: W/System.err(15177): at
org.keplerproject.luajava.LuaState.call(LuaState.java:602) 12-14
13:57:07.165: W/System.err(15177): at
com.zed1.server.LuaService.call(LuaService.java:33) 12-14
13:57:07.193: W/System.err(15177): at
com.zed1.server.LuaThread.callLua(LuaThread.java:71) 12-14
13:57:07.220: W/System.err(15177): at
com.zed1.server.LuaThread.run(LuaThread.java:49)
I had the same issue, however not on my device but on one of my customers. I found someting on this site. They use the following code:
Image image;
try {
image = mImageReader.acquireLatestImage();
} catch (RuntimeException e) {
/* In API level 23 or below, it will throw "java.lang.RuntimeException:
ImageReaderContext is not initialized" when ImageReader is closed. To make the
behavior consistent as newer API levels, we make it return null Image instead.*/
if (isImageReaderContextNotInitializedException(e)) {
image = null;
} else {
throw e; // only catch RuntimeException:ImageReaderContext is not initialized
}
}
if (image == null) {
return null;
}
private boolean isImageReaderContextNotInitializedException(RuntimeException e) {
return "ImageReaderContext is not initialized".equals(e.getMessage());
}
I don't know yet, if it solves the issue, because the crash does not occur on my device. Let me know if it helps.

FileNotFoundException while unzipping file in android

I am getting error FileNotFoundException open failed: EROFS (Read-only file system) while unzipping file in android. I have lost my time but not got solution. please help me for resolve my problem.
public class UnZipActivity extends Activity {
private String zipFile = Environment.getExternalStorageDirectory() + "/database/db.zip";
private String unzipLocation = Environment.getExternalStorageDirectory() + "/database/";
Button btnSelectPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getimage);
Log.d("Unzip", "Zipfile: " + zipFile);
Log.d("Unzip", "location: " + unzipLocation);
btnSelectPhoto = (Button)findViewById(R.id.btnSelectPhoto);
btnSelectPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
unzip();
}
});
}
public void unzip() {
FileInputStream fin = null;
try {
fin = new FileInputStream(new File(zipFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ZipInputStream zin = new ZipInputStream(fin);
BufferedInputStream in = new BufferedInputStream(zin);
ZipEntry ze = null;
try {
while ((ze = zin.getNextEntry()) != null) {
Log.v("Unzip", "Unzipping " + ze.getName());
if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
zin.closeEntry();
FileOutputStream fout = new FileOutputStream(new File(unzipLocation + ze.getName()));
BufferedOutputStream out = new BufferedOutputStream(fout);
/*for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}*/
byte b[] = new byte[1024];
int n;
while ((n = in.read(b,0,1024)) >= 0) {
out.write(b,0,n);
}
zin.closeEntry();
fout.close();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
zin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void _dirChecker(String dir) {
File f = new File(unzipLocation + dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
}
Error
08-21 02:40:46.934: W/System.err(8495): java.io.FileNotFoundException: /storage/sdcard/database/objectdetail_create.sql: open failed: EROFS (Read-only file system)
08-21 02:40:46.934: W/System.err(8495): at libcore.io.IoBridge.open(IoBridge.java:409)
08-21 02:40:46.944: W/System.err(8495): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
08-21 02:40:46.944: W/System.err(8495): at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
08-21 02:40:46.954: W/System.err(8495): at com.example.buttonstyleapp.UnZipActivity.unzip(UnZipActivity.java:71)
08-21 02:40:46.954: W/System.err(8495): at com.example.buttonstyleapp.UnZipActivity$1.onClick(UnZipActivity.java:43)
08-21 02:40:46.954: W/System.err(8495): at android.view.View.performClick(View.java:4240)
08-21 02:40:46.954: W/System.err(8495): at android.view.View$PerformClick.run(View.java:17721)
08-21 02:40:46.954: W/System.err(8495): at android.os.Handler.handleCallback(Handler.java:730)
08-21 02:40:46.964: W/System.err(8495): at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 02:40:46.964: W/System.err(8495): at android.os.Looper.loop(Looper.java:137)
08-21 02:40:46.974: W/System.err(8495): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-21 02:40:46.974: W/System.err(8495): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 02:40:46.974: W/System.err(8495): at java.lang.reflect.Method.invoke(Method.java:525)
08-21 02:40:46.974: W/System.err(8495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-21 02:40:46.984: W/System.err(8495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-21 02:40:46.984: W/System.err(8495): at dalvik.system.NativeStart.main(Native Method)
08-21 02:40:46.984: W/System.err(8495): Caused by: libcore.io.ErrnoException: open failed: EROFS (Read-only file system)
08-21 02:40:46.994: W/System.err(8495): at libcore.io.Posix.open(Native Method)
08-21 02:40:47.004: W/System.err(8495): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-21 02:40:47.014: W/System.err(8495): at libcore.io.IoBridge.open(IoBridge.java:393)
08-21 02:40:47.014: W/System.err(8495): ... 15 more
I have added permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

android sending files using socket

I am using wifi direct to send file between two android phones.
sender code:
OutputStream outputStream = null;
InputStream inputStream = null;
try {
outputStream = socket.getOutputStream();
inputStream = new FileInputStream(exportTempFile);
byte[] buf = new byte[socket.getSendBufferSize()];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
return 0;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
receiver code:
OutputStream outputStream = null;
InputStream inputStream = null;
try {
tempDir = new File(context.getCacheDir(), "temp");
if (!tempDir.exists()) {
tempDir.mkdir();
}
File file = new File(tempDir, "temp.zip");
file.createNewFile();
outputStream = new FileOutputStream(file);
inputStream = socket.getInputStream();
byte[] buf = new byte[socket.getReceiveBufferSize()];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
outputStream.flush();
}
return file;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
However, I always get "W/System.err" at the receiver side when running bytestream.copy . I wonder if I did something wrong. Did I close socket too early so the other side can not get data?
error is as below:
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:545)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at cc.megaman.led.service.ImportManager$ImportTask.doInBackground(ImportManager.java:420)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at cc.megaman.led.service.ImportManager$ImportTask.doInBackground(ImportManager.java:377)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:140)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)

Capture current Webview and save to SD card

ok so im trying capture the webview on button click, of the web page that is being displayed on my webview activity and save it to the sd card.
i have in my manifest the right permission to write external storage and all webview features are working just great, just when i attempt to capture the image.
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
WebViewClientDemoActivity.web.goBack();
break;
case R.id.button2:
WebViewClientDemoActivity.web.goForward();
break;
case R.id.button3:
WebViewClientDemoActivity.web.capturePicture();
//Capture Picture
Picture picture = WebViewClientDemoActivity.web.capturePicture();
//Create a new canvas
Canvas mCanvas = new Canvas();
//Draw the Picture into the Canvas
picture.draw(mCanvas);
//Create a Bitmap
Bitmap sreenshot = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(),Config.ARGB_8888);
//copy the content fron Canvas to Bitmap
//mCanvas.drawBitmap(mBitmapScreenshot, 0, 0, null);
mCanvas.drawBitmap(sreenshot, 0, 0, null);
//Save the Bitmap to local filesystem
if(sreenshot != null) {
ByteArrayOutputStream mByteArrayOpStream = new
ByteArrayOutputStream();
sreenshot.compress(Bitmap.CompressFormat.JPEG, 90,
mByteArrayOpStream);
try {
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Enlighten/Images");
folder.mkdirs();
// create a File object for the parent directory
File outputFile = new File(folder, "enlighten.jpg");
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(mByteArrayOpStream.toByteArray());
fos.close();
Toast.makeText(WebViewClientDemoActivity.this, "File Created", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(WebViewClientDemoActivity.this, "File Not Found", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Im getting this error message. (UPDATED)
10-15 11:33:10.336: W/System.err(20577): java.io.FileNotFoundException: /mnt/sdcard/Enlighten/Images/enlighten.jpg: open failed: ENOENT (No such file or directory)
10-15 11:33:10.336: W/System.err(20577): at libcore.io.IoBridge.open(IoBridge.java:406)
10-15 11:33:10.336: W/System.err(20577): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
10-15 11:33:10.336: W/System.err(20577): at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
10-15 11:33:10.336: W/System.err(20577): at com.jaisonbrooks.enlighten.WebViewClientDemoActivity.onClick(WebViewClientDemoActivity.java:374)
10-15 11:33:10.336: W/System.err(20577): at android.view.View.performClick(View.java:3565)
10-15 11:33:10.336: W/System.err(20577): at android.view.View$PerformClick.run(View.java:14165)
10-15 11:33:10.336: W/System.err(20577): at android.os.Handler.handleCallback(Handler.java:605)
10-15 11:33:10.336: W/System.err(20577): at android.os.Handler.dispatchMessage(Handler.java:92)
10-15 11:33:10.336: W/System.err(20577): at android.os.Looper.loop(Looper.java:137)
10-15 11:33:10.336: W/System.err(20577): at android.app.ActivityThread.main(ActivityThread.java:4517)
10-15 11:33:10.336: W/System.err(20577): at java.lang.reflect.Method.invokeNative(Native Method)
10-15 11:33:10.346: W/System.err(20577): at java.lang.reflect.Method.invoke(Method.java:511)
10-15 11:33:10.346: W/System.err(20577): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
10-15 11:33:10.346: W/System.err(20577): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
10-15 11:33:10.346: W/System.err(20577): at dalvik.system.NativeStart.main(Native Method)
10-15 11:33:10.346: W/System.err(20577): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
10-15 11:33:10.346: W/System.err(20577): at libcore.io.Posix.open(Native Method)
10-15 11:33:10.346: W/System.err(20577): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
10-15 11:33:10.346: W/System.err(20577): at libcore.io.IoBridge.open(IoBridge.java:390)
The openFileOutput() expects just the file name, without path separators, because it assumes that the file will be created in the app's private data area (if my memory doesn't cheat me then it should be /data/data/[your app package name]/files/).
To create a file on sdcard you can use FileOutputStream directly, see here for an example.
And another advice is that don't use hardcoded path like /mnt/sdcard because the absolute path of sdcard may vary on different devices, instead you should use Environment.getExternalStorageDirectory()
I resolved my issue with this code so it screen captures from inside the menu
public boolean onOptionsItemSelected (MenuItem item){
// Called when you tap a menu item
switch (item.getItemId()){
case R.id.settings_capture:
item.setIcon(R.drawable.capture);
//Resize the webview to the height of the webpage
int pageHeight = web.getContentHeight();
LayoutParams browserParams = web.getLayoutParams();
web.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, pageHeight));
//Capture the webview as a bitmap
web.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(web.getDrawingCache());
web.setDrawingCacheEnabled(false);
//Create the filename to use
String randomFilenamepart = String.valueOf(new SecureRandom().nextInt(1000000));
String filename = Environment.getExternalStorageDirectory().toString() + "/Enlighten_Mobile_" + randomFilenamepart + ".jpg";
File imageFile = new File(filename);
//Stream the file out to external storage as a JPEG
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.flush();
fout.close();
Toast.makeText(WebViewClientDemoActivity.this, "Screen Capture Saved!\n\nImage Saved at location : /sdcard\n\nSaved As: Enlighten_Mobile_xxxxx.jpg", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(WebViewClientDemoActivity.this, "Problem with Capturing Image or Location to Store Image", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
} finally {
web.setLayoutParams(browserParams);
}
return true;

Categories