Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read json file from SD Card

I need to read a json file from the SD card and display the data in the spinner. Is there any way to read the data from file in Android and display the contents of that file in spinner?

like image 999
saini Avatar asked Dec 14 '11 04:12

saini


People also ask

How can I view JSON files?

Cross-platform to open JSON files: Generally, users can open the JSON file in any text editor as it is a plain text-based file. The Google Chrome and Mozilla Firefox web browsers are cross-platform to open JSON files that are compatible with every operating system (OS).


1 Answers

First read the file from SD card and then parse that file

Step-1 Retrieve the data from file from SD card. see tutorial

Step-2 Parse the data. See How to parse JSON String

Sample code

try {

            File dir = Environment.getExternalStorageDirectory();
            File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
            FileInputStream stream = new FileInputStream(yourFile);
            String jString = null;
            try {
                FileChannel fc = stream.getChannel();
                MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                /* Instead of using default, pass in a decoder. */
                jString = Charset.defaultCharset().decode(bb).toString();
              }
              finally {
                stream.close();
              }


                    JSONObject jObject = new JSONObject(jString); 



        } catch (Exception e) {e.printStackTrace();}
like image 126
Sunil Kumar Sahoo Avatar answered Sep 21 '22 18:09

Sunil Kumar Sahoo