How to save file from website to sdcard
You can use this method to download a file from the internet to your SD card:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/xmls");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer 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");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
You need to add the following permissions to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<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.READ_PHONE_STATE"></uses-permission>
How to download a file from a server and save it in specific folder in SD card in Android?
Your download URL is not a link to any file. It's a directory. Make sure its a file and exists. Also check your logcat window for error logs. One more suggestion, its always better to do a printStackTrace() in catch blocks instead of Logs. Its gives a more detailed view of the error.
Change this line:
URL url = new URL("http://myexample.com/android/");
to:
URL url = new URL("http://myexample.com/android/yourfilename.txt"); //some file url
Next, in catch block, add this line:
e.printStackTrace();
Also in the directory path, it should be something like this:
File dir = new File(root.getAbsolutePath() + "/mnt/sdcard/myclock/databases");
instead of
File dir = new File(root.getAbsolutePath() + "/myclock/databases");
Next, make sure you have acquired permission for writing to external storage in Android manifest.
Downloading file from server
First of all, this line:
add(new RichTextField("Deleted and created", Field.NON_FOCUSABLE));
Makes me think you are doing this directly on the event thread, which is bad practice. If the connection times out or takes a long time, then you are freezing the GUI for that time. You would usually spawn a worker thread to do long tasks like this.
That said, your code could work, but it is not really robust. A lot of things can go bad. For instance, this line:
HttpConnection connection = (HttpConnection) Connector.open("http://127.0.0.1/xml/home.xml");
The returned connection can be null so you must check for it. You'd better use ConnectionFactory
instead as it appends the correct suffix for each kind of connection (WiFi, BES, TCP,...). In simulator, I'm not sure you can use a localhost URL since it is local to your workstation, but the simulated BB device has to go through an MDS simulator.
With FileConnection
you must also check it is not null, and also that fconn.canRead
returns true. Take into account that not every device has an sdcard slot (most recent ones do). You could check if the card is available as it is explained in this article, or let the catch
handle the exception. If you are testing on simulator, you'll have to "mount" a virtual sdcard.
Also this call:
ds.read(data);
will block until the server actually sends you something. This is probably what is happening.
You must check you have the correct permissions. For the file connection, you'll need:
ApplicationPermissions.PERMISSION_FILE_API
And for the network connection, depending on where are you connecting to, you'll need one of:
ApplicationPermissions.PERMISSION_INTERNET
ApplicationPermissions.PERMISSION_SERVER_NETWORK
A final tip: add a finally clause to the try-catch, and close all the streams and connections in the finally (in case they are not null).
How to download XML and convert to string
You can use HttpURLConnection, Sample code:
String xmlString;
HttpURLConnection urlConnection = null;
URL url = new URL("http://example.com");
String userName = "test";
String password = "password";
try {
urlConnection = (HttpURLConnection)url.openConnection();
// set authentication
String userCredentials = userName+":"+password;
String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));
urlConnection.setRequestProperty("Authorization", basicAuth.trim());
// set request method
urlConnection.setRequestMethod("GET");
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuilder xmlResponse = new StringBuilder();
BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
xmlResponse.append(strLine);
}
xmlString = xmlResponse.toString();
input.close();
}
}
catch (Exception e) {// do something
}
finally {// close connection
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Set xml file from sd card as layout in android
No,Its not possible.
To set xml file as layout in your activity you have that file in res/layout
directory and also make sure its id entry in R.java
files.
Without keeping it in res/layout
you can't apply it as a layout to your activity.
EDIT:
Basically when you put any xml layout
file in res/layout
then its id entry created in public static final class layout
in R.java
files, And from there when you set that file as a contentView()
of your activity or inflate
it, the android nutshell make a view from that raw layout xml file and apply it to your activity.
Related Topics
Cordova Cannot Add Android Failed with Exit Code Enoent
How to Add Firebase Database Rules Without Authentication
Using Android Studio with Vuforia
Sqlitedatabase Close() Function Causing Nullpointerexception When Multiple Threads
Android - Expandable Textview with Animation
Android Browser Textarea Scrolls All Over The Place, Is Unusable
How to Listen for a Custom Uri
How to Pin a Certificate with Square Okhttp
How to Create a Floating Action Button (Fab) in Android, Using Appcompat V21
Add Support Library to Android Studio Project
Get Color Value Programmatically When It's a Reference (Theme)
Android Layout with Square Buttons
Firebase Servervalue.Timestamp in Java Data Models Objects
Captured Photo Orientation Is Changing in Android
Android - Multiple Custom Versions of The Same App