Internal storage not storing file on my device - android

Hi friends have lot of confusion.
First thing is it's not storing in on my device instead of it stores on my emulator under this path data/data/com.customfonts/files/Robotoo.ttf. Then when I try to get file throwing Runtime Exception file not found because it's searching under data/user/0/com.customfonts/Robotoo.ttf instead of searching data.data/com.customfonts/files/Robotoo.ttf.
getDirectory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
new DownloadingTask().execute();
Log.i("FilePAthFirst",""+getFilesDir());
}
});
btnGETDATA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String filename="Robotoo.ttf";
getTypeface(filename);
}
});
private Typeface getTypeface(String filename)
{
Typeface font;
try
{
font = Typeface.createFromFile(getFilesDir() +"/"+filename);
Log.i("FOnt found",""+font);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return font;
}
private class DownloadingTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = new FileOutputStream(getApplicationContext().getFilesDir()+ "Robotoo.ttf");
Log.i("Download","complete");
Log.i("FOS",""+fos.toString());
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 (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
return null;
}
}

Harmonize the code to get the file path for saving the file and loading the file.
To load the tff also use getApplicationContext().getFilesDir()+filename

I used your same code, which is in answer it working fine, May be you can check you have permission for the internet in Manifest <uses-permission android:name="android.permission.INTERNET"></uses-permission>, if you already have this, You can wait till onPostExecute of your AsyncTask and check you are getting any error.
Internal storage
And For internal storage, It will not be constant as data.data/com.customfonts/files/ from Android 6.0, It will be dynamic, We should not hard code the path(You are doing that is correct)
Refer this Offical Doc
Edited: Forgot to Add earlier that to writing a file in internal storage as per doc we should use openFileOutput so I am using that.
private class DownloadingTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("[your url here]");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
Log.d("sdsdfds", "doInBackground: " + getApplicationContext().getFilesDir());
FileOutputStream fos = getApplicationContext().openFileOutput("Robotoo4.ttf", MODE_PRIVATE);
Log.i("Download","complete");
Log.i("FOS",""+fos.toString());
InputStream is = c.getInputStream();
byte[] buffer = new byte[4 * 1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
File file = new File(getFilesDir() + "/" + "Robotoo4.ttf");
Log.d("", "onPostExecute: " + file.exists() + " " + file.getAbsolutePath() + " Length " + file.length() );
}
}

Related

How to download sqlite database file from the server in Android?

protected void doDownload(final String urlLink, final String fileName) {
Thread dx = new Thread() {
public void run() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Content2/");
if(dir.exists()==false) {
dir.mkdirs();
}
//Save the path as a string value
try
{
URL url = new URL(urlLink);
Log.i("FILE_NAME", "File name is "+imageFile);
Log.i("FILE_URLLINK", "File URL is "+url);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir+"/"+imageFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
Log.i("ERROR ON DOWNLOADING FILES", "ERROR IS" +e);
}
}
};
dx.start();
}
through this, I cannot download the file from the server.
How to solve this problem?
First of all you should use Async-Task.
Here is how you can do this
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}

Android: Download from URL

i follow more explain in this site for download mp3 or picture from URL , I follow more method and try to write my method but when i run application it stop.
I make method to query download when click
also put permission for INTERNET & WRITE_EXTERNAL_STORAGE
put the problem is still
this method is download
public static void downloadMain(){
File fileToSave = null;
String scrPath ="http://***";
BufferedInputStream bis;
BufferedOutputStream bos;
fileToSave = new File(Environment.getExternalStorageDirectory().getPath() +"/"+ "A"+"/");
if (!fileToSave.exists())
fileToSave.mkdirs();
fileToSave = new File(Environment.getExternalStorageDirectory().getPath() +"/"+ "A" +"/" + "h"+"/");
if (!fileToSave.exists())
fileToSave.mkdirs();
File file = new File (fileToSave,"***.mp3");
try{
URL url = new URL(scrPath+"***.mp3");
URLConnection ucon = url.openConnection();
ucon.connect();
bis=new BufferedInputStream(ucon.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(file));
bis=new BufferedInputStream(url.openStream());
byte[] data = new byte[1024];
int a =0;
while(true){
int k = bis.read(data);
if(k==-1){
bis.close();
bos.flush();
bos.close();
break;
}
bos.write(data, 0, k);
a+=k;
}
}catch(IOException e){}
}
I have three main perplexity about your program:
Do you run the following code in an asynctask? (this must run asincronusly otherwise it will block)
Why it loop infinitly?
You couldn't open an url or a file named with a '*' inside of it
Edit:
You must run the download method asincronusly otherwise it wouldn't work, interaction with filesystem and network couldn't be done in the main thread
Edit2:
AsyncTask should be something like this
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");//put here your path and your mkdirs
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
}
And you shoould call it like this
DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
You could also have a look at this answer

Download image from url and show it into real device gallery android?

Using this code to download image from url in internal stroage. It working properly and showing image in emulator but When debugging on real device it gives empty.. Help me...
File fileWithinMyDir = getApplicationContext().getFilesDir();
downloadImage(url1, fileWithinMyDir.getAbsolutePath()+MODE_WORLD_READABLE + "/" +"image1.jpg");
public boolean downloadImage(String URL,String fileName){
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(URL);
File file = new File(fileName);
URLConnection ucon = url.openConnection();
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);
}
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return true;
}
If your device is connected with USB cable run your App & remove device from USB cable and check it. I hop it will work.
And it will not work use the fallowing code
String serverURL1 = "enter your image url";
new imageFile().execute(serverURL1);
public class imageFile extends AsyncTask<String,Void,Void>
{
private Context context;
public void setContext(Context contextf)
{
context = contextf;
}
protected Void doInBackground(String... arg0)
{
try
{
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"SD card path");
FileOutputStream f = new FileOutputStream(myFile);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 )
{
f.write(buffer,0, len1);
}
f.close();
}
catch (Exception e)
{
Log.e("imageFile", "Update error! " + e.getMessage());
}
return null;
}}
//Animation class focus on windows button change
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
{
frameAnimation.start();
}
else
{
frameAnimation.stop();
}
}

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