Reputation: 185
I am trying to fetch data from MySQL table and show it to the Android table.
For table design I am using the following dependencies.
de.codecrafters.tableview:tableview:2.8.0
My JsonArray
{
"result": [
{
"sl": "36",
"user_id": "575512",
"email": "[email protected]",
"password": "123",
"name": "Moderator",
"gender": "Male",
"phone": "1223345",
"lvl": "Moderator",
"stat": "1"
},
{
"sl": "68",
"user_id": "814769",
"email": "[email protected]",
"password": "1WCcvnhp",
"name": "Test Moderator",
"gender": "Male",
"phone": "7412589630",
"lvl": "Moderator",
"stat": "1"
},
{
"sl": "69",
"user_id": "742136",
"email": "[email protected]",
"password": "YG5*3Kj9",
"name": "Mod3",
"gender": "Male",
"phone": "1423687450",
"lvl": "Moderator",
"stat": "1"
}
]
}
Till now my code:
JSONArray result = response.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jsonObject = result.getJSONObject(i);
String name = jsonObject.getString("name");
String phone = jsonObject.getString("phone");
String email = jsonObject.getString("email");
modUpdateAdapter.setName(name);
modUpdateAdapter.setPhone(phone);
modUpdateAdapter.setEmail(email);
arrayList.add(modUpdateAdapter);
}
showData();
And the showData
function is
public void showData(){
data = new String[arrayList.size()][10];
for (int j = 0; j < arrayList.size(); j++) {
modUpdateAdapter = arrayList.get(j);
data[j][0] = modUpdateAdapter.getName();
data[j][1] = modUpdateAdapter.getEmail();
data[j][2] = modUpdateAdapter.getPhone();
}
tableView.setDataAdapter(new SimpleTableDataAdapter(getActivity(), data));
}
Problem is that only the last value is shown 3 times, even if I call the showData()
inside the for loop. I want to show all 3 objects from the array, not a single object 3 times. Please help me.
Upvotes: 0
Views: 49
Reputation: 24211
You have a problem while you are parsing the data from the JSON and putting the data into an ArrayList
of modUpdateAdapter
. You are not creating a new instance of ModUpdateAdapter
each time you are setting the name, email and phone. So each time you are parsing a data and saving it in the same modUpdateAdapter
class. So the function needs to modified like the following.
JSONArray result = response.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jsonObject = result.getJSONObject(i);
String name = jsonObject.getString("name");
String phone = jsonObject.getString("phone");
String email = jsonObject.getString("email");
// Each time create a new instance and then save the value.
ModUpdateAdapter modUpdateAdapter = new ModUpdateAdapter();
modUpdateAdapter.setName(name);
modUpdateAdapter.setPhone(phone);
modUpdateAdapter.setEmail(email);
arrayList.add(modUpdateAdapter);
}
Upvotes: 2