Подтвердить что ты не робот

Android Как я могу прочитать json файл (текстовый файл) с SD-карты и отображать данные в текстовое окно

У меня есть следующий текстовый файл в моей SdCard. Теперь я хочу разобрать этот файл через парсер Json, и я хочу разобрать и прочитать этот файл и отобразить данные в своем текстовом виде, как я могу это сделать?

{
"data": [
    {
        "id": "1",
        "title": "Farhan Shah",
        "duration": 10,
    },
    {
        "id": "2",
        "title": "Noman Shah",
        "duration": 10,
    },
    {
        "id": "3",
        "title": "Ahmad Shah",
        "duration": 10,
    },
    {
        "id": "4",
        "title": "Mohsin Shah",
        "duration": 10,
    },
    {
        "id": "5",
        "title": "Haris Shah",
        "duration": 10,
    }
  ]

}

Это код:

File sdcard = Environment.getExternalStorageDirectory();

    //Get the text file

    File file = new File(sdcard,"textarabics.txt");

    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;


    //Read text from file
    StringBuilder text = new StringBuilder();

Я получаю файл, но теперь я не знаю, как я могу анализировать данные?

4b9b3361

Ответ 1

Прочитайте файл JSON с помощью File с SD-карты и используйте JSONObject, чтобы проанализировать его.

Здесь стартовый код:

    import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ReadJsonFile {
public ReadFile (){ 
            try {
            File yourFile = new File(Environment.getExternalStorageDirectory(), "path/to/the/file/inside_the_sdcard/textarabics.txt");
            FileInputStream stream = new FileInputStream(yourFile);
            String jsonStr = null;
            try {
                FileChannel fc = stream.getChannel();
                MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

                jsonStr = Charset.defaultCharset().decode(bb).toString();
              }
              catch(Exception e){
              e.printStackTrace();
              }
              finally {
                stream.close();
              }
/*  String jsonStr = "{\n\"data\": [\n    {\n        \"id\": \"1\",\n        \"title\": \"Farhan Shah\",\n        \"duration\": 10\n    },\n    {\n        \"id\": \"2\",\n        \"title\": \"Noman Shah\",\n        \"duration\": 10\n    },\n    {\n        \"id\": \"3\",\n        \"title\": \"Ahmad Shah\",\n        \"duration\": 10\n    },\n    {\n        \"id\": \"4\",\n        \"title\": \"Mohsin Shah\",\n        \"duration\": 10\n    },\n    {\n        \"id\": \"5\",\n        \"title\": \"Haris Shah\",\n        \"duration\": 10\n    }\n  ]\n\n}\n";
  */     
                 JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting data JSON Array nodes
                JSONArray data  = jsonObj.getJSONArray("data");

                // looping through All nodes
                for (int i = 0; i < data.length(); i++) {
                    JSONObject c = data.getJSONObject(i);

                    String id = c.getString("id");
                    String title = c.getString("title");
                    String duration = c.getString("duration");
                    //use >  int id = c.getInt("duration"); if you want get an int


                    // tmp hashmap for single node
                    HashMap<String, String> parsedData = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    parsedData.put("id", id);
                    parsedData.put("title", title);
                    parsedData.put("duration", duration);


                    // do what do you want on your interface
                  }


           } catch (Exception e) {
           e.printStackTrace();
          }
     }
}

Не забывайте добавлять хранилище чтения в свой mainfest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Ответ 2

Может быть полезно, что я взял с сайта разработчика Android.

Чтобы читать или записывать файлы на внешнем хранилище, ваше приложение должно получить системные разрешения READ_EXTERNAL_STORAGE или WRITE_EXTERNAL_STORAGE.

Вы можете установить разрешения в файле манифеста следующим образом:

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    ...
</manifest>

Вот несколько методов, которые вы можете использовать для проверки доступности:

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

Прочитайте содержимое файла, как показано ниже. После этого вы можете обрабатывать,

final File file = new File(Environment.getExternalStorageDirectory()
                          .getAbsolutePath(), filename);

Ответ 3

получить содержимое файла следующим образом:

File yourFile = new File("/mnt/extSdCard/test.json");
        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();
          }

разобрать и добавить в список:

String[] from = new String[] {"title"};
int[] to = new int[] { R.id.name};
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();

try 
{
    JSONArray names = new JSONArray(jsonString);
    Log.i("MyList","Number of names " + names.length());
    for (int j = 0; j < names.length(); j++) 
    {
         JSONObject jsonObject = names.getJSONObject(j);
         HashMap<String, String> map = new HashMap<String, String>();
         map.put("title", jsonObject.getString("title"));
         fillMaps.add(map);
    }
} 
catch (Exception e) 
{
    e.printStackTrace();
}

SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to);
mListView.setAdapter(adapter);

Здесь mListView - это ваш предопределенный ListView.