I created a json file locally. I can view that in data>data>com.example.storage>files>filename.json. Using this, I want to fetch all the text values locally & download a
Well its quite simple! here it goes:
private void DoWork() {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"file.json"); //path to your file assuming its in root of SD card
String content = "";
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
content = sb.toString();
} finally {
br.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
}
mTextView.setText(""); // A multiline text view big enough
mTextView.append("\n\n-----START CONTENT-----\n\n");
mTextView.append(content);
mTextView.append("\n\n-----START JSON-----\n\n");
try {
JSONArray jsonArray = new JSONArray(content);
int length = jsonArray.length();
for (int i = 0; i < length; i++) { /itterate throu json array
JSONObject obj = jsonArray.getJSONObject(i);
//here you can access individual parts of you json object by getString()...getBoolean().... etc...
mTextView.append("\n" + obj.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
To read an internal file belonging to the app directory try:
this.openFileInput("yourfile.txt");
//`this` is the reference to you Activity or Context
Example:
FileInputStream in = openFileInput("filename.txt");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
more details here