Android Json Example- How To Show JSON Data In TableView In Android
To an Android developer, JSON is a lifesaver that manages Data as easily as cutting through butter. But many developers face a problem while using it. They end up asking themselves, android json example- how to show json data in tableview in android?
Use the fetch() command to get the data from any URL or API. You will have to use response.json() to use the data you just fetched. After that, use SimpleAdapter as ListAdapter under the TableView command to get the desired output.
For a developer, the steps we talked about will make complete sense. But if you are an amateur in Android development, you might need elaborate instructions. On the other hand, for any complete newbie, let’s start with JSON.
What is JSON?
Similar to most programing and developers, JSON is not the actual word. It is the abbreviation of JavaScript Object Notation.
This is the best alternative for XML to fetch data from external servers. It is Lightweight, structured, and, most importantly, readable by humans.
Unlike XML parsing, the complexity of JSON parsing is thousand of times simpler. It’s shorter, simpler, and faster if you want to interchange data. Most of the user-friendly API out there recognize this truth and support JSON.
If you think about what classes JSON has, you will be surprised that it has four. These four classes are enough to manipulate any JSON data and interchange it with a data server. The classes are:
- JSONObject
- JSONTokenizer
- JSONStringer
- JSONArray
In most cases, an Android developer is faced with the hurdle of fetching data from a given URL or API and displaying it in table format. So, they have to use JSON to parse the information and execute it. Then how to display JSON data in table view in android?
Android Json Example- Static TableView
Many will suggest you use a static loop if you ask them android json example- how to show json data in tableview in android? Though this can be one of the viable solutions, it is not the best. If you want the best solution, you can follow these steps.
But before we start Parsing the JSON data, we will need to create a URL. For convenience, we will make our one URL database using the following steps.
Step 01: Create the database from which you want to interchange the data.
Step 02: Make a table with three columns. We took Match ID (int), Team A (varchar), and Team B (varchar).
Step 03: Using PHPMyadmin, insert data in the table. In our example, we inserted the World Cup fixture.
Step 04: Now, we will turn these PHP data into JSON formatted data using three PHP files. The files will have to be in a folder called “wamp,” and they are:
- php
- php
- php
Step 05: Open http://localhost/tech/getFixture.php in your browser.
{“fixture”:[
{
“matchId”:”1″,
“teamA”:”BRAZIL”,
“teamB”:”CROATIA”
},
{
“matchId”:”2″,
“teamA”:”MEXICO”,
“teamB”:”CAMEROON”
},
{
“matchId”:”3″,
“teamA”:”SPAIN”,
“teamB”:”NETHERLANDS”
},
{
“matchId”:”4″,
“teamA”:”CHILE”,
“teamB”:”AUSTRALIA”
},
{“matchId”:”5″,
“teamA”:”COLOMBIA”,
“teamB”:”GREECE”
},
{
“matchId”:”6″,
“teamA”:”URUGUAY”,
“teamB”:”COSTA RICA”
},
{
“matchId”:”7″,
“teamA”:”ENGLAND”,
“teamB”:”ITALY”
},
{
“matchId”:”8″,
“teamA”:”IVORY COAST”,
“teamB”:”JAPAN”
},
{
“matchId”:”9″,
“teamA”:”SWITZERLAND”,
“teamB”:”ECUADOR”},
{
“matchId”:”10″,
“teamA”:”FRANCE”,
“teamB”:”HONDURAS”
},
{
“matchId”:”11″,
“teamA”:”ARGENTINA”,
“teamB”:”BOSNIA”
},
{
“matchId”:”12″,
“teamA”:”GERMANY”,
“teamB”:”PORTUGAL”
},
{
“matchId”:”13″,
“teamA”:”IRAN”,
“teamB”:”NIGERIA”
},
{
“matchId”:”14″,
“teamA”:”GHANA”,
“teamB”:”USA”},
{
“matchId”:”15″,
“teamA”:”BELGIUM”,
“teamB”:”ALGERIA”
},
{
“matchId”:”16″,
“teamA”:”BRAZIL”,
“teamB”:”MEXICO”
},
{
“matchId”:”17″,
“teamA”:”RUSSIA”,
“teamB”:”SOUTH KOREA”
},
{
“matchId”:”18″,
“teamA”:”AUSTRALIA”,
“teamB”:”NETHERLANDS”
},
{
“matchId”:”19″,
“teamA”:”SPAIN”,
“teamB”:”CHILE”
},
{
“matchId”:”20″,
“teamA”:”CAMEROON”,
“teamB”:”CROATIA”
},
{
“matchId”:”21″,
“teamA”:”COLOMBIA”,
“teamB”:”IVORY COAST”
},
{“matchId”:”22″,
“teamA”:”URUGUAY”,
“teamB”:”ENGLAND”
},
{
“matchId”:”23″,
“teamA”:”JAPAN”,
“teamB”:”GREECE”
},
{
“matchId”:”24″,
“teamA”:”ITALY”,
“teamB”:”COSTA RICA”
},
{
“matchId”:”25″,
“teamA”:”SWITZERLAND”,
“teamB”:”FRANCE”
},
{
“matchId”:”26″,
“teamA”:”HONDURAS”,
“teamB”:”ECUADOR”
},
{
“matchId”:”27″,
“teamA”:”ARGENTINA”,
“teamB”:”IRAN”
},
{
“matchId”:”28″,
“teamA”:”GERMANY”,
“teamB”:”GHANA”
},
{
“matchId”:”29″,
“teamA”:”NIGERIA”,
“teamB”:”BOSNIA”
},
{
“matchId”:”30″,
“teamA”:”BELGIUM”,
“teamB”:”RUSSIA”
},
{
“matchId”:”31″,
“teamA”:”SOUTH KOREA”,
“teamB”:”ALGERIA”
},
{
“matchId”:”32″,
“teamA”:”USA”,
“teamB”:”PORTUGAL”
}
]
}
This confirms that the data has been assigned to the URL. Now is the time to Parse the data in JSON format. To do this, we will show you the way by creating an android application.
Step 01: Start “Eclipse” and start a new project.
Step 02: Make default activity name and layout file as MainActivity.java and activity_main.xml, respectively.
Step 02-a: Extend the MainActivity.java to add ListActivity.
Step 02-b: Add the URL.
Step 02-c: Use the required tag to Parse the data.
Step 02-d: Store the information using JSONArray and ArrayList.
Step 02-e: To communicate with the server, create the asynctask class.
Step 02-e-i: Introduce protected void using onPreEsecute().
Step 02-e-ii: Call the makeServicecall function using ServiceHandler and receive it in string(json).
Step 02-e-iii: Store the array fixture in JSON Array using the following code.
Step 02-e-iv: Parse the match, Team A, and Team B data. Using a hashmap for each node and following code, add the child nodes to the matchfixture ArrayList.
Step 02-e-v: After creating a SimpleAdapter, use it as a ListAdapter.
Step 02-e-vi: Finally, use the GetFixture command to fetch the data.
Step 03: Create and save a new class after naming it Servicehandler.java. Also, make sure to save it in the src folder.
Step 04: Since the data will be fetched over the internet, make a few changes to the AndroidManifest.xml.
Step 05: Save a new XML file in res > layout folder named list_item.xml.
If you follow the steps correctly, you will have the perfect code that lets you interchange the JSON data from external data servers.
For those who want the source code, here it is:
package com.example.testjsonparsing;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class MainActivity extends ListActivity {
private String URL_ITEMS = “http://10.0.2.2/tech/getFixture.php”;
private static final String TAG_FIXTURE = “fixture”;
private static final String TAG_MATCHID = “matchId”;
private static final String TAG_TEAMA = “teamA”;
private static final String TAG_TEAMB = “teamB”;
JSONArray matchFixture = null;
ArrayList<HashMap<String, String>> matchFixtureList = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call Async task to get the match fixture
new GetFixture().execute();
}
private class GetFixture extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void… arg) {
ServiceHandler serviceClient = new ServiceHandler();
Log.d(“url: “, “> ” + URL_ITEMS);
String json = serviceClient.makeServiceCall(URL_ITEMS,ServiceHandler.GET);
Log.d(“Get match fixture response: “, “> ” + json);
if (json != null) {
try {
Log.d(“try”, “in the try”);
JSONObject jsonObj = new JSONObject(json);
Log.d(“jsonObject”, “new json Object”);
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d(“json aray”, “user point array”);
int len = matchFixture.length();
Log.d(“len”, “get array length”);
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_MATCHID);
Log.d(“matchId”, matchId);
String teamA = c.getString(TAG_TEAMA);
Log.d(“teamA”, teamA);
String teamB = c.getString(TAG_TEAMB);
Log.d(“teamB”, teamB);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_MATCHID, matchId);
matchFixture.put(TAG_TEAMA, teamA);
matchFixture.put(TAG_TEAMB, teamB);
matchFixtureList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d(“catch”, “in the catch”);
e.printStackTrace();
}
} else {
Log.e(“JSON Data”, “Didn’t receive any data from server!”);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, matchFixtureList,
R.layout.list_item, new String[] {
TAG_MATCHID, TAG_TEAMA,TAG_TEAMB
}
, new int[] {
R.id.matchId,R.id.teamA,
R.id.teamB
}
);
setListAdapter(adapter);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Once you are sure that the code is flawless, execute it. If there are no issues, you will get an output similar to this.
Dynamic TableView
If you are looking for a solution to fetch JSON data dynamically, you can not use the earlier example. For Dynamic TableView, you will have to make use of TableLayout.
Follow these steps:
Step 01: First, ready the MainActivity.java file similar to the following code.
package table_demo.coderzheaven.com.tabledemo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String companies[] = {“Google”, “Windows”, “iPhone”, “Nokia”, “Samsung”,
“Google”, “Windows”, “iPhone”, “Nokia”, “Samsung”,
“Google”, “Windows”, “iPhone”, “Nokia”, “Samsung”};
String os[] = {“Android”, “Mango”, “iOS”, “Symbian”, “Bada”,
“Android”, “Mango”, “iOS”, “Symbian”, “Bada”,
“Android”, “Mango”, “iOS”, “Symbian”, “Bada”};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addHeaders();
addData();
}
private TextView getTextView(int id, String title, int color, int typeface, int bgColor) {
TextView tv = new TextView(this);
tv.setId(id);
tv.setText(title.toUpperCase());
tv.setTextColor(color);
tv.setPadding(40, 40, 40, 40);
tv.setTypeface(Typeface.DEFAULT, typeface);
tv.setBackgroundColor(bgColor);
tv.setLayoutParams(getLayoutParams());
tv.setOnClickListener(this);
return tv;
}
@NonNull
private LayoutParams getLayoutParams() {
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(2, 0, 0, 2);
return params;
}
@NonNull
private TableLayout.LayoutParams getTblLayoutParams() {
return new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
}
public void addHeaders() {
TableLayout tl = findViewById(R.id.table);
TableRow tr = new TableRow(this);
tr.setLayoutParams(getLayoutParams());
tr.addView(getTextView(0, “COMPANY”, Color.WHITE, Typeface.BOLD, Color.BLUE));
tr.addView(getTextView(0, “OS”, Color.WHITE, Typeface.BOLD, Color.BLUE));
tl.addView(tr, getTblLayoutParams());
}
public void addData() {
int numCompanies = companies.length;
TableLayout tl = findViewById(R.id.table);
for (int i = 0; i < numCompanies; i++) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(getLayoutParams());
tr.addView(getTextView(i + 1, companies[i], Color.WHITE, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent)));
tr.addView(getTextView(i + numCompanies, os[i], Color.WHITE, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent)));
tl.addView(tr, getTblLayoutParams());
}
}
@Override
public void onClick(View v) {
int id = v.getId();
TextView tv = findViewById(id);
if (null != tv) {
Log.i(“onClick”, “Clicked on row :: ” + id);
Toast.makeText(this, “Clicked on row :: ” + id + “, Text :: ” + tv.getText(), Toast.LENGTH_SHORT).show();
}
}
}
Step 02: For the activity_main.xml file, you will have to use layout. So, try something similar to this code.
Step 03: Once you execute the code, you will get the perfect Dynamic TableView for your application.
Frequently Asked Questions (FAQs)
What is JSON?
Similar to XML, JSON is a file format. But this format is specifically used only to interchange data from external servers and APIs. It stands for JavaScript Object Notation.
Though it is not as multitasking as XML, it is better than XML for data interchange. JSON is the perfect minimal and readable format for any structured data.
Is JSON better than XML for data interchange?
Between XML and JSON, the latter is more popular for data interchange. It uses human-readable text to complete its task of data fetching.
Unlike XML, parsing JSON is much easier and swifter. Not only that, but it is also lighter than using a static loop to fetch the data from the database.
What applications can JSON files be viewed on?
Multiple applications and tools can be used to read a JSON file.
For Windows users, the most common ones are Notepad, Notepad ++ Mozilla Firefox, and WordPad. If you are a Linux user, you can use Mozilla Firefox, Google Chrome, Pico, and Vim. And for the Mac users, the tools are MacVim, Mozilla Firefox, and Apple TextEdit.
Where can I get JSON data from for an Android App?
JSON can be used to fetch or get data from verities of sources. To bring data from a URL, you will have to use fetch(URL) function while parsing the JSON file. For getting data from a path, you will have to use fetch(‘/api/path’).
You will have to use response.json() to get the data back no matter what you fetch from.
Can JSON data be used dynamically?
Using JSON dynamically means using JSON to store arrays as a JSON object. So to use the fetched JSON data dynamically, you will have to bring the data and store it under the class JSONObject.
Here is an example:
You may also be interested to know:
How to see when someone is typing android
how to unmute text messages on android
how to turn off message blocking on android
how to get sms messages on android
Final Words
XML has ruled the Android Development world for a long time. But it is still far inferior then JSON when it comes to data interchanging. But android json example- how to show json data in tableview in android?
Parsing Json is more straightforward than XML, so you will need to just add a few commands to your code. And once you do it flawlessly, you will have an Android Application that can fetch and show data in table view. So, know your options and code smart!