2016-01-01 137 views
-2

我对Android开发并不陌生,但我编写了很多C#(WinF,WPF)。我为应用程序创建了一个测验应用程序(德语单词),我不太确定如何存储和加载字典(一个文件,其中行包含2个单词)。什么是存储这些字典的最佳方式?我搜索了一下,但没有找到确切的答案。目前,我直接在代码中生成单词。 谢谢!什么是存储文本数据的最佳方式?

+0

您可以将其存储在资产产生的文件夹,并可以访问这些文件 –

+0

SharedPreferences。 –

回答

1

正如你刚才的键值对,我会建议从你的数据创建一个json,存储到assests文件夹并在运行时使用。

例如, CountyCode.json

[ 
    { 
    "country_name": "Canada", 
    "country_code": 1 
    }, 
    { 
    "country_name": "United States of America", 
    "country_code": 1 
    }, 
    { 
    "country_name": "US Virgin Islands", 
    "country_code": 1 
    }, 
    { 
    "country_name": "Russia", 
    "country_code": 7 
    }, 
    { 
    "country_name": "Tajikistan", 
    "country_code": 7 
    }] 

负荷和使用下面的代码需要时解析JSON数据。

要从入资产价值文件夹加载JSON

String countryJson = FileManager.getFileManager().loadJSONFromAsset(getActivity(), "countrycode.json");

解析JSON和使用

   try { 
        JSONArray jsonArray = new JSONArray(countryJson); 
        if (jsonArray != null) { 
         final String[] items = new String[jsonArray.length()]; 
         for (int i = 0; i < jsonArray.length(); i++) { 
          JSONObject jsonObject = jsonArray.getJSONObject(i); 
          items[i] = jsonObject.getString("country_name"); 
         } 

FileManager.java

import android.content.Context; 

import java.io.IOException; 
import java.io.InputStream; 

/** 
* Created by gaurav on 10/10/15. 
*/ 
public class FileManager { 
    static FileManager fileManager = null; 

    private FileManager(){} 

    public static FileManager getFileManager() 
    { 
     if(fileManager==null) 
      fileManager = new FileManager(); 
     return fileManager; 
    } 

    public String loadJSONFromAsset(Context context,String fileName) { 
     String json = null; 
     try { 
      InputStream is = context.getAssets().open(fileName); 
      int size = is.available(); 
      byte[] buffer = new byte[size]; 
      is.read(buffer); 
      is.close(); 
      json = new String(buffer, "UTF-8"); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
      return null; 
     } 
     return json; 
    } 
} 
+0

FileManager类从哪里来? –

+0

为filemanager类添加了代码。 – CodingRat

+0

非常感谢,抱歉接受这样的答案。我还没有尝试过,我今晚会试试它。 – Topna

相关问题