android file download from Internet gives an exception - android

I am trying to download file form Internet. I have given all permission.But my apps gives some Exception. Here is my source code ..........
private void write()
{
try {
URL url = new URL("http://wordpress.org/plugins/about/readme.txt");
// URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
// c.setReadTimeout(10000); // millis
// c.setConnectTimeout(15000); // millis
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
// }
} catch (IOException e) {
MessageBox(e.getMessage());
}
}
//permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
c.connect(); // this connect() function gives an exception. I can't identify the problem.
Please somebody help me....

add this in main function
new AsyncTaskRunner().execute("");
add below after main function
private class AsyncTaskRunner extends AsyncTask<String, String, String>
{
#Override
protected void onPostExecute(String result) {
try
{
MessageBox(result);
/*
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c;
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
*/
}
catch(Exception ex)
{
MessageBox(ex.getMessage()+"error ");
}
}
#Override
protected String doInBackground(String... params) {
try
{
URL url = new URL("http://wordpress.org/plugins/about/readme.txt");
// URL url = new
// URL("http://androidsaveitem.appspot.com/downloadjpg");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
// c.setReadTimeout(10000); // millis
// c.setConnectTimeout(15000); // millis
//c.setDoOutput(true);
c.connect();
InputStream is = c.getInputStream();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
//InputStream is = c;
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Log.v("esty", "Successfully");
return "Successfully";
}
catch(Exception ex)
{
Log.v("esty", ex.getMessage());
return "failed"+ex.getMessage();
}
}
i hope it solves your problem! :)

Related

How to download and automatic install apk from url in android

I'm trying to programmatically download an .apk file from a given URL and then install it, but I am getting a FileNotFoundException. What could be a possible reason for the issue?
try {
URL url = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "VersionUpdate.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
**//Getting error in this line**
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.flush();
fos.close();
is.close();
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file:///sdcard/download/VersionUpdate.apk"),"application/vnd.android.package-archive");
startActivity(intent);
}
You just replaced by InputStream is = c.getInputStream(); to given code.
InputStream is ;
int status = c.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
is = c.getErrorStream();
else
is = c.getInputStream();
Try the following code
File outputFile = new File(file, "VersionUpdate.apk");
if(!outputFile.exists())
{
outputFile.createNewFile();
}
What you are doing is deleting the file, when it already exist, then FileOutputStream will not get file where you want to download the apk .
If the file already exist, FileOutputStream will override the content with new update.
If you have queries, do ask!!

Android download even if does not exist

try {
URL url = new URL("http://URL/Dragonfly.db");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split("/");
String _file = path[path.length - 1];
int lengthOfFile = c.getContentLength();
if(lengthOfFile > 0){ // Copy file if Length > 0
String PATH = db.DB_PATH; ;//Environment.getExternalStorageDirectory()+
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "Dragonfly.db";
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}else{
TestAdapter mDbHelper = new TestAdapter(getBaseContext());
mDbHelper.createDatabase();
}
} catch (IOException e) {
e.printStackTrace();
}
I use this code to update database, downloading a new one. but if i dont have a file on server, it replace the database i have for a new empty one (0bytes).
How can i download the file just if it exist on server?
Try to do a status response check:
int responseCode = c.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
{
// update database replacing the old one with the new one
} else {
// continue to use old database
}

save image in android

This is a code for saving images in SD card if and if not exist.
but i don't know how to read it.
Can anybody help me please.
This is the download file method:
public static String DownLoadFile(String netUrl, String name ) {
try {
//need uses permission WRITE_EXTERNAL_STORAGE
ByteArrayBuffer baf = null;
long startTime = 0;
//get to directory (a File object) from SD Card
File savePath=new File(Environment.getExternalStorageDirectory().getPath()+"/postImages/");
String ext="jpg";
URL url = new URL(netUrl);
//create your specific file for image storage:
File file = new File(savePath, name + "." + ext);
boolean success = true;
if (!savePath.exists()) {
success = savePath.mkdir();
}
if (success) {
if(file.createNewFile())
{
file.createNewFile();
//write the Bitmap
Log.i("file existence", "file does not exist!!!!!!!!!!!");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
startTime = System.currentTimeMillis();
baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
return file.getAbsolutePath();
}//end of create file if not exists
}//end of if success
} catch (Exception exx) {
if (exx.getMessage() != null) {
} else {
}
}
return null;
}
Try this,
Uri uri = Uri.parse("file:///sdcard/temporary_file.jpg");
img.setImageURI(uri);
if u have image uri so get path from uri like
String Path = fileUri.getPath();
// read file from sdcard
public static byte[] readFromStream(String path) throws Exception { File
file = new File(path); InputStream inputStream = new
FileInputStream(file); ByteArrayOutputStream baos = new
ByteArrayOutputStream(); DataOutputStream dos = new
DataOutputStream(baos); byte[] data = new byte[(int) file.length()]; int
count = inputStream.read(data); while (count != -1) { dos.write(data, 0,
count); count = inputStream.read(data); } return baos.toByteArray(); }

Save image from url to sdcard

I am saving image from url to sdcard. But image size is 0 in sdcard. Image is created in sdcard but now retrieve data from url and save. so it is giving me 0 size.
try
{
URL url = new URL("http://api.androidhive.info/images/sample.jpg");
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,username+".png"));
try {
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
} catch(Exception e)
{
System.out.println("error in sd card "+e.toString());
}
Try this code.It works...
You should have permission of internet and write external storage.
try
{
URL url = new URL("Enter the URL to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
String filename="downloadedFile.png";
Log.i("Local filename:",""+filename);
File file = new File(SDCardRoot,filename);
if(file.createNewFile())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize) filepath=file.getPath();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
filepath=null;
e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;
Try this, this may late but it will help someone.
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap>
{
#Override
protected Bitmap doInBackground(String... arg0)
{
downloadImagesToSdCard("","");
return null;
}
private void downloadImagesToSdCard(String downloadUrl,String imageName)
{
try
{
URL url = new URL(img_URL);
/* making a directory in sdcard */
String sdCard=Environment.getExternalStorageDirectory().toString();
File myDir = new File(sdCard,"test.jpg");
/* if specified not exist create new */
if(!myDir.exists())
{
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection)ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
inputStream = httpConn.getInputStream();
}
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) >0 )
{
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
}
catch(IOException io)
{
io.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Declare your network operations in AsyncTask as it will load it as a background task. Don't load network operation on main thread. After this either in button click or in content view call this class like
new ImageDownloadAndSave().execute("");
And don't forget to add the nework permission as:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Hope this will help :-)

My download video code does not works in android 4.0

I have done video file download code for the application and its working perfact for the version upto 2.3.3 but it does not working properly in the android 4.0 and it is giving the error like java.io.FileNotFoundException
Can anyone help me to solve this problem?
Thanks in advance
public void video_download(String urlstring, String Name) {
URL url;
try {
url = new URL(urlstring);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/application/";
Log.v("PATH", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName;
fileName = Name + ".mp4";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories

Resources