Android: EACCES (Permission denied) , while I added the uses-permisson in manifest - android

I'm using a very simple code to download an Image from my localhost : here it is :
package com.pep.www.imagedownloader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
download();
}
});
thread.start();
}
});
}
public void download(){
int read = -1;
byte[] buffer = new byte[5*1024];
URL url = null;
HttpURLConnection ucon = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
File file = null;
try {
url = new URL("http://192.168.1.128/image.jpg");
ucon = (HttpURLConnection) url.openConnection();
inputStream = ucon.getInputStream();
file = new File("mnt/sdcard/image.jpg");
fileOutputStream = new FileOutputStream(file);
while((read=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,read);
Log.i("LOG","Downling : "+read);
}
Log.i("LOG","Downloaded");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
While I've added this permission in manifest :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I still get this error :
java.io.FileNotFoundException: mnt/sdcard/image.jpg: open failed: EACCES (Permission denied)
EDIT :
when I change my file path to this :
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/image.jpg ");
I still get this error :
java.io.FileNotFoundException: /storage/sdcard/Pictures/aylar.jpg : open failed: EACCES (Permission denied)
EDIT :
Instead of being so childish and giving downVotes , solve the problem !
Stackoverflow has become a place to play childish games :(

Firstly let me tell you one thing If you are using an emulator then the code will not work you need a real device.As we know we give permission to store image in external storage So You can use this method to save your image and then get back.
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,"myImage.png"));
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}

try to use this
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
{
file =new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/image.jpg ");
if(!file.exists())
file.createNewFile();
}

replace
file = new File("mnt/sdcard/image.jpg");
with
file = new File("file:///sdcard/image.jpg");

its simple code any file like image,video,audio etc we can download it.
Button start;
//String HttpMyUrl="http://am.cdnmob.org/_/img/loader-small.gif";
String HttpMyUrl="http://ringtones.mob.org/ringtone/RIusrm-7xATkRQlLw1o89w/1424909358/fa1b23bb5e35c8aed96b1a5aba43df3d/stefano_gambarelli_feat_pochill-land_on_mars_v2.mp3";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start= (Button) findViewById(R.id.startBtn);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(HttpMyUrl));
request.setTitle("File Download");
request.setDescription("File is being Downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String fileName = URLUtil.guessFileName(HttpMyUrl,null, MimeTypeMap.getFileExtensionFromUrl(HttpMyUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
DownloadManager manager =(DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});

Related

Saving file to storage programmatically

I have tried with the following code: (Previously it was working fine, Now I am testing its not working may be due to android 10 or some other error).
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
public class AboutUs extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new DownloadFile().execute("https://4.img-dpreview.com/files/p/E~TS590x0~articles/3925134721/0266554465.jpeg");
}
private class DownloadFile extends AsyncTask<String,Integer, String> {
private PowerManager.WakeLock mWakeLock;
#Override
protected String doInBackground(String... strings) {
String fileUrl = strings[0];
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "MyFolder");
folder.mkdir();
File pdfFile = new File(folder, fileUrl);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
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);
// if we get here, length is known, now set indeterminate to false
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: "+result, Toast.LENGTH_LONG).show();
else {
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
activity.startActivity(activity.getIntent());
activity.finish();
}
}
}
public static class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have tried with the above code.
I have added WRITE_INTERNAL_STORAGE and also ask run time permission
There were major changes on how files can be accessed on Android 10
See https://developer.android.com/training/data-storage
You need to use MediaStore or Storage Access Framework (SAF), details https://developer.android.com/training/data-storage/shared for files outside of your App's private directories.
As you are storing photo then MediaStore would be the way to access pictures https://developer.android.com/training/data-storage/shared/media
Though as a quick fix is to temporarily opt out https://developer.android.com/training/data-storage/compatibility but this will only work until Android 11
Some better examples at https://proandroiddev.com/working-with-scoped-storage-8a7e7cafea3
Android 10 requered android:requestLegacyExternalStorage="true" in your AndroidManifest file
check this link
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.xxx.xxxx">
<application
android:requestLegacyExternalStorage="true">
</application>
</manifest>

PDF printing view issue

I have tried in two ways,
1) Am creating a WebView and loading my pdf document, and my application is almost done with its part of the printing process. But in that am facing printing issue.
Its not with full A4 sheet view.Can anyone please help,The following code i have used,
public void createWebPagePrint(WebView webView) {
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
printAdapter = webView.createPrintDocumentAdapter();
String jobName = getString(R.string.app_name) + " Document";
PrintAttributes.Builder builder = null;
builder = new PrintAttributes.Builder();
builder.setMediaSize(PrintAttributes.MediaSize.ISO_A4);
PrintJob printJob = null;
printJob = printManager.print(jobName, printAdapter, builder.build());
if (printJob.isCompleted()) {
Toast.makeText(getApplicationContext(), "Print Complete", Toast.LENGTH_LONG).show();
} else if (printJob.isFailed()) {
Toast.makeText(getApplicationContext(), "Print Failed", Toast.LENGTH_LONG).show();
}
builder.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setResolution(new PrintAttributes.Resolution("id", Context.PRINT_SERVICE, 1024, 720))
.setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).build();
}
}
Note:
https://developer.android.com/training/printing/html-docs.html
And some times while loading pdf its not displaying.
2) I have tried using with pdf view lib ,
compile 'com.github.barteksc:android-pdf-viewer:2.8.2'
But that time am getting better view compared to webview. The problem is only visible view is drawing on canvas.The print view is not clear.Its not readable.I have given the page count, So according to the page count its repeating the pages but print view is same as in first page.The following view am getting while printing.
This is my sample code,
code
If anyone know please help me.
The above procedure is very hard.Even am not getting solution for that.After that i come up with a solution and its working perfectly for me.
1) To view PDF file no need to load with webview or external pdf libraries.Just download the pdf file and view it with default pdf viewer.The below code i have used,
To download a file,
import android.app.Activity;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory, Activity activity){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class DownloadFile extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0];
String fileName = strings[1];
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "Test");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile,InventoryStockActivity.this);
return null;
}
}
public void download(String viewUrl) {
new DownloadFile().execute(viewUrl, "Test.pdf");
Log.d("Download complete", "----------");
}
To view a pdf file;
public void view() {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Test/" + "Test.pdf");
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(InventoryStockActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
In manifest,
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
And when its open default pdf viewer, there will be print menu.Just print from there.

image is not saving to android device in Sd card

package com.lociiapp;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.example.imageslideshow.R;
public class recciverfullimageActivty extends Activity {
String reccvierid;
Context context;
ImageView recciverimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent myintent = getIntent();
reccvierid = myintent.getStringExtra("reccvierid");
recciverimage = (ImageView) findViewById(R.id.recciverImage);
String myfinalpathare = reccvierid;
Toast.makeText(getApplicationContext(), reccvierid, 10000).show();
String imagepathe = "http://api.lociiapp.com/TransientStorage/"
+ myfinalpathare + ".jpg";
try {
saveImage(imagepathe);
Log.e("****************************", "Sucess");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void saveImage(String urlPath) throws Exception {
String fileName = "test.jpg";
File folder = new File("/sdcard/LociiImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder, fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection()
.getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with
// bytes from the data
// input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This is My code I am trying to save Image which is coming from server we have Image Url . when i Run this Code then Folder is creating in Sd card But image is not downloading on Save in Sd care please help and tell where i am doing wrong .
Your checklist should be as follows:
A. Make sure you have the right permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
B. Move networking and file IO logic to non-UI thread:
new AsyncTask<Params, Progress, Result>() {
#Override protected Result doInBackground() {
saveImage(imagepathe);
}
#Override protected void onPostExecute(String result) {
// update UI here
}
}.execute(params);
C. Do not read one byte at the time. It is probably not the source of your problem but it
does make your solution much slower than it can be:
Instead of:
for(;;) {
fileData[x] = dis.readByte();
}
Do this:
URL u = new URL(url);
URLConnection connection = u.openConnection();
byte[] buffer = new byte[connection.getContentLength()];
stream.readFully(buffer); // <------------- read all at once
stream.close();
D. And , finally, consider using Picasso for the job:
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
Nowadays you just no not need to write that much code to get were you're going..
Try this..
Call like below instead of saveImage(imagepathe);
myAsyncTask myWebFetch = new myAsyncTask();
myWebFetch.execute();
and myAsyncTask.class
class myAsyncTask extends AsyncTask<Void, Void, Void> {
public ProgressDialog dialog;
myAsyncTask()
{
dialog = new ProgressDialog(webview.this);
dialog.setMessage("Loading image...");
dialog.setCancelable(true);
dialog.setIndeterminate(true);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
protected Void doInBackground(Void... arg0) {
try {
InputStream stream = null;
URL url = new URL("http://api.lociiapp.com/TransientStorage/286.jpg");
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File myDir = new File(SDCardRoot + "/LociiImages");
myDir.mkdirs();
File file = new File(myDir,"test.jpg");
FileOutputStream fileOutput = new FileOutputStream(file);
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = stream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
EDIT
String imagePath = Environment.getExternalStorageDirectory().toString() + "/LociiImages/test.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageview.setImageBitmap(bitmap);

File not found error in android?

I am trying to download pdf file and save on android at some location .But I am getting this error why ?java.io.FileNotFoundException: http://www.pdf995.com/samples/pdf.pdf
I am checking my code on emulator.can you please tell me why this error coming because when I hit this url on browser http://www.pdf995.com/samples/pdf.pdf it give pdf to us .But here it is not giving to use,
code:
package com.example.downloadfile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
int totalSize = 0;
int downloadedSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.b1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//showProgress(dwnload_file_path);
new Thread(new Runnable() {
public void run() {
downloadFile();
}
}).start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
void downloadFile(){
try {
URL url = new URL("http://www.pdf995.com/samples/pdf.pdf");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the <span id="IL_AD12" class="IL_AD">downloaded</span> file
File file = new File(SDCardRoot,"aaa.pdf");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are <span id="IL_AD9" class="IL_AD">downloading</span>
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
float per = ((float)downloadedSize/totalSize) * 100;
//cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// pb.dismiss(); // if you want close it..
}
});
} catch (final MalformedURLException e) {
// showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
//showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
//showError("Error : Please <span id="IL_AD4" class="IL_AD">check your</span> internet connection " + e);
}
}
}
Calling openConnection() is enough to access the input stream later. Looks like the second call to connect() is what's causing the problem. Just strip that part from your code and it will work fine:
URL url = new URL("http://www.pdf995.com/samples/pdf.pdf");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
...
As an aside, if you want to show progress during the download, I'd suggest using an AsyncTask instead. It's tailor-made for uses like this.

problem to store data into sdcard

i have problem to store image into sd car, there are not display file in sdcard which i want.
this is code.
package com.sdcard;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class SdcardActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
URL url = new URL ("http://www.coolpctips.com/wp-content/uploads/2011/05/top-30-android- games.jpg");
InputStream input = url.openStream();
try {
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/top-30-android-games.jpg");
try {
int aReasonableSize = 10;
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, buffer.length);
}
} finally {
output.close();
}
} finally {
input.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}}
add this lines in your code:
catch (Exception e) {
e.printStackTrace();
}
and you will notice an exception that the url is malformed. Add more information about what you want to achieve so that I can write a better answer.
The exception in your comment might be related with some kind of a bug in Android:
http://code.google.com/p/android/issues/detail?id=2764. You can try with this solution: Android java.net.UnknownHostException: Host is unresolved (strategy question) or give IP address instead of DNS.
Here you have tested code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
URL url = new URL ("http://www.coolpctips.com/wp-content/uploads/2011/05/top-30-android-games.jpg");
InputStream input = url.openStream();
try {
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/top-30-android-games.jpg");
int aReasonableSize = 1000;
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;;
try {
while ((bytesRead = input.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
you should use Environment.getExternalStorageDirectory() instead of mnt/sdcard/
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/myImage.png");
Your problem is you are referencing your host computers local filesystem inside your android device. C:\ isn't a path that android knows how to interpret.
Host it on a local webserver then use something like http://192.168.0.100/your/url/image.png

Categories

Resources