How to read Json from online instead of asset folder - java

I was learning to make quiz app from online and it is going well. I was wondering instead of reading json from assets , it will be wise to read from online such that question can be added or changes accordingly and user don't have to update app.
Here is the JSON Structure.
{"questions" : [{"category":"general","question": "Grand Central Terminal, Park Avenue, New York is the world's", "choices": ["largest railway station","highest railway station","longest railway station","None of the above"], "correctAnswer":0},
{"category":"science","question": "Entomology is the science that studies", "choices": ["Behavior of human beings","Insects","The origin and history of technical and scientific terms","the formation of rocks"], "correctAnswer":1},
{"category":"science", "question":"What is known as the 'master gland' of the human body?", "choices":["Thyroid gland","Pituitary gland","Pineal gland","Pancreas"],"correctAnswer":1}
]}
and the code to read from assets is
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = mContext.getAssets().open("questionsJSON.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
I would like to show progress loading dialog when next question loads and any help will be largely appreciated. Thanks in advance.

Best option will be using REST APIs, Get data from Server/Database, which can be edited anytime from anywhere
You can learn to use Node js, it is not hard and it is based on JavaScript.
For getting JSON from APIs you can use Retrofit
Learning and implementing these things will be a bit hard if you are beginner but it will be the best option for long run
hope this helped!

Maybe consider using two different threads (or Runnables), one thread for downloading the JSON content and the other thread for displaying the GUI. For example, take a look at this: Stackoverflow Post
The solution involved making a Runnable that would first start downloading the data from the online website and then update the current progress onto the GUI thread as it is downloading. He uses the BufferedInputStream class so he can use a while loop to read the data in, update the number of bytes downloaded, get the current progress, and then display the results. I suppose you can do something similar here by using a while loop, and then checking if the download is finished. If so, you can close the display.

Related

How to stream an encrypted file?

I want to stream an encrypted file from the back-end to the front end using a jersey rest API. I searched on the internet for some clues. I found something that i thought could get the job done: https://github.com/google/ExoPlayer/issues/2467. There is an example on how to random access an cipherinputstream. I can stream the video, but i can't search through the video with the standard html5 videoplayer slider.
The problem is i don't know how to get the offset from the videoplayer where the video needs to continue playing.
Below is my endpoint. The StreamingCipherInputStream is the same as in the link above.
`#GET
#Produces("video/mp4")
#Path("stream/{id}")
public Response streamVideo(#PathParam("id") int id) throws Exception {
Video video = videoservice.getVideo(id);
StreamingCipherInputStream in =
videoservice.getVideoInputStream(video.getFilename());
StreamingOutput entity = output -> {
ReaderWriter.writeTo(in, output);
};
return Response.ok(entity).build();
}`
My question is how can i make it work with everything i have or are the some better options i'm missing?

Adding elements to an JSON object in a external JSON file?

(After months of surfing the internet, talking to the school's computing department and try code out, I still don't get how to do it, but I do know more specific about what I trying to do)
Previously I said I want to "Add lines" to a existing JSON file.
What I want to do is simply add an element to an JSON object from a file, then save the file.
However I am still confused about how to do it.
The process I am guessing is to use ajax to load the content of the file (the JSON code in the file) into a variable then add the new element into the object then save the file.
I have seen a lot of code but are all just too confusing and looks like its for webpages. I am trying to edit a file on the computer as a program which I think webpage related code such as xmlhttp requests are irrelevant as the file is in a folder in appdata.
I have been confused and thought Java and Javascript were the same thing, I know now they're not.
What code or functions would I look for and how would it be used in the code?
(Please don't post pseudocode because I have no idea how to write the code for them since I have literally no idea how to code anything other than a html webpage and some php. Other coding language like Java, Javascript and Python I have little knowledge with but not enough to write a program alone.)
I think it would be best to use code that somebody else has already written to manipulate the JSON. There are plenty of libraries for that, and the best would be the officially specified one, JSON-P. What you would do is this:
Go to http://jsonp.java.net/ and download JSON-P. (You will have to examine the page carefully to find the link to "JSON Processing RI jar".) You will need to include this JAR in your class path while you write your program.
Add imports to your program for javax.json.*.
Write this code to do the job (you will have to catch JsonExceptions and IOExceptions):
JsonReader reader = Json.createReader(new FileReader("launcher_profiles.json"));
JsonObject file = reader.readObject();
reader.close();
JsonObject profiles = file.getJsonObject("profiles");
JsonObject newProfile = Json.createObjectBuilder()
.add("name", "New Lines")
.add("gameDir", "New Lines")
.add("lastVersionId", "New Lines")
.add("playerUUID", "")
.build();
JsonObjectBuilder objectBuilder = Json.createObjectBuilder()
.add("New Profile Name", newProfile);
for (java.util.Map.Entry<String, JsonValue> entry : profiles.entrySet())
objectBuilder.add(entry.getKey(), entry.getValue());
JsonObject newProfiles = objectBuilder.build();
// Now, figure out what I have done so far and write the rest of the code yourself! At the end, use this code to write out the new file:
JsonWriter writer = Json.createWriter(new FileWriter("launcher_profiles.json"));
writer.writeObject(newFile);
writer.close();

Best API model design

I have offline JSON definitions (in assets folder) - and with them I create my data model. It has like 8 classes which all inherit (extend) one abstract Model class.
Would it be better solution if I parse the JSON and keep the model in memory (more or less everything is Integer or String) through the whole life cycle of the App or would it be smarter if I parse the JSON files as they are needed?
thanks
Parsing the files and storing all the data in the memory will definitely give you a speed advantage. The problem with this solution is that if your application will go to back-ground (the user receives a phone call or just leaves the app by his will), no one can guarantee that the data will stay intact in memory.
This data can be clear by the GC if the system decided that it needs more memory.
This means that when the user comes back to the application and if you relay on the fact that the data is in the memory you might face an exception. So you need to consider this situation.
And from that point of you it is good to store you data on a file that can be parsed at a desired time, even thought this might be a slower solution.
Another solution you may look at is to parse this data at first application start-up to an SQLite DB and use it from there, or even store it in the DB in the first place. This will give you the advantages of both worlds, you would not have to parse the data before using it, and you will have a quick access to it using a Cursor and you are not facing the problem of data deletion in case of insufficient memory in the system.
I'd read all the file content at once and keep it as a static String somewhere in my application that is available to all application components (SingleTone Pattern) since usually Maintaining a small string in the memory is much cheaper than opening and closing files frequently.
To solve the GC point #Emil pointed out you can write your code something like this:
public class DataManager {
private static String myData;
public static String getData(Context context){
if(myData == null){
loadData(context);
}
return myData;
}
private static void LoadData(Context context){
context.getAssets().
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("data.txt"), "UTF-8"));
StringBuilder builder = new StringBuilder();
do {
String mLine = reader.readLine();
builder.append(mLine);
} while (mLine != null)
reader.close();
myData = builder.toString();
} catch (IOException e) {
}
}
}
And from any class in your application that has a valid Context reference:
String data = DataManager.getData(context);

Adding elements from webpage to ArrayList in java

I'm currently working on a project that involves analyzing weather information from various airports and weather stations. What I need to do is display the basic weather info from a url (example: http://w1.weather.gov/xml/current_obs/KFHB.xml). Where I need to display temperature, visibility, etc. in some basic format. I was thinking an array list.
Can anyone tell me how to do this? How do I display the elements from a webpage onto a java application? What classes (methods, or other procedures) should I look into? Are there any good templates out there for this? Any help would be appreciated. Thanks.
You can read through the contents of the url like reading a file doing the following:
URL url = new URL(link);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
You can also capture the RSS feed from that weather station. Read this article if you want an an example as how to parse a RSS feed:
http://www.vogella.com/articles/RSSFeed/article.html

Android/Java How to read this file on website?

www.rgrfm.be/rgrsite/maxradio/android.php
www.rgrfm.be/rgrsite/maxradio/onair.txt
The track information of the music being played is contained in onair.txt. android.php is a php script I wrote.
I need to display the track information in my Android application. I do not want do download it to disk but keep it in memory. I don't know if the php script is useless because it would create additional overhead. So it's probably better to simply parse onair.txt
InputStream is = new URL("http://www.rgrfm.be/rgrsite/maxradio/onair.txt").openStream();
I am stuck with this. Has anyone got time to help me?
As described, php script seems useless. Since, you can directly read the text file. So, first read it as text, then parse it.
URL url = new URL("http://www.rgrfm.be/rgrsite/maxradio/onair.txt");
String text = readAsText(url)
parse(text);
String readAsText(URL url) {
// read the url as text here.
}
void parse(String text) {
}

Categories