Set value inside table from database using array - android

I am trying to fetch data from MySQL database and trying to show it into a table. For this I am using volley.
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");
String j = String.valueOf(i);
data = new String[][]{{j, name, email, phone}};
tableView.setDataAdapter(new SimpleTableDataAdapter(getActivity(), data));
}
My json array
{
"result": [
{
"sl": "36",
"user_id": "575512",
"email": "m#gmail.com",
"password": "123",
"name": "Moderator",
"gender": "Male",
"phone": "1223345",
"lvl": "Moderator",
"stat": "1"
},
{
"sl": "68",
"user_id": "814769",
"email": "m2#gmail.com",
"password": "1WCcvnhp",
"name": "Test Moderator",
"gender": "Male",
"phone": "7412589630",
"lvl": "Moderator",
"stat": "1"
}
]
}
The problem is I am getting only the last value from jsonArray, because the String array is resetting itself.
data = new String[][]{{j, name, email, phone}};
I want to get all the values available in the jsonArray.
I am using the following dependencies for table
de.codecrafters.tableview:tableview:2.8.0

Try like this
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");
String j = String.valueOf(i);
data = new String[][]{{j, name, email, phone}};
}
tableView.setDataAdapter(new SimpleTableDataAdapter(getActivity(), data));
After getting all values in array, add that array to tableview

Related

how to parse this type json array in android [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
this is array which i have
[ {
"comment": "Sir, 2nd paper qualifying hai ya Uski bhi merit banegi?",
"user": "Sameer",
"image": "https://jdcivils.org/images/co.png",
"date": "04/Sep/2016",
"reply": [
{
"comment": "Abhi qualifying nhi hai,iske marks merit list me judte hain",
"user": "Admin",
"image": "https://jdcivils.org/images/co.png",
"date": "04/Sep/2016"
}
]
},
{
"comment": "Cgpsc me hight kis kis post ke liye jaruri hoti hai..\r\nplss btayega koi??",
"user": "Vinod kumar Yadav",
"image": "https://jdcivils.org/images/co.png",
"date": "29/Aug/2016",
"reply": ""
},
{
"comment": "Sir Cgpsc Me gen. category walo Ko Psc k attempts ki koi limit Hoti Hai kya??",
"user": "Vinod kumar Yadav",
"image": "https://jdcivils.org/images/co.png",
"date": "28/Aug/2016",
"reply": [
{
"comment": "nahi",
"user": "Admin",
"image": "https://jdcivils.org/images/co.png",
"date": "28/Aug/2016"
}
]
}]
Try in this way
JSONArray jsonarray = new JSONArray(yourresponse))
for(int i=0;i<jsonarray.length;i++){
JSONObject jsonobject = jsonarray.getJsonObject(i);
String comment = jsonobject.getString("comment");
String user = jsonobject.getString("user");
String image = jsonobject.getString("image");
String date = jsonobject.getString("date");
JSONArray jsonarray1 = jsonobject.getJSONArray("reply");
for(int j=0; j<jsonarray1.length;j++){
String comment1 = jsonobject.getString("comment");
String user1 = jsonobject.getString("user");
String image1 = jsonobject.getString("image");
String date1 = jsonobject.getString("date");
}
}
I am assuming you are getting string in respose so convert it to jsonArray
JSONArray SamplejsonArray = new JSONArray(String);
for(int i = 0;i<SamplejsonArray .length();i++){
JSONObject SamplejsonObject = SamplejsonArray .getJsonObject(i);
String comment = SamplejsonObject .getString("comment");
String user = SamplejsonObject .getString("user");
String image= SamplejsonObject .getString("image");
String date= SamplejsonObject .getString("date");
JSONArray replyjsonArray = SamplejsonObject.getJSONArray(reply);
for(int j = 0;i<replyjsonArray .length();j++){
JSONObject replyjsonObject = replyjsonArray.getJsonObject(j);
String comment = replyjsonObject .getString("comment");
String user = replyjsonObject .getString("user");
String image= replyjsonObject .getString("image");
String date= replyjsonObject .getString("date");
}
}
Use json to pojo converter for create model class from complex json array
Refer link : http://www.jsonschema2pojo.org/
Use this library, all you need is create model with same key as string that you have. Gson parser
<Your model> value = new Gson().fromJson(new String(<Ur string>.getBytes("ISO-8859-1"),
"UTF-8"), <Your model>.class);
try this way
JSONArray jsonArray = new JSONArray(sampleString);
for(int i = 0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJsonObject(i)
String comment = jsonObject.getString("comment");
String user = jsonObject.getString("user");
JSONArray replyArray = jsonObject.getJSONArray("reply");
for(int j = 0;j<replyArray.length();j++){
JSONObject innerObject = replyArray.getJSONObject(j);
String comment = innerObject.getString("comment"); ...
}
}
try {
//Create array object from String object that contains your json array
JSONArray jArray = new JSONArray(jsonString);
//Get JSONObject from array
jArray.get(0);
} catch (JSONException e) {
e.printStackTrace();
}

Printing json object on an android textview

I have this json object as an output of a web service , I want to print each part_Name node on a separate android text view how to do that?
{
"0": [],
"1": {
"Part_ID": "1",
"Part_NAME": "part_name_one "
},
"2": {
"Part_ID": "2",
"Part_NAME": " part_name_two "
},
"3": {
"Part_ID": "3",
"Part_NAME": "part_name_three"
},
I tried this code but I don't get an output in my textview
jobj = jsonparser.makeHttpRequest("http://192.168.1.7:89/My_website/My_Webservice.php");
try {
JSONObject jsonRootObject = new JSONObject(jobj.toString());
JSONArray jsonArray = jsonRootObject.optJSONArray("Services_Parts");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("Part_NAME").toString();
data += "Node"+i+ "+ name +" +name+ " \n ";
tv2.setText(name);
}
if possible then try to change the structure of your json to something like that
[
{
"Part_ID": "1",
"Part_NAME": "part_name_one "
},
{
"Part_ID": "2",
"Part_NAME": " part_name_two "
},
{
"Part_ID": "3",
"Part_NAME": "part_name_three"
}
]
put each json object into an jsonarray .. as shown above
then parse each jsonobject and create the textview dynamically acc. to no. of jsonobject inside jsonarray
using the above ex. there are 3 jsonobject inside jsonarray
hence create 3 textview dynamically at the time of json parsing
JSONArray jsonArray = <your json array>;
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("Part_NAME").toString();
addTextView(name);
}
// add text to dynamically created textview code..
public void addTextView(String text)
{
final TextView textView = new TextView(this);
textView.setText(text);
myLinearLayout.addView(textView);
}

How to get inner array data

I am building an Android app and are collecting data from my remote API (using Volley)
and I need to parse the response. I know how to get the "projects" array but how can I get the title for each project (please note the project key for each project).
{
"code": 200,
"total": 4,
"projects": [
{
"project": {
"id": 1,
"title": "A nice long title",
"latitude": 56.0293783,
"longitude": 12.7256732,
"created_at": "2013-10-20T20:57:00+02:00",
"created_at_human": "5 months",
"total_tasks": 7,
"description": "This is a description.",
"address": "simple highway 22",
"zipcode": "25656",
"city": "florida"
}
},
{
"project": {
"id": 2,
"title": "A nice long title",
"latitude": 56.0293783,
"longitude": 12.7256732,
"created_at": "2013-10-20T20:57:00+02:00",
"created_at_human": "5 months",
"total_tasks": 7,
"description": "This is a description.",
"address": "simple highway 22",
"zipcode": "25656",
"city": "florida"
}
}
]
}
This is the code I use now and that needs to be modified:
JSONArray jsonPosts = mData.getJSONArray("projects");
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(i);
Log.e("OUTPUT", "THE POST: " + post);
}
This outputs:
E/OUTPUT﹕ THE POST: {"project":{"id":1,"title":"A nice long title","total_tasks":7,"address":"simple highway 22","description":"This is a description.","zipcode":"25656","created_at":"2013-10-20T20:57:00+02:00","longitude":12.7256732,"created_at_human":"5 MåNADER","latitude":56.0293783,"city":"florida"}}
How can I access the title for each?
Each jSONObject item contains a key and jSONObject. I think you need to get jSONObject from item in Array then get title and city.
I hope it will helpful for you........
JSONArray jsonPosts = mData.getJSONArray("projects");
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(i);
JSONObject innerjson = post.getJSONObject("project");
String title = innerjson.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
String city = innerjson.getString(KEY_CITY);
city = Html.fromHtml(city).toString();
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_CITY, city);
blogPosts.add(blogPost);
}
String[] keys = {KEY_TITLE, KEY_CITY};
int[] ids = { R.id.top_label, R.id.bottom_label};
SimpleAdapter adapter = new SimpleAdapter(this, blogPosts, R.layout.list_item, keys, ids);
setListAdapter(adapter);
This is a JSONArray and not a JSONObject - to make a JSONObject from it, use
JSONObject jsonObject = jsonArray.getJSONObject(0);
this gets the first JSONObject from this JSONArray.
If you have multiple JSONObjects, use this:
JSONObject jsonObject;
for(int n = 0; n < jsonArray.length(); n++)
{
jsonObject = jsonArray.getJSONObject(n);
}
To get the values:
jsonObject.getString("name");

Android parsing JSON with array in array

Help me parsing JSON. I parse this JSON without "moment" and don't know how parse with "moment".
My JSON response:
{
"A": [
{
"time0_90": "20",
"score": "0 : 0",
"team1": "Россия",
"team2": "Франция",
"group": "A",
"live": "1"
},
{
"time0_90": "20",
"score": "0 : 0",
"team1": "Португалия",
"team2": "Гондурас",
"group": "A",
"live": "0",
"time": "18:30",
"stadium": "",
"referee": "судья"
}
],
"B": [
{
"time0_90": "3",
"score": "1 : 0",
"moment": [
{
"class_moment": "g",
"name1": "Халк",
"time0_90Moment": "5",
"team": "1"
},
{
"class_moment": "sub",
"name1": "Фред",
"time0_90Moment": "50",
"team": "1",
"name2": "Жо"
}
],
"team1": "Бразилия",
"team2": "Испания",
"group": "B",
"live": "1"
}
],
"C": [],
"D": [],
"E": [],
"F": [
{
"time": "15:00",
"stadium": "Маракана",
"referee": "судья",
"team1": "Россия",
"team2": "Франция",
"group": "F",
"live": "0"
}
],
"G": [],
"H": []
}
This code is parse response without "moment". How to parse response with "moment" and save it in array?
JSONObject jsonResponse = new JSONObject(jsonResult);
for (int j=0; j<8; j++){
String[] groupName = {"A", "B", "C", "D", "E", "F", "G", "H"};
JSONArray jsonMainNode = jsonResponse.optJSONArray(groupName[j]);
if (jsonMainNode.length() == 0){ continue;}
else {
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
team1 = jsonChildNode.optString("team1");
team2 = jsonChildNode.optString("team2");
group = jsonChildNode.optString("group");
int live = jsonChildNode.getInt("live");
String time = null;
if (live == 1){
time = jsonChildNode.optString("time0_90")+"'";
score = jsonChildNode.optString("score");
}
else {
score = jsonChildNode.optString("time");
referee = jsonChildNode.optString("referee");
time = jsonChildNode.optString("stadium");
}
try this :
jsonArray moment = json.getJsonArray("B").getJsonObject(0).getJsonArray("moment");
String class = moment.getString("class_moment");
String name= moment.getString("name1");
String time= moment.getString("time0_90Moment");
String team= moment.getString("team");
I would recommend that you use a JSON Mapping library, like Jackson or GSON, manually parsing JSON is a waste of time and effort unless it is purely for educational purposes.
Other than that I assume the correct usage would be .optJSONArray("moment") follow by an iteration with a cast of each result to JSONObject or similar? Manually doing this is just a mess. ;o
I did it, here's the code
JSONObject jsonResponse = new JSONObject(jsonResult);
for (int j=0; j<8; j++){
String[] groupName = {"A", "B", "C", "D", "E", "F", "G", "H"};
JSONArray jsonMainNode = jsonResponse.optJSONArray(groupName[j]);
if (jsonMainNode.length() == 0){ continue;}
else {
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
team1 = jsonChildNode.optString("team1");
team2 = jsonChildNode.optString("team2");
group = jsonChildNode.optString("group");
int live = jsonChildNode.getInt("live");
String time = null;
if (live == 1){
time = jsonChildNode.optString("time0_90")+"'";
score = jsonChildNode.optString("score");
JSONArray jsonMoment = jsonChildNode.optJSONArray("moment");
if (jsonMoment == null)
{
class_moment=new String[1];
name1 = new String[1];
name2 = new String[1];
name1 = new String[1];
time0_90Moment = new String[1];
team = new int[1];
}
else {
class_moment=new String[jsonMoment.length()];
name1 = new String[jsonMoment.length()];
name2 = new String[jsonMoment.length()];
name1 = new String[jsonMoment.length()];
time0_90Moment = new String[jsonMoment.length()];
team = new int[jsonMoment.length()];
for (int k = 0; k < jsonMoment.length(); k++) {
JSONObject jsonChildMoment = jsonMoment.getJSONObject(k);
class_moment[k] = jsonChildMoment.optString("class_moment");
name1[k] = jsonChildMoment.optString("name1");
name2[k] = jsonChildMoment.optString("name2");
time0_90Moment[k] = jsonChildMoment.optString("time0_90Moment");
team[k] = jsonChildMoment.getInt("team");
}}
}
else {
score = jsonChildNode.optString("time");
referee = jsonChildNode.optString("referee");
time = jsonChildNode.optString("stadium");
}

Get json array keys in android

{
"204": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/02\/0\/0\/A\/Content\/",
"timestamp": 1385909880,
"cover": ["17\/Pg017.png",
"18\/Pg018.png",
"1\/Pg001.png",
"2\/Pg002.png"],
"year": "2013",
"month": "12",
"day": "02",
"issue": "2013-12-02",
"id": "204"
},
"203": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/01\/0\/0\/A\/Content\/",
"timestamp": 1385806902,
"cover": ["1\/Pg001.png",
"2\/Pg002.png",
"3\/Pg003.png",
"4\/Pg004.png"],
"year": "2013",
"month": "12",
"day": "01",
"issue": "2013-12-01",
"id": "203"
},
"202": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/11\/30\/0\/0\/A\/Content\/",
"timestamp": 1385720451,
"cover": ["1\/Pg001.png",
"2\/Pg002.png",
"3\/Pg003.png",
"4\/Pg004.png"],
"year": "2013",
"month": "11",
"day": "30",
"issue": "2013-11-30",
"id": "202"
}
}
The above sample json array , how to get the 204, 203 and 202? Thanks
I tried:
JSONArray issueArray = new JSONArray(jsonContent);
for (int j = 0; j < issueArray.length(); j++) {
JSONObject issue = issueArray.getJSONObject(j);
String _pubKey = issue.getString(0);
}
above sample json array , how to get the 204, 203 and 202?
No, current String is JSONObject instead of JSONArray. you should get Iterator using JSONObject. keys () if inner JSONObject keys dynamic as:
JSONObject issueObj = new JSONObject(jsonContent);
Iterator iterator = issueObj.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
JSONObject issue = issueObj.getJSONObject(key);
// get id from issue
String _pubKey = issue.optString("id");
}
Answer given by Mr. K is also right but you can also use jsonObject names() method. please find the sample code
for(int i = 0; i<jsonobject.length(); i++){
Log.e(TAG, "Key = " + jsonobject.names().getString(i) + " value = " + jsonobject.get(jsonobject.names().getString(i)));
}
I hope dis will help you
User this method to iterate json dynamically
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("" + key + " : " + data.optString(key));
}
} catch (Throwable e) {
System.out.println("" + key + " : " + data.optString(key));
e.printStackTrace();
}
}
}
}
You can also use names() as below to get the keys as JSONArray :
JSONArray jArray = jsonObject.names();
int len = jsonObject.length();
for (int i=0; i<len; i++) {
String keyName = (String)jArray.get(i);
JSONObject jValue = jsonObject.getJSONObject(keyName);
String _pubKey = jValue.optString("id");
//get the other values from jValue
}
Here you are trying to get JSONArray but in json response it is JSONObject.
Use following code.
JSONObject issueObject = new JSONObject(jsonContent);
String _pubKey = issueObject.getString(0);

Categories

Resources