I am kinda new to Android development, but I coded a lot of C#(WinF,WPF). I created an quiz app (German words) for app and I'm not quite sure how to store and load dictionaries (a file, where lines contain 2 words). What is the best way to store these dictionaries? I googled a bit, but didn't find exact answers. At the moment I generate the words directly in the code. Thanks!
Asked
Active
Viewed 111 times
-2
-
You can store it in assests folder and can access the files – Rohit Heera Jan 01 '16 at 11:27
1 Answers
1
As you have just key-value pair i will suggest to create a json from your data, store into assests folder and use at runtime.
For eg. 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
}]
load and parse json data when needed using following code.
To load json from assests folder
String countryJson = FileManager.getFileManager().loadJSONFromAsset(getActivity(), "countrycode.json")
;
parse json and use
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;
}
}

CodingRat
- 1,934
- 3
- 23
- 43
-
-
-
Thank you so much, sorry for accepting the answer so yet. I haven't tried it out, Im going to try it tonight. – Topna Jan 01 '16 at 19:03