2014-02-23 57 views
11

我將下列文本文件插入到我的SdCard中。現在我想通過Json解析器解析此文件,並且我想解析並閱讀本文文件和顯示數據到我的textview,我怎麼能做到這一點?Android如何從SD卡中讀取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, 
    } 
    ] 

} 

這是代碼:

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

我得到的文件,但現在我不知道該怎麼樣,我可以分析數據?

+0

是閱讀文件或解析文件的問題,我假設你知道如何在文本視圖中顯示的東西。 – Tomas

+0

我想通過json解析此文件並將數據顯示到我的文本視圖 –

+0

downvote的原因??? –

回答

19

使用SD卡中的File讀取JSON文件並使用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(); 
      } 
    } 
} 

Ddon't忘記您mainfest添加讀取存儲:

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

親愛的感謝您的答覆,kindely告訴我JSONObject jsonObj = new JSONObject(jsonStr);在參數中,什麼是jsonStr?它給我錯誤。 –

+0

多數民衆贊成在這個問題,檢查我的編輯jsonStr是一個字符串 – Smile2Life

+0

親愛的當我來到這一點JSONObject jsonObj = new JSONObject(jsonStr); .....它的崩潰,對此有任何想法,這是我的崩潰報告.. org .json.JSONException:類型java.lang.String的值不能轉換爲JSONObject –

2

得到的文件內容是這樣的:

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控件。

+0

JSONArray names = new JSONArray(jsonString);在參數中是什麼jsonString? –

4

下面可能是有用的,這是我從Android開發者網站採取。

爲了讀取或寫入外部存儲器上的文件,您的應用程序必須獲取READ_EXTERNAL_STORAGEWRITE_EXTERNAL_STORAGE系統權限。

您可以設置權限在manifest文件是這樣的:

<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); 
相關問題