Save downloaded file using the External Storage (private) - android

this is my code to download a file and save it in the internal storage:
public class getResults extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params){
String fileName = "results"+month+year+".pdf";
URLConnection conn;
try {
URL url = new URL(params[0]);
conn = url.openConnection();
int contentLength = conn.getContentLength();
DataInputStream in = new DataInputStream(conn.getInputStream());
byte[] buffer = new byte[contentLength];
in.readFully(buffer);
in.close();
if (buffer.length > 0) {
DataOutputStream out;
FileOutputStream fos = openFileOutput(fileName,Context.MODE_PRIVATE);
out = new DataOutputStream(fos);
out.write(buffer);
out.flush();
out.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "true";
}
protected void onPostExecute(String result){
}
}
but how I have to change the code, so that I save the file on External Storage and app-private?

Use FileOutputStream fos = new FileOutputStream(getExternalFilesDir() + "/" + fileName); But this is not private memory.

Related

Download a file with an AsyncTask

I tried using many codes I've found for downloading files with an AsyncTask with no success yet.
I get an error on the logcat: E/Error:: No such file or directory.
Despite looking for solutions for this error, couldn't find What's missing or wrong.
This is the doInBackground method in which I assume something is missing/wrong:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new DownloadJSON().execute("http://api.androidhive.info/json/movies.json");
}
protected String doInBackground(String...fileUrl) {
int count;
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(fileUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File fileName = new File(root+"/movies.json");
boolean existsOrNot = fileName.createNewFile(); // if file already exists will do nothing
// Output stream to write file
OutputStream output = new FileOutputStream(fileName,false);
byte data[] = new byte[1024];
System.out.println("Downloading");
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Thanks.
Didn't want to bombard with redundant code. If some other code is needed, I'd love to provide it.
UPDATED ANSWER
this is working for me, write file in local storage and read it again on method PostExecute
class DownloadJSON extends AsyncTask<String, Void, Void>{
String fileName;
String responseTxt;
String inputLine;
String folder;
#Override
protected Void doInBackground(String... strings) {
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//Set methods and timeouts
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder response = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
response.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
responseTxt = response.toString();
Log.d(TAG, "doInBackground: responseText " + responseTxt);
// PREPARE FOR WRITE FILE TO DEVICE DIRECTORY
FileOutputStream fos = null;
fileName = "fileName.json";
folder = fileFolderDirectory();
try {
fos = new FileOutputStream(new File(folder + fileName));
//fos = openFileOutput(folder + fileName, MODE_PRIVATE);
fos.write(responseTxt.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
fos.close();
}
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// -- THIS METHOD IS USED TO ENSURE YOUR FILE AVAILABLE INSIDE LOCAL DIRECTORY -- //
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(folder +fileName));
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
Toast.makeText(TestActivity.this, "result " + sb.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ops, almost forget this method
public static String fileFolderDirectory() {
String folder = Environment.getExternalStorageDirectory() + File.separator + "write_your_app_name" + File.separator;
File directory = new File(folder);
if(!directory.exists()){
directory.mkdirs();
}
return folder;
}
Your root is wrong
String root = "data/data/package.appname";
make sure your root contains right package name or file path.
package name which should be your application id

Getting Response Code 404 when Trying to write to online text file

I am trying to save data into a text file that does not yet exist online, but my urlConnection.getResponseCode() is returning a 404. I can read from files with similar urls, so I'm pretty certain the url is correct, but I've never written to an online file before.
private class SaveFile extends AsyncTask<String, Void, String> {
private String scheme = "http";
private String authority = "172.16.0.45";
private String path1 = "PrivateFile";
private String path2 = "SavedInstances";
protected void onPreExecute() {
}
protected String doInBackground(String...params) {
String result = null;
String filename = params[0] + ".txt";
String location = params[1];
OutputStream outStream = null;
HttpURLConnection urlConnection = null;
try {
// Save online as opposed to internal storage
if (location.equals("on")) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(scheme);
builder.authority(authority);
builder.appendPath(path1);
builder.appendPath(path2);
builder.appendPath(filename);
String _url = builder.build().toString();
URL url = new URL(_url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
if (urlConnection.getResponseCode() != 200) // Runs as true
throw new IOException(Integer.toString(urlConnection.getResponseCode()));
else {
outStream = urlConnection.getOutputStream();
}
} else if (location.equals("in")) {// Saving to internal
File file = new File(getFilesDir(), filename);
outStream = new FileOutputStream(file);
}
// Writing the file
PrintWriter writer = new PrintWriter(outStream);
writer.println(utils.size());
writer.println(trans.size());
writer.println(cables.size());
for (int i = 0; i < utils.size(); i++)
writer.println(utils.get(i).getValues());
for (int i = 0; i < trans.size(); i++)
writer.println(trans.get(i).getValues());
for (int i = 0; i < cables.size(); i++)
writer.println(cables.get(i).getValues());
writer.close();
outStream.close();
if (urlConnection != null)
urlConnection.disconnect();
result = "Save Successful";
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
result = e.getMessage();// 404
System.out.println(e.getMessage());
}
return result;
}
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
}
}
When I send the exception with getResponseMessage() instead, the message is "not found". What am I missing to get this connection working?

Download file within the app by clicking on the weblink.

I am developing app like playstore in which user can download any app. i have many apps in my application that i got from my website through wp api v2. when we click on any of the available application detail opened and it have a download link. when we click on the link it goes to the browser but what i want is when we click on any of the apps downloading link downloading should start within my app with progress bar. i didn't found any appropriate solution yet on stack or anywhere.
Here is the screenshot attached for better understanding. arrow is pointing to the downloading link.
Try this code, you can put this on click of the link(textview)
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
you can use intent service to download the app.
Here is the code :
public class DownloadService extends IntentService {
File cacheDir;
public DownloadService() {
super("DownloadService");
}
#Override
public void onCreate() {
super.onCreate();
String tmpLocation =
Environment.getExternalStorageDirectory().getPath();
cacheDir = new File(tmpLocation);
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
}
#Override
protected void onHandleIntent(Intent intent) {
String remoteUrl = intent.getExtras().getString("url");
String location;
String filename =
remoteUrl.substring(
remoteUrl.lastIndexOf(File.separator) + 1);
File tmp = new File(cacheDir.getPath()
+ File.separator + filename);
if (tmp.exists()) {
location = tmp.getAbsolutePath();
stopSelf();
return;
}
try {
URL url = new URL(remoteUrl);
HttpURLConnection httpCon =
(HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = is.read(buf))) {
out.write(buf, 0, n);
}
out.close();
is.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(tmp);
fos.write(response);
fos.flush();
fos.close();
is.close();
location = tmp.getAbsolutePath();
} catch (Exception e) {
Log.e("Service", "Failed!", e);
}
}
}
Run this service with url passed in the intent

How to write XML file on Android, getting from remote server

I need sometimes read XML file from remote server, and replace data in XML on my Android device.
I read data through XmlPullParser:
XmlPullParser users;
try {
URL xmlUrl = new URL("http://xx.xx.xx.xx/1.xml");
users = XmlPullParserFactory.newInstance().newPullParser();
users.setInput(xmlUrl.openStream(), null);
}
How can I replace it on Android?
Simply use this code, it's overwrites the file with the new file you download from the internet.
public static boolean downloadFile(String fileToDownload, File newPath,
String newFileName) {
try {
URL url = new URL(fileToDownload);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
if (!newPath.isDirectory()) {
CreateLog.createFolder(newPath.toString());
}
File file = new File(newPath.toString() + "/" + newFileName);
if (!file.isFile()) {
CreateLog.writeLogToFile(newPath.toString() + newFileName,
"%TEMP%");
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
return true;
} catch (MalformedURLException e) {
CreateLog.addToLog(e.toString());
return false;
} catch (IOException e) {
CreateLog.addToLog(e.toString());
return false;
}
}
public static void createFolder(String filePath) {
File createFolder = new File(filePath);
createFolder.mkdirs();
}
A cleaner method is to use a Asynctask, the code runs in a new thread. But it's a bit harder to code.
private class GetProblems extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
for (String myUrl : params) {
try {
URL url = new URL(myUrl);
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("Accept", "application/xml");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
String str = new String(baf.toByteArray(), "UTF8");
return str;
} catch (MalformedURLException e) {
CreateLog.addToLog("[GetProblems] " + e.toString());
} catch (IOException e) {
CreateLog.addToLog("[GetProblems] " + e.toString());
}
}
return "error";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// updateProgressBar(values[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
...write result to a file
}
}
Run the AsyncTask code:
new GetProblems().execute("http://myurl.com/xmlfile.xml");

How to download an MP3 file

I want to download an mp3 file using an AsyncTask or a thread.
How can I do this?
You can do something like this...
When you decide to start downloading:
new Thread(new Runnable()
{
#Override
public void run()
{
File out;
Downloader DDL;
DDL=new Downloader();
out=new File(Environment.getExternalStorageDirectory() + "/DestFileName.txt");
DDL.DownloadFile("SourceURL",out);
}
}).start();
Where the downloader class is
public class Downloader {
public void Downloader()
{
// TODO Auto-generated method stub
}
public boolean DownloadFile(String url, File outputFile)
{
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
}
catch(FileNotFoundException e)
{
return false;
}
catch (IOException e)
{
return false;
}
return true;
}
}
Refer to this thread:
android: file download in background
Use This Function In for Downloading Files On SDCARD
public void downloadNauhe(String url) {
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url1 = new URL("http://downloads.hussainiat.com/nauhey/arsalan_haider/vol_2011_-_12/01_tum_jawab_e_zulm_dogay_-_arsalan_haider_2011_-_2012.mp3");
URLConnection conexion = url1.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url1.openStream());
OutputStream output = new FileOutputStream("/sdcard/01_manum_abbas_as_-_mesum_abbas_2012.mp3");
byte data[] = new byte[1024];
long total = 0;
System.out.println("downloading.............");
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total/(float)lenghtOfFile)*100));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mprBar.setProgress(values[0]);
}
}
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute(url);
}
Don'forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Categories

Resources