I download json data from server and I want to save them to a file in android mobile.
How can I do it with external storage? When I save them I also want to search in file for specific data. Is there a better way to do that than external storage?
//parse json data
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
category = new String[jArray.length()];
name = new String[jArray.length()];
date = new String[jArray.length()];
content = new String[jArray.length()];
for(int i=0;i<jArray.length()+2;i++){
HashMap<String, String> map = new HashMap<String, String>();
if(i==0){
if(category8 == "All"){
map.put("id", "5");
map.put("name", " All Posts");
map.put("latitude", "");
map.put("longitude", "");
map.put("date", "");
map.put("content", "");
mylist.add(map);
} else {
json_data = jArray.getJSONObject(i);
category[i] = json_data.getString("category");
map.put("id", "5");
map.put("name", " "+category[i]);
map.put("latitude", "");
map.put("longitude", "");
map.put("date", "");
map.put("content", "");
mylist.add(map);
}
} else if(i<jArray.length()+1) {
json_data = jArray.getJSONObject(i-1);
id = json_data.getInt("post_id");
name[i-1] = json_data.getString("username");
latitude = json_data.getDouble("latitude");
longitude = json_data.getDouble("longitude");
date[i-1] = json_data.getString("post_date");
content[i-1] = json_data.getString("post_content");
map.put("id", String.valueOf(id));
map.put("name", name[i-1] + " wrote:");
map.put("latitude", "Latitude: " + latitude);
map.put("longitude", "Longitude: " + longitude);
map.put("date", "Date: " + date[i-1]);
map.put("content", content[i-1]);
mylist.add(map);
}
if(i==jArray.length()+1) {
map.put("id", "5");
map.put("name", "");
map.put("latitude", "");
map.put("longitude", "");
map.put("date", "");
map.put("content", "");
mylist.add(map);
}
}
} catch(JSONException e1) {
Toast.makeText(getBaseContext(), "No posts found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
JSON needs to be parsed in order to get information from it. So saving a JSON-Request and parsing it every time you need information from it is generally a bad idea.
Instead, you’ll want to parse it once, get your desired information, and save them somewhere you can easily access them. Where and how to save them differs from what you want to do with it:
Also, you said you wanted to store those things on the external storage. Generally speaking: Storing things which belong to your application on the external storage is a bad idea. There are however some cases where it makes sense:
ContentProvider)Keep in mind that every file saved on the external storage can be manipulated! Also, you can’t rely on the external storage because some users might don’t have one.
In cases other then the listed above, it’s a better idea to use the internal storage.