Android如何從SD卡讀取json文件(文本文件)並將數據顯示到textview [復制]

[英]Android How can I read json file(text file) from SD Card and display data into textview [duplicate]


This question already has an answer here:

這個問題在這里已有答案:

I have the following textfile into my SdCard.now i want to parse this file via Json parser,and i want to parse and read this file and display data into my textview,how i can do this?

我有以下文本文件到我的SdCard.now我想通過Json解析器解析這個文件,我想解析並讀取這個文件並將數據顯示到我的textview中,我該怎么做?

{
"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,
    }
  ]

}

This is the code:

這是代碼:

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();

i get the file,but now i have no idea that how i can parse the data?

我得到了文件,但現在我不知道如何解析數據?

3 个解决方案

#1


19  

Read the JSON file using File from SD card and use JSONObject to parse it.

使用SD卡中的File讀取JSON文件,並使用JSONObject對其進行解析。

Here a starting code:

這是一個起始代碼:

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

Ddon't forget to add read storage on your mainfest:

別忘了在mainfest上添加讀取存儲:

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

#2


4  

Following may be useful, which I have taken from android developer site.

以下可能有用,我從android開發者網站獲取。

In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions.

要在外部存儲上讀取或寫入文件,您的應用必須獲取READ_EXTERNAL_STORAGE或WRITE_EXTERNAL_STORAGE系統權限。

You can set the permissions in your manifest file like this:

您可以在清單文件中設置權限,如下所示:

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

Here are a couple methods you can use to check the availability:

您可以使用以下幾種方法檢查可用性:

/* 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;
}

Read the file content as given below. After that you can process,

閱讀下面給出的文件內容。之后你可以處理,

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

#3


2  

get the file contents like this:

得到這樣的文件內容:

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

parse and add to listview:

解析並添加到listview:

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);

Here mListView is your predefined ListView.

這里mListView是您預定義的ListView。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/02/23/f92f7cd3e3cd825665b1e18bfcd8dba.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com