For Android App development, the most common question is how to initialize the application when launching the app. The most simple way to initialize the Android app is doing the job in OnCreate function of your Activity class, especially for Activity related init work. In this tutorial, I will show you how to load a built-in JSON file to initialize a ListView with word and images.
This is the 2nd tutorial of my Android ListView Based App Tutorial series. The whole tutorial has 4 sessions:
- Android ListView App Template Guide: Start From Planning
- Android ListView App Template Guide: Loading Local JSON Configuration File
- Android ListView App Template Guide: Customize ListView Item Layout Style
- Android ListView App Template Guide: Play MP3 File From ListView Playlist
- Android App ListView App Template Guide: Listen EditText Changes (Coming Soon)
Read Local JSON File in OnCreate Function
In this example, I will read a JSON file which is built-in the Android app. After loading the JSON in JSONObject, I will sort the key by alphabet sequence and feed the sorted data into ListView. First, let me show you the layout.xml source code. It is quite simple, I just put a ListView on the screen.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/zerodp" android:paddingLeft="@dimen/zerodp" android:paddingRight="@dimen/zerodp" android:paddingTop="@dimen/zerodp"> <ListView android:id="@+id/wordlist" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
The above layout is used by Fragment class. In my Activity class, I will instantiate the Fragment. Then, all init jobs will be in the onCreateView function of Fragment class. The following example code is my Activity onCreate function.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WordListFragment pFragment = new WordListFragment(this); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, pFragment).commit(); } }
Now, let me show you Fragment class source code. WordListFragment is the subclass of Fragment. All the init jobs are done in onCreateView function. Here is the source code:
public static class WordListFragment extends Fragment { private Context context; public ArrayList<WordData> englishWordList = null; public ListView wordListView = null; public WordListAdapter wordListAdapter = null; public WordListFragment(Context c) { context = c; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.wordlist, container, false); try { InputStream wordListSteam = this.getResources().openRawResource(R.raw.words); String wordListStr = Utils.readStringFromStream(wordListSteam); JSONObject wordList = new JSONObject(wordListStr); JSONArray keyArray = wordList.names(); //sort json objects List<String> jsonKey = new ArrayList<String>(); for(int i=0; i<keyArray.length(); i++) { jsonKey.add(keyArray.getString(i)); } Collections.sort(jsonKey); keyArray = new JSONArray(jsonKey); englishWordList = new ArrayList<WordData>(); for (int i=0; i < keyArray.length(); i++) { WordData wd = new WordData(); wd.word = keyArray.getString(i); wd.translation = wordList.getString(wd.word); englishWordList.add(wd); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } wordListView = (ListView) rootView.findViewById(R.id.wordlist); wordListAdapter = new WordListAdapter(context, R.layout.worditem, englishWordList); wordListView.setAdapter(wordListAdapter); return rootView; } } [/java] <h3>Read JSON File Into JSONObject</h3> The source code is very long, but it is not very complicated actually. I will help you to explain the source code piece by piece. In onCreateView function above, I read the json content and save the content in JSONObject. [java] InputStream wordListSteam = this.getResources().openRawResource(R.raw.words); String wordListStr = Utils.readStringFromStream(wordListSteam); JSONObject wordList = new JSONObject(wordListStr);
After that, I have to sort the JSON key even I already draft my json data in alphabet sequence. Here is the example of my json file (English to Spanish).
{ "almond":"almendra", "apple": "manzana", "apricot": "albaricoque", "avocado": "aguacate", "banana": "plátano", "breadfruit":"árbol del pan" }
Sort JSON Array
But in JSON’s defination, the JSON object is an unordered set of name/value pairs. So Android will not preserver the order of name/value pairs after we load the json content in JSONObject. Hence, I have to write some code to sort the name(key) again. (There are lots of solutions on the internet, you can leave a reply here if you find a better one.)
//sort json objects Now we get the sorted JSON object ready. Next, I will build my own data structure which will be used later to feed my ListView adapter. Here is the source code example. englishWordList = new ArrayList for (int i=0; i < keyArray.length(); i++) {
WordData wd = new WordData();
wd.word = keyArray.getString(i);
wd.translation = wordList.getString(wd.word);
englishWordList.add(wd);
}
wordListView = (ListView) rootView.findViewById(R.id.wordlist);
wordListAdapter = new WordListAdapter(context, R.layout.worditem, englishWordList);
wordListView.setAdapter(wordListAdapter);
[/java]
Here is how my ListView looks like:
You can download and install this android app from Google Play, or scan the following QR code to download and install on your android phone simply. If you feel it is helpful, please support me by clicking the banner inside the app. Scan the following QR code to download this app in Google Play easy and fast.
JSONArray keyArray = wordList.names();
List
for(int i=0; iTry The Android App
Get Full Android App Template Source Code under $5.99
You will get whole Android App ListView template source code at $5.99. With this source code, you can do everything you want: