Capture current Webview and save to SD card - java

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;

Related

File not found error for no apparent reason?

My application should save a piechart as a png on the external storage. However this error appears:
java.io.FileNotFoundException: /storage/emulated/0/SAVE IMAGE EXAMPLE/myimage.png (No such file or directory)
I followed the instructions to add this kind of functionality very closely (From this tutorial), but yet the error appears. The app has the permission to write to external storage, I added the permission in my android_manifest.xml.
Can you guys spot the error? Because i can not.
If you also can't find the error, can you recommend any other way to do this?
Im using MPAndroidChart, but i don't really think it has to do with this, because i could try to save any other object and the error remains.
The code is
final PieChart piechart = (PieChart) findViewById(R.id.piechart);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
Toast.makeText(Main.this, "Chart Saved", Toast.LENGTH_SHORT).show();
piechart.setCenterText("Test");
Bitmap bitmap;
OutputStream output;
bitmap = BitmapFactory.decodeResource(getResources(),R.id.piechart);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()+"/SAVE IMAGE EXAMPLE");
dir.mkdirs();
File file = new File(dir, "myimage.png");
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
FULL ERROR
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/SAVE IMAGE EXAMPLE/myimage.png (No such file or directory)
W/System.err: at java.io.FileOutputStream.open(Native Method)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
W/System.err: at com.pies.quickpie.Main$1$3.onClick(Main.java:175)
W/System.err: at android.view.View.performClick(View.java:5637)
W/System.err: at android.view.View$PerformClick.run(View.java:22429)
W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
You need to implement Runtime Permission model to get Storage Permission from user from marshmallow and above.
See the example here for storage permission

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)

file writing is not performing in android

I need to write the registration credentials into a file during registration and during login will check that file for credentials. but on registration button click nothing is performing.
Manifest file contains this permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
the registration.java part:
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String user=username.getText().toString();
String pwd=password.getText().toString();
String cpwd=confirm.getText().toString();
if(user.equals("")||pwd.equals("")||cpwd.equals("")){
Toast.makeText(getApplicationContext(), "Fields cannot be Blank", Toast.LENGTH_SHORT).show();
}
else if(pwd.equals(cpwd)){
String data=user+","+pwd+":";
try {
FileOutputStream fout = new FileOutputStream(Environment.getExternalStorageDirectory()+"/myapp/userregister.txt/", true);
fout.write(data.getBytes());
Toast.makeText(getApplicationContext(), "Succesfully Register", Toast.LENGTH_SHORT).show();
Intent a=new Intent(getApplicationContext(),LoginActivity.class);
startActivity(a);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(!pwd.equals(cpwd)){
Toast.makeText(getApplicationContext(), "Password not match.. Try again!", Toast.LENGTH_SHORT).show();
}
}
});
In LoginActivity.java
if(username.equals("") || password.equals("")){
Toast.makeText(getApplicationContext(), "Fields Cannot be Blank", Toast.LENGTH_SHORT).show();
}else{
String reply=FileManipulator.authenticateUser(username, password);
if(reply.equals("user")){
Intent gotoNextActivity=new Intent(getApplicationContext(),HomeActivity.class);
startActivity(gotoNextActivity);
}else{
Toast.makeText(getApplicationContext(), "Invalid User.... Try again",Toast.LENGTH_SHORT).show();
}
}
FileManipulator class authenticateUser function:
public static String authenticateUser(String user, String pass){
String data="";
String data1 = "";
try{
FileInputStream fin=new FileInputStream(Path.userregister);
byte[] b=new byte[fin.available()];
fin.read(b);
data=new String(b);
String st=user+","+pass+":";
if(data.contains(st)){
data1="user";
}
}catch(Exception e){
e.printStackTrace();
}
return data1;
}
The log cat shows
09-02 05:48:06.292: D/dalvikvm(1964): GC_CONCURRENT freed 240K, 12% free 2838K/3200K, paused 5ms+32ms, total 177ms
09-02 05:48:06.802: I/Choreographer(1964): Skipped 36 frames! The application may be doing too much work on its main thread.
09-02 05:48:10.362: I/Choreographer(1964): Skipped 32 frames! The application may be doing too much work on its main thread.
09-02 05:48:20.872: W/System.err(1964): java.io.FileNotFoundException: /mnt/sdcard/myapp/userregister.txt: open failed: EACCES (Permission denied)
09-02 05:48:20.872: W/System.err(1964): at libcore.io.IoBridge.open(IoBridge.java:416)
09-02 05:48:20.882: W/System.err(1964): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
09-02 05:48:20.882: W/System.err(1964): at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
09-02 05:48:20.882: W/System.err(1964): at com.example.text.RegActivity$1.onClick(RegActivity.java:49)
09-02 05:48:20.892: W/System.err(1964): at android.view.View.performClick(View.java:4204)
09-02 05:48:20.892: W/System.err(1964): at android.view.View$PerformClick.run(View.java:17355)
09-02 05:48:20.902: W/System.err(1964): at android.os.Handler.handleCallback(Handler.java:725)
09-02 05:48:20.912: W/System.err(1964): at android.os.Handler.dispatchMessage(Handler.java:92)
09-02 05:48:20.912: W/System.err(1964): at android.os.Looper.loop(Looper.java:137)
09-02 05:48:20.912: W/System.err(1964): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-02 05:48:20.922: W/System.err(1964): at java.lang.reflect.Method.invokeNative(Native Method)
09-02 05:48:20.922: W/System.err(1964): at java.lang.reflect.Method.invoke(Method.java:511)
09-02 05:48:20.922: W/System.err(1964): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-02 05:48:20.922: W/System.err(1964): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-02 05:48:20.922: W/System.err(1964): at dalvik.system.NativeStart.main(Native Method)
09-02 05:48:20.932: W/System.err(1964): Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
09-02 05:48:20.942: W/System.err(1964): at libcore.io.Posix.open(Native Method)
09-02 05:48:20.942: W/System.err(1964): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
09-02 05:48:20.952: W/System.err(1964): at libcore.io.IoBridge.open(IoBridge.java:400)
09-02 05:48:20.952: W/System.err(1964): ... 14 more
I'm a newbie to android and java..please help me to find the error.
1) Add android.permission.WRITE_EXTERNAL_STORAGE in AndroidManifest.xml file.
2) Always check for the availability of external storage before writing/reading by :
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
} else {
// Can't read or write
}
3) Create a directory, then make your file in it.
File dir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/myapp");
dir.mkdirs();
File file = new File(dir, "userregister.txt");
NOTE :
If you are using Android 4.4 KitKat, Apps are not allowed to write to secondary external storage devices, except in their package-specific directories
The reason from http://source.android.com/devices/tech/storage/index.html
The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.

Button not creating a file and showing email provider option menu when pressed

I've created a button that creates a file then sends it as an attachment to an email,
it grabs the text from one of the textviews, saves it to a .txt and sends it. A small email service option selector should show up too. The code is meant to create a file path if one is not already there. This code is above the onCreate method and in a regular activity.
i keep getting this in the logcat (specific message marked by (-->)):
-->08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ java.io.IOException: open failed: ENOENT (No such file or directory)<---
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.io.File.createNewFile(File.java:946)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.example.adrian.trucktracker.Locator.clickedUpdate(Locator.java:76)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View$1.onClick(View.java:3860)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View.performClick(View.java:4480)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View$PerformClick.run(View.java:18686)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Looper.loop(Looper.java:157)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5872)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at libcore.io.Posix.open(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.io.File.createNewFile(File.java:939)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ ... 15 more
My code:
public void clickedUpdate(View view)
{
TextView dLong = (TextView) findViewById (R.id.textLong);
TextView dLat = (TextView) findViewById (R.id.textLat);
String dataLat = dLat.getText().toString();
String dataLong = dLong.getText().toString();
boolean UpdateResume;
if(!(dataLat.equals("") && !(dataLong.equals(""))))
{
UpdateResume = true;
}
else
{
UpdateResume = false;
}
TelephonyManager telephonemanager =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String PhoneNumber = telephonemanager.getLine1Number();
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
File Data = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"data" + File.separator+"Locationer.txt");
String datapath = Data + ""
if(!Data.exists())
{
try {
line 76 ----> Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
while (UpdateResume = true)
{
if (Data.exists())
{
try
{
FileWriter fileWriter = new FileWriter(Data);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write(PhoneNumber + "," + dataLat + "," + dataLong);
bfWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
break;
}
}
Intent emailintent = new Intent(Intent.ACTION_SEND);
emailintent.setType("text/plain");
emailintent.putExtra(Intent.EXTRA_EMAIL, new String[]{"apraiswater#legion-logistics.com"});
emailintent.putExtra(Intent.EXTRA_SUBJECT, "Data");
emailintent.putExtra(Intent.EXTRA_TEXT, "Hello World!");
File root = Environment.getExternalStorageDirectory();
String DataAttachment = "Android/data/Locationer.txt";
File filer = new File(root, DataAttachment);
if (!filer.exists() || filer.canRead())
{
return;
}
Uri uri = Uri.fromFile(filer);
emailintent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailintent, "Choose an Email provider"));
}
A few details seem relevant:
First you check the existence of the dir:
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
according to the documentation, your try{}catch(Exception e){} aren't needed. You just would need to check whether the directory actually exists. There's the additional problem that you seem to create a subdirectory of another subdirectory. So, you might want to exchange it to mkdirs() instead.
Afterwards, you try to create the File if it doesn't exist
try {
line 76 ----> Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Take a look at the documentation for this method. You might note that it tells you
This method is not generally useful. For creating temporary files, use
createTempFile(String, String) instead. For reading/writing files, use
FileInputStream, FileOutputStream, or RandomAccessFile, all of which
can create files.
but maybe, if you've included the proper permissions, the changes I suggested above will help to make your code work.

Android downloading a file getting a FileNotFoundException

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);

Categories