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

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");

Related

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?

Store and retrieve image from URL in local database in an Android app

I am getting image path URL and now I want to get image from that URL and save in to local database but I am not able to convert it into bytes so that BLOB in database will accept it. I have tried a lot but all in vain. I used a code but ByteArrayBuffer not resolved type.
// code to convert image url into byte array
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
System.out.println("11111");
InputStream is = ucon.getInputStream();
System.out.println("12121");
BufferedInputStream bis = new BufferedInputStream(is);
System.out.println("22222");
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
System.out.println("23333");
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
photo = baf.toByteArray();
System.out.println("photo length" + photo);
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return accImage;
}
after that I have used tutorial "https://github.com/CoderzHeaven/StoreImageSqliteAndroid" to save into database
Replace your method by this
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
System.out.println("11111");
InputStream is = ucon.getInputStream();
System.out.println("12121");
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream accImage = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
accImage.write(buffer, 0, bytesRead);
}
return accImage.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
**You can try this method for download and save image into database**
public class MainActivity extends Activity {
protected SQLiteDatabase sqlitedatabase_obj;
DataBaseHelper databasehlpr_obj;
int accId;
byte[] accImage;
byte[] logoImage;
byte[] photo;#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AndroidContext.setContext(this);
sqlitedatabase_obj = DataBaseHelper.getInstance().getDb();
new ImageDownloader().execute("http://images.100bestbuy.com/images/small_137385013870957.jpg");
}
/* get logo image method */
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
System.out.println("test1");
InputStream is = ucon.getInputStream();
System.out.println("test2");
BufferedInputStream bis = new BufferedInputStream(is);
System.out.println("test3");
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
System.out.println("test4");
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
photo = baf.toByteArray();
System.out.println("photo length" + photo);
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return accImage;
}
public void insertUser() {
ContentValues userdetailValues = new ContentValues();
userdetailValues.put("account_image", photo);
sqlitedatabase_obj.insert(DataBaseHelper.IMG_table, null, userdetailValues);
}
/* AsyncTask method */
private class ImageDownloader extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected Void doInBackground(String... param) {
sqlitedatabase_obj.delete(DataBaseHelper.IMG_table, null, null);
logoImage = getLogoImage(param[0]);
insertUser();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "Wait", "Downloading Image");
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
}

download file from url and read later locally

I want to download a file from url to read this file later locally. I have this code to download the file:
private void startDownload() {
String url = "my url";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Actualizando programa..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/myfile.json");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
I donĀ“t know where it will be save the file with this code and how can I read this file later locally.
To save your file, to your app dir use this:
//save to cache
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(activity.getFilesDir(), "/myfile.json")));
oos.writeObject(list);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
To retrieve content:
ObjectInputStream dis = new ObjectInputStream(new FileInputStream(new File(context.getFilesDir(), "/myfile.json")));
ArrayList<String> = (ArrayList<String>) dis.readObject();
dis.close();
I hope it helps!

Save downloaded file using the External Storage (private)

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.

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