create app with synchronization of remote files in Android studio - java

I am developing my app which contains some xml files used by some internal routines.
I would like to have the original xml files stored in a remote server, so that when a synchronization with such server is required by the user, the app updates the xml files, i.e. the version of the files present in remote is downloaded in local. Is it possible to realize such a setup? Is it possible to add a synchronize button inside the app? I develop in Android studio. For the moment, my app contains the local version of the xml files,
and the synchronization is missing.

Since these are not layout XML files,
Use something like this to download the file you need:
URL website = new URL("http://www.website.com/some_file.xml");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("some_file.xml");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
Put such block of code in the onClick method of the sync button
Modify the argument of the constructor of the FileOutputStream to save the file elsewhere
Save them somewhere like 'Environment.getExternalStorageDirectory() + "Android/package.name/files/some_file.xml'
And use the same path to get to the file and use it
I hope this helps
EDIT: As per your last comment, you need to identify each device using a uniqur identifier, which is usually hard to find being available on all android devices,I think you'd have to use Sign in/up system and thus means using PHP
Maybe there's better solution though

Related

How to write to local PC file from Android emulator app

I've been searching for hours and came across a lot of non-sense about read-only this and that and folders and directories and viewing the phone fs, etc. etc.
All I want to do is write to a file that is on my PC for an Android project. I've tried to use local paths (Windows) and have been met with read-only fs system problems, even after completely converting the desired folder to read AND write, Android refuses to get it. I set uses-permissions in my manifest with WRITE_EXTERNAL_STORAGE and WRITE_INTERNAL_STORAGE, but no luck.
I've tried to write to the phone, via emulator and actual physical phone, but every search I make turns up nothing (searching for the name of the file).
How can I write to a log file, any file that is where my development source code is? I need to digest JSON data from a web service call and I need it to be written to a local file so that I can work with it. The calls are through Android, currently an emulator, and an install on a physical device, yet no log is written because either a read-only problem which is non-sense, or I just can't find the damn file.
Any help would be greatly appreciated.
I guess ultimately the question I asked was just too messy. I wanted to know where I could find "local" logs on my Android device, which I can open and read myself in some text editor. I also wanted to know where "local" logs/files are written to my hard disk when testing the app via emulator.
At this point, I haven't found anything relating to a log file or any arbitrary file being able to be written from an Android app to a local dev PC without being pulled from something like adb.
I have found the solution to where I can write arbitrary files to an emulator or phone's filesystem (Source: https://www.journaldev.com/9383/android-internal-storage-example-tutorial):
FileOutputStream fos = Main.getAppContext().openFileOutput( "myfile.txt", Context.MODE_PRIVATE );
fos.write( "Hello, world".getBytes() );
fos.close();
Some things to note (Android SDK 26+ at least, others are untested):
FileOutputStream works very well.
"Main" refers to whichever entry point class you're using for your app. It most likely (or must?) extends AppCompatActivity.
Context.MODE_PRIVATE seems to be required.
AndroidManifest.xml permissions READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, READ_INTERNAL_STORAGE, WRITE_INTERNAL_STORAGE do NOT seem to be required.
Important: Files will be saved to /data/data/YOUR.APP.PACKAGE/files/.
This was also helpful: https://developer.android.com/training/data-storage

External Storage (public across apps)

I need to make a file in the Android External Storage area that can be accessed (read/write) by other apps.
I looked here but that says to pass it a directory type such as DIRECTORY_MUSIC, DIRECTORY_PICTURES etc.
But none of those types is what i want. So what I'm thinking is this:
File F = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyAppName" + File.separator + "MyFile");
Will this work or how can i ensure that a file will truly have public read/write access for other apps?
Also, I read somewhere that OutputStreams are only supposed to take a name with no path, and are always private, so how would i read/write ints to F?
Well, it seems to me that the statement for creating a new File you have there, would work. Although, why not try it out? Also, it is absolutely possible to write to a file and have it be accessible publicly, you do not need to do anything for this to happen, it will just happen by default. Reading/writing ints from/to the File can be done as usual, I recommend converting it to a String before writing.
It will works. You can ensure that a file truly have public access if you'll find it with some file manager and try to open it. In your example path to your file will be "%HOME_DIR%\MyAppName\MyFile". Also for creating file you could use FileOutputStream (not OutputStream), it takes File as parameter in constructor.
Files created in external storage are by default can be accessed by any other app (since the file is in external storage). The only thing you can control is the lifetime of the created file. As in whether the file should exist with your app only and deleted once the app is uninstalled or the file exists even after your app is removed.
If you want to create a file on your own path (not in DIRECTORY_PICTURE etc) inside your application then use getExternalFileDir() and pass null to it. See the link below for more details.
Saving file in external storage

Application files path in android

I'm working on an android application, I need to get the path where the files generated by the app are stored, conosco that using this:
this.getFilesDir();
or I can get that folder through:
OutputStreamWriter fout=
new OutputStreamWriter(
openFileOutput("prueba_int.txt", Context.MODE_PRIVATE));
fout.write("Texto de prueba.");
fout.close();
and then:
getFileStreamPath("samplefile.txt");
I can get that route, but I am making a library and I need to place a series of files in the specified path without using parameters or the context of the activity.
there is way to get it?
there is way to get it?
No.
You will need to modify your library to accept something as input that will let you read and write your data where and how the app wants. Ideally, you use some sort of Java interface that allows the app some flexibility (e.g., stores your data in its own encrypted container), with you supplying a stock implementation that perhaps uses File from the app's own Context.

Where to put text files in directory in Android

I have a text file i want to include in my Android application, it is not a string file it is a standard text file. It contains data that defines the characteristics of a "map" that is drawn on a board. The file is not an XML file so i am unsure where i should put it or if this isn't good file structure for android? Are you suppose to do this? If you are then under what directory are you suppose to put them? How then are you suppose to access the file? I know how to use FileInputStreams and FileOutputStreams i just need to know how to access the file. All relevant answers are welcome and appreciated!
Use assets or raw folder in your android folders structure to keep that file. For more info read this
You have to put your file in the assets folder as Waqas said.
Now to access it you do it like that.
I give you an example using BufferedReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("YourTextFile.txt")));
Be careful. In my case, I don't know why for now, I cannot read text files bigger than ~1MB and I had to split them in multiple small files. It seems other had the same problem of file size but I didn't find any information about that on Android developer site. If any one knows more about this ....
FOLLOW UP
My problem with the 1MB was due to a know bug/limitation of earlier versions of Android. Since using recent versions of Android, that problem is not present anymore.
I would just like to add to the accepted answer (I don't have enough reputation to comment unfortunately.) The link there to the tutorial that explains how to set up the res/raw method or the assets method is mostly good, but there's actually a MUCH easier way. Look at the function described there called LoadFile. That function is rather verbose. Lets say all you need is an InputStream variable so that you can read and write to a file. Then delete everything after line 77! Also you don't need the resource id at all! You can use this function:
//get the file as a stream
iS = resources.openRawResource(R.raw.mygpslog)
Now all you have to do is return iS and you will have your much desired file handle.
For reference, the tutorial is right here -> http://www.41post.com/3985/programming/android-loading-files-from-the-assets-and-raw-folders

How I save and retrieve an image on my server in a java webapp [duplicate]

This question already has answers here:
How to save uploaded file in JSF
(2 answers)
Closed 7 years ago.
Here with another question on Images ( which seems to be more difficult than I initialy predicted) I'm working on a java Web app with JSF 2.0 ( apache myFaces) and I want this app to be able to upload a picture to a destination on the server it's going to run on. I have a Windows r2 2008 Server running a mySQL Db, but I don't want to store the image in the db, I'd rather store it somewhere in the server and then just save the path as a string in the db.
I was told this is the best way, but I can't seem to find an example on how to save it on the server. I run the app on the Apache tomcat Server as a WAR file. so I don't know if I have to save the file to a path on the server drive (i.e. C:\images) or a special folder in the project itself ( within the java, html files) any help at all is greatly appreciated. I'm totally lost and have been stuck the whole day trying to figure this out.
The code I use to upload the image to the java class is this ( courtesy of CodyS):
InputStream is = uploadedFile.getInputStream();
byte[] buffer = new byte[(int) uploadedFile.getSize()];
is.read(buffer);
File f = new File("C:\\temp\\" + this.patient.getPk() + ".jpeg");
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer); //This is where I write it to the C Drive
fos.close();
is.close();
instead of writing it to my C drive I'm going to run it on the server, but where should I store the image to later retriev and display in an xhtml file? I hope I'm being clear on what I need, let me know if I am not and I'll try to explain in another way.
instead of writing it to my C drive I'm going to run it on the server, but where should I store the image to later retriev and display in an xhtml file?
That depends on how much control you have over configuring the server. Ideal would be to configure a fixed path outside the Tomcat webapps folder. For example, /var/webapp/upload. You can set this path as a VM argument or environment variable so that your webapp can retrieve it programmatically without the need to change the code.
For example, when specifying as VM argument -Dupload.location=/var/webapp/upload, you can complete the upload as follows:
Path folder = Paths.get(System.getProperty("upload.location"));
String filename = FilenameUtils.getBaseName(uploadedFile.getName());
String extension = FilenameUtils.getExtension(uploadedFile.getName());
Path file = Files.createTempFile(folder, filename + "-", "." + extension);
try (InputStream input = uploadedFile.getInputStream()) {
Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING);
}
String uploadedFileName = file.getFileName().toString();
// Now store it in DB.
As to serving the file back, most ideal would be to add the upload location as a separate <Context> to Tomcat. E.g.
<Context docBase="/var/webapp/upload" path="/uploads" />
This way you can access it directly by http://example.com/uploads/foo-123456.ext
If you have zero control over configuring the server, then, well, storing in the DB or sending to a 3rd party host such as Amazon S3 is your best bet.
See also:
How to provide relative path in File class to upload any file?
Reliable data serving
I would consider allowing the user to upload to Amazon S3 directly. Amazon offers a service for that. Using that service, the client would post a form with the file directly to S3. Once the file has arrived there, Amazon will redirect the client to one of your endpoints, to confirm that the data has arrived, passing you the relevant details.
The benefits are:
Your server does not spend a lot of time in receiving huge files. You can spend your CPU cycles on something a little bit more interesting.
The availability guaranteed by storing it on S3 is probably better then what you would get by storing it on your own Windows box.
It scales. At some point, your filesystem will run out of space. (Or you reach the limit of what you can store inside a folder.)
I'd suggest that you save your images in a subfolder which is in your application's WEB-INF folder. Remember that when you use Tomcat, your WAR files will be extracted automatically. This approach also has the advantage that you can always migrate your application to another server, you only have to save the path relative to WEB-INF folder in your DB.

Categories

Resources