How can I read json file from SD card

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

+5
source share
1 answer

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

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

Step-2 Data Parsing. See How to parse a JSON string

Code example

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();}
+17
source

All Articles