How to update dynamic editext values into nested json array in android? - android

This is my json data I have created ui design using this json string but by the time of updating I am confused about this how to correctly get EditText values and how to update
{
"SingleExtras": [{
"Id": 1,
"name": "size",
"isEnabled": 1,
"values": [{
"extraId": 30,
"objId": "Gb39Rpmdl9",
"extraName": "Small",
"extraPrice": 15,
"currency": "Aed",
"isEnabled": 1
},
{
"extraId": 30,
"objId": "kknwBtS9zJ",
"extraName": "Medium",
"extraPrice": 18,
"currency": "Aed",
"isEnabled": 0
},
{
"extraId": 30,
"objId": "d5YfEGAgMt",
"extraName": "Large",
"extraPrice": 20,
"currency": "Aed",
"isEnabled": 1
}
]
},
{
"Id": 5,
"name": "Milk",
"isEnabled": 1,
"values": [{
"extraId": 30,
"objId": "8obBCWDXbh",
"extraName": "LowFatMilk",
"extraPrice": 0,
"currency": "Aed",
"isEnabled": 1
},
{
"extraId": 31,
"objId": "CC629INXuP",
"extraName": "FullFatMilk",
"extraPrice": 0,
"currency": "Aed",
"isEnabled": 1
}
]
}
],
"Extras": [{
"extraId": 5,
"objId": "PxDQX3LGU2",
"extraName": "ExtraShot",
"extraPrice": 5,
"currency": "Aed",
"isEnabled": 1
}]
}
I'm using the code below to get the modified EditText values in that
for(int i=0; i < allEds.size(); i++){
pricelist.add(allEds.get(i).getText().toString().trim());
priceidslist.add(allEds.get(i).getId());
}
This is nested array function here in loop I'm getting array index{0,1,2,0,1,2,0} like this i have all editetxt prices list by using im not able to update index position values mismatching
public void jsonarray(JSONArray arry){
try {
for (int j = 0; j < arry.length(); j++) {
JSONObject rw = arry.getJSONObject(j);
String extraId = rw.optString("extraId");
String objId = rw.optString("objId");
String extraName = rw.optString("extraName");
String extraPrice = rw.optString("extraPrice");
String currenc = rw.optString("currency");
String chksts = rw.optString("isEnabled");
if (namechklist.contains(extraName)) {
rw.put("isEnabled", "1");
}
if (nameunchklist.contains(extraName)) {
rw.put("isEnabled", "0");
}
if(allnames.contains(extraName)){
rw.put("extraPrice", pricelist.get(j));
}
Log.d("res", "jsonarray:loop "+arry.toString());
}
Log.d("res", "jsonarray: "+arry.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Anyone please suggest me which way is better to achieve this logic correctly

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject row = jsonArray.getJSONObject(i);
String itemid = row.optString("id");
JSONArray arry = row.getJSONArray("values");
if(i == 0){
}
else{
final int ar = arry.length();
final int tot = g + ar ;
int h = 0;
for (int j = g ; j < tot; j++) {
JSONObject rw = arry.getJSONObject(h);
String extraName = rw.optString("extraName");
String extraId = rw.optString("extraId");
if(namechklist.size() > 0){
if(namechklist.contains(extraName)){
rw.put("isEnabled","1");
}
}
if(nameunchklist.size()>0){
if(nameunchklist.contains(extraName)){
rw.put("isEnabled","0");
}
}
if(j >= arry.length()){
}else{
String gh = String.valueOf(priceidslist.get(j));
if(gh.equals(extraId)){
rw.put("extraPrice",pricelist.get(j));
}
}
h++;
}
g = arry.length();
}
}
Log.d("chk", "res:last "+jsonArray.toString());
}
JSONArray extraArray = obj.getJSONArray("Extras");
for (int i = 0; i < extraArray.length(); i++) {
JSONObject rw = extraArray.getJSONObject(i);
String extraName = rw.optString("extraName");
String extraId = rw.optString("extraId");
if(exnamechklist.size() > 0){
if(exnamechklist.contains(extraName)){
rw.put("isEnabled","1");
}
}
if(exnameunchklist.size()>0){
if(exnameunchklist.contains(extraName)){
rw.put("isEnabled","0");
}
}
}
I just changed for loop condition and changed format of getting json values now its working fine

Related

How Get configurationVal of Packing_charge in below JSON?

This is the url I used to fetch
private static String url = "http://52.206.14.188:8080/Configuration";
But I can't able to get the Packing charge value someone help me to write code to parse I am beginner to android
[
{
"configurationId": 1,
"configurationName": "CGST",
"configurationVal": "2.5"
},
{
"configurationId": 2,
"configurationName": "SGST",
"configurationVal": "2.5"
},
{
"configurationId": 3,
"configurationName": "DELIVERY_CHARGE",
"configurationVal": "0"
},
{
"configurationId": 4,
"configurationName": "Admin_Mobile",
"configurationVal": "9500100042,8939404592"
},
{
"configurationId": 5,
"configurationName": "MIN_ORDER_AMOUNT",
"configurationVal": "98"
},
{
"configurationId": 6,
"configurationName": "Packing_charge",
"configurationVal": "3"
}
]
Try this
String myjsonstring = "http://52.206.14.188:8080/Configuration";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
JSONArray jsonArray = new JSONArray(myjsonstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentobject = jsonArray.getJSONObject(i);
String configurationId = currentobject.getString("configurationId");
String configurationName = currentobject.getString("configurationName");
String configurationVal = currentobject.getString("configurationVal");
Log.i("configurationId", ":" + configurationId);
Log.i("configurationName", ":" + configurationName);
Log.i("configurationVal", ":" + configurationVal);
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(configurationId);
tv.setText(configurationName);
tv.setText(configurationVal);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}

Associate Ids and names from a json with the itemonclicklistener?

How do I associate the ids and names from a JSON file with the position parameter in onitemclicklistener in Android Studio?
I have a JSON data file containing ids and names and I want to retrieve them into a listview onTextChangedQuery in autocomplete search. I have done that but now I can't relate it to their respective position in OnItemClickListener.
This is the JSON file
"data": [
{
"id": "26",
"fullname": "Abbas",
"address": "mingora"
},
{
"id": "28",
"fullname": "shakeel",
"address": "mingora"
},
{
"id": "29",
"fullname": "Fayaz",
"address": "Odigram"
},
{
"id": "30",
"fullname": "Fayaz",
"address": "Odigram"
},
{
"id": "31",
"fullname": "m fayaz",
"address": "odigram"
}
]
The following is the code:
public void onResponse(String response) {
try {
JSONObject Jobject = new JSONObject(response);
JSONArray DATA = Jobject.getJSONArray("data");
for (int i = 0; i < DATA.length(); i++) {
jsonObject = DATA.getJSONObject(i);
id = jsonObject.getString("id");
name = jsonObject.getString("fullname");
// getting id from json
String newId = id;
int currentid = myids.length;
int newSize1 = currentid + 1;
String[] ArrayId = new String[newSize1];
for (int k = 0; k < currentid; k++) {
ArrayId[k] = myids[k];
}
ArrayId[newSize1 - 1] = newId;
myids = ArrayId;
//the following code adds new item to the array from the json object
String newItem = name;
int currentSize = contactList.length;
int newSize = currentSize + 1;
String[] tempArray = new String[newSize];
for (int j = 0; j < currentSize; j++) {
tempArray[j] = contactList[j];
}
tempArray[newSize - 1] = newItem;
contactList = tempArray;
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(BloodDonerActivity.this, R.layout.list_item, R.id.textView, contactList);
lv.setAdapter(arrayAdapter);
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
String userId = myids[pos];
Toast.makeText(getApplicationContext(), userId, Toast.LENGTH_SHORT).show();
//id of user on position
}
});

How to get Json key and value with iterator in andorid

How to get this Json key and value from the web. This is my code, but I can't get this from the second iteration. can some one help me to do this.
Json Response :
"attributes": [
{
"main_id": "3",
"Color": [
{
"id": "60",
"text": "46( +$0.00)"
}
]
},
{
"main_id": "21",
"dede": [
{
"id": "73",
"text": "baba( +$0.00)"
}
]
}
]
This is my android code to parse the values :
JSONArray jsonArrayAttributes = jsonObj.getJSONArray("attributes");
for (int i = 0; i < jsonArrayAttributes.length(); i++) {
JSONObject jsonObject1 = jsonArrayAttributes.getJSONObject(i);
Iterator iteratorKey = jsonObject1.keys();
String strAttrId = (String) iteratorKey.next();
String strAttrName = (String) iteratorKey.next();
JSONArray jsonArrayName = jsonObject1.getJSONArray(strAttrName);
for (int j = 0; j < jsonArrayName.length(); j++) {
JSONObject jsonObjName = jsonArrayName.getJSONObject(j);
}
}
You have to change your code little bit like
JSONArray jsonArrayAttributes = jsonObj.getJSONArray("attributes");
for (int i = 0; i < jsonArrayAttributes.length(); i++) {
JSONObject jsonObject1 = jsonArrayAttributes.getJSONObject(i);
Iterator it = jsonObject1.keys();
boolean arrFlag = false;
while (it.hasNext()) {
String key = (String) it.next();
if (!arrFlag) {
String value = jsonObject1.getString(key);
Log.i("Key:Value", "" + key + ":" + value);
arrFlag = true;
} else {
JSONArray value = jsonObject1.getJSONArray(key);
Log.i("Key:Value", "" + key + ":" + value);
arrFlag = false;
}
}
}
It working perfectly.
You will get all keys and value over here.

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