How to load XML file online and process? - file

I want to make an android app that is actually a RSS reader. This will load XML file from a particular link like http://kalaerkantho.com/rss.xml. After downloading I know how to parse it. But my question is how to download it first so that I can process the downloaded file.

Try this:
private static void downloadFile(String url, String filePath) {
try {
File outputFile = new File(filePath);
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
}
}
Adapted from this answer.

Related

How to open a PDF file downloaded and stored in the Download folder an a mobile device?

I've researched different solutions to this problem, but none of them works for me. I am trying to download a file from Firebase (which I am successful in doing) and then I am trying to open that file in my app right after the download completes. However, my app either crashes or does nothing.
Below is the code for downloading the file (from FirebaseStorage which works):
public void download(String name) {
final String pdf_name = name.substring(0, name.lastIndexOf('.'));
storageReference = firebaseStorage.getInstance().getReference();
ref=storageReference.child("Auctions/" + name);
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
downloadFile(ActiveAuctionsActivity.this, pdf_name, ".pdf", DIRECTORY_DOWNLOADS, url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
SpannableString spannableString = new SpannableString("אין תיק עבודה למכרז זה");
spannableString.setSpan(
new ForegroundColorSpan(getResources().getColor(android.R.color.holo_red_light)),
0,
spannableString.length(),
0);
Toast.makeText(ActiveAuctionsActivity.this, spannableString, Toast.LENGTH_LONG).show();
}
});
}
public void downloadFile(Context context, String fileName, String fileExtention, String destinationDirectory, String url){
DownloadManager downloadmanager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDescription("מוריד.....");
//request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName + fileExtention);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName + fileExtention);
// call allowScanningByMediaScanner() to allow media scanner to discover your file
request.allowScanningByMediaScanner();
downloadmanager.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Toast.makeText(getApplicationContext(), "מוריד את התיק העבודה.....",
Toast.LENGTH_SHORT).show();
}
After, I setup the receiver with the openFile() method:
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(getApplicationContext(), "ההורדה הסתיימה",
Toast.LENGTH_LONG).show();
openFile("GMU.pdf");
}
};
public void openFile(String fileName){
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
Uri path = Uri.fromFile(file);
Log.i("Fragment2", String.valueOf(path));
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
Toast.makeText(ActiveAuctionsActivity.this, "error", Toast.LENGTH_LONG).show();
}
}
Again, the file does download, but doesn't open.
What am I doing wrong, could you please advise me?
EDIT
I also tried the code below as my openFile() but that also doesn't work:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setDataAndType(path, pdfOpenintent.getType());
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
ActiveAuctionsActivity.this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
pdfOpenintent.setType("application/*");
startActivity(Intent.createChooser(pdfOpenintent, "No Application found to open File - " + fileName));
}

Not able to move files from Google Drive to Blobstore

I was moving files from Google drive to blobstore using the below code . But now the FileWriteChannel is deprecated and the code is not working. Is there an alternative solution for this problem ?
private BlobKey getBlobKey(File f, DriveObject driveObject)
throws IOException, MalformedURLException {
Drive service = ((GoogleDrive) driveObject).getService();
byte[] buffer = new byte[(int) f.getFileSize().intValue()];
GenericUrl url = new GenericUrl(f.getDownloadUrl());
HttpResponse response = service.getRequestFactory()
.buildGetRequest(url).execute();
InputStream is = response.getContent();
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = null;
boolean lock = true;
try {
file = fileService.createNewBlobFile("application/zip");
FileWriteChannel writeChannel = fileService.openWriteChannel(
file, lock);
int len;
while ((len = is.read(buffer)) >= 0) {
ByteBuffer bb = ByteBuffer.wrap(buffer, 0, len);
writeChannel.write(bb);
}
writeChannel.closeFinally();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BlobKey bk = fileService.getBlobKey(file);
return bk;
}
You need to use Java Client library:
GcsOutputChannel outputChannel =
gcsService.createOrReplace(fileName, GcsFileOptions.getDefaultInstance());
outputChannel.write(ByteBuffer.wrap(content));
outputChannel.close();

RESTClient java program returning unreadable output on console?

public class helloWorldClient {
public static void main(String[] args) {
helloWorldClient crunchifyClient = new helloWorldClient();
crunchifyClient.getResponse();
}
private void getResponse() {
try {
Client client = Client.create();
WebResource webResource2 = client.resource("http://localhost:8080/Downloader/webapi/folder/zipFile");
ClientResponse response2 = webResource2.accept("application/zip").get(ClientResponse.class);
if (response2.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response2.getStatus());
}
String output2 = response2.getEntity(String.class);
System.out.println("\n============RESPONSE============");
System.out.println(output2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This program returning an unreadable output. but when I hit that URL "http://localhost:8080/Downloader/webapi/folder/zipFile" in browser "server.zip" file is getting downloaded.
My question is how can I read that response and write to some folder through java client program?
You can get the InputStream instead of String. Then just do your basic IO.
InputStream output2 = response2.getEntity(InputStream.class);
FileOutputStream out = new FileOutputStream(file);
// do io writing
// close streams
InputStream output2 = response2.getEntity(InputStream.class);
OutputStream out = new FileOutputStream(new File("/home/mpasala/Downloads/demo.zip"));
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = output2.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
output2.close();
out.close();
System.out.println("Done!");
Thanks to https://stackoverflow.com/users/2587435/peeskillet .

display bytes from database as image in imageview in javafx

please I have been stuck on how to convert my stored images from my
database and display it as an image in imageview in javafx.
All the
previously asked questions have not helped me.
I'm using objectdb as my database
I also used fxml to build my GUI
for (Person p : person) {
name.setText(p.getName());
gender.setText(p.getGender());
byte[] byteArray = p.getImage();
image.setImage(new Image(new ByteArrayInputStream(byteArray)));
}
I'll show a detailed step on saving to the database using a file chooser and writing an image to a file in a directory(folder) on your hard drive, and also displaying it to imageview in fmxl GUI.
The following below are triggered during a button event or initialized
from the controller
FileChooser choose = new FileChooser();
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
choose.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
File file = choose.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
byte[] b;
try (ByteArrayOutputStream out = new ByteArrayOutputStream(262144)) {
ImageIO.write(bufferedImage, "jpg", out);
out.flush();
b = out.toByteArray();
}
EntityService service = new EntityService();
Person p = new Person();
p.setId(UUID.randomUUID().toString());
p.setImage(b);
service.putPerson(p);
} catch (IOException e) {
e.printStackTrace();
}
Person p = service.getPerson();
byte[] byteArray = p.getImage();
ByteArrayInputStream in = new ByteArrayInputStream(byteArray);
BufferedImage read = ImageIO.read(in);
image.setImage(SwingFXUtils.toFXImage(read, null));
String output = "C:\\java\\images\\1.jpg";
try (FileOutputStream fos = new FileOutputStream(output)) {
fos.write(byteArray);
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex);
} catch (IOException ioe) {
System.out.println("IOException : " + ioe);
}

How do I backup a database file to the SD card on Android?

I'd like to add a feature to my Android app that automatically backs up the SQLite database to the SD card.
What's the best way to go about this? Are any examples or tutorials available?
This code works for me!
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//{package name}//databases//{database name}";
String backupDBPath = "{database name}";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
}
Does anyone know if this will work on non-root phones? I have only tried it on a rooted G1.
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+ packageName +"//databases//"+dbList[0];
String backupDBPath = dbList[0];
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
That works as opposed to the above examples in which the "/" are "\" wasted 20 minutes of my life figuring that out, but I really should have seen that sooner. The Toast will tell you where the file has been place or tell you what's wrong when it doesn't work.
SQLite databases are completely self-contained files and are portable — you can just copy the entire file straight to the SD card.
Though first I'd check whether an SD card is installed in the device, and what its path is (using Environment.getExternalStorageDirectory()).
I answered a question similar to this with a method you can place in your SQLiteOpenHelper. It is as simple as copying the db file from some kind of external storage, to the internal application storage. There is also some extra code that opens and reads the db file to make sure it is in the proper state for Android to make database calls to it.
public static void BackupDatabase() throws IOException
{
boolean success =true;
File file = null;
file = new File(Environment.getExternalStorageDirectory() +"/M.O.L.S_Backup");
if (file.exists())
{
success =true;
}
else
{
success = file.mkdir();
}
if (success)
{
String inFileName = "/data/data/com.sygic.sdk.demo/databases/MOLS_DB.s3db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/M.O.L.S_Backup/MOLS_DB.s3db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
fis.close();
}
}
You have to give the permission android.permission.WRITE_EXTERNAL_STORAGE in your application. It works fine on unrooted devices.
I don't know what happens if the phone is rooted or not but you should write your files to:
/Android/data/{package_name}/files/
This will work whether it's rooted or not.
You find your Database Name in the Database Adapter if you are new into this.
Note that you can do this for SharedPreferences too but keep in mind to change your Context.MODE_PRIVATE to Context.MODE_MULTI_PROCESS.
SharedPreferences_name should look like this = ExportSP("temp.xml");
String currentPathForSharedPreferences = "/data/"+ context.getPackageName() +"/shared_prefs/"+ SharedPreferences_name;
For export
exportDB("MyDbName");
private void exportDB(String db_name){
File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "Your Backup Folder"+
File.separator );
boolean success = true;
if (!sd.exists()) {
success = sd.mkdir();
}
if (success) {
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
String backupDBPath = db_name;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
} catch(IOException e) {
e.printStackTrace();
}
}}
For import
importDB("MyDbName");
private void importDB(String db_name){
File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "Your Backup Folder"+
File.separator );
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String backupDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
String currentDBPath = db_name;
File currentDB = new File(sd, currentDBPath);
File backupDB = new File(data, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
} catch(IOException e) {
e.printStackTrace();
}
}
#skeniver's code works for me. I just want to add the following:
Use:
String currentDbPath = getApplicationContext().getDatabasePath("{database name}");
It will give you your database path. It is better to use that instead of hardcoding the path, like:
String currentDbPath = "//data//{package name}//databases//{database name}";
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+getPackageName()+"//databases//"+DATABASE_NAME+"";
String backupDBPath = "backup.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}

Resources