How to get JSON data with two arrays in android - android

I want to get one array from PHP that one of the fileds is an array.
How can get basket's data with jsonArray and jsonObject ?
(In the code below, the basket is an array that contains 5 parameters).
It's my array:
[{"orderCode":11514,"orderDate":"2017/05/21","orderPrice":"1‌​9200","fullName":"Ja‌​ck","address":"addr 1","cellphone":"09151515730","basket":[{"b_qty":"4","pid":"8‌​","b_price":"9500","‌​b_discount":"10","ti‌​tle":"obj1"}]
Edit
String b_price ="";
String b_discount="";
String b_qty ="";
String ti‌​tle= "";
String pid="";
try
{
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String orderCode = object.getString("orderCode");
String orderDate = object.getString("orderDate");
String orderPrice = object.getString("orderPrice");
String fullName = object.getString("fullName");
String address = object.getString("address");
String cellphone = object.getString("cellphone");
JSONArray orderBasket = object.getJSONArray("basket");
for (int j = 0; j < orderBasket.length(); j++){
JSONObject object1 = orderBasket.getJSONObject(j);
b_qty = object1.getString("b_qty");
pid = object1.getString("pid");
b_price = object1.getString("b_price");
b_discount = object1.getString("b_discount");
ti‌​tle = object1.getString("ti‌​tle");
}
CustomOrderList customOrderList = new CustomOrderList(getApplicationContext());
customOrderList.orderCode.setText(orderCode);
customOrderList.orderDate.setText(orderDate);
customOrderList.orderTotalPrice.setText(orderPrice);
customOrderList.orderFullName.setText(fullName);
customOrderList.orderAddress.setText(address);
customOrderList.orderCellphone.setText(cellphone);
customOrderList.basketPrice.setText(b_price);
customOrderList.basketDiscount.setText(b_discount);
customOrderList.basketTitle.setText(ti‌​tle);
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearOrders.addView(customOrderList);
}
} catch (JSONException e) {
e.printStackTrace();
}

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String orderCode = object.getString("orderCode");
String orderDate = object.getString("orderDate");
String orderPrice = object.getString("orderPrice");
String fullName = object.getString("fullName");
String address = object.getString("address");
String cellphone = object.getString("cellphone");
//Now orderBasket is jsonArray
JSONArray orderBasket = object.getJSONArray("basket");
// So fetch all objects from orderBasket array
for (int j = 0; j < orderBasket.length(); j++){
JSONObject objectbsk = orderBasket.getJSONObject(j);
String b_qty = objectbsk.getString("b_qty");
String pid = objectbsk.getString("pid");
String b_price = objectbsk.getString("b_price");
String b_discount = objectbsk.getString("b_discount");
String ti‌​tle = objectbsk.getString("ti‌​tle");
// Create a orderBasket list for Basket with these keys also as you have created for CustomOrderList and use it
}
CustomOrderList customOrderList = new CustomOrderList(getApplicationContext());
customOrderList.orderCode.setText(orderCode);
customOrderList.orderDate.setText(orderDate);
customOrderList.orderTotalPrice.setText(orderPrice);
customOrderList.orderFullName.setText(fullName);
customOrderList.orderAddress.setText(address);
customOrderList.orderCellphone.setText(cellphone);
customOrderList.orderBasket.setText(orderBasket);
// here you can't do set text since it's jsonarray. So use basketlist to show the data`
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearOrders.addView(customOrderList);
}

Related

how to display dynamic text of submodule in below modules using volley?

I want to display dynamic text at the bottom of modules as shown in the following image
I have tried this
for (int i =0;i<dataArray.length();i++) {
Log.v("Response***",""+dataArray);
try {
JSONObject jsonObject = dataArray.getJSONObject(i);
JSONObject moduleobj = jsonObject.getJSONObject("module");
String ICONOBJ = moduleobj.getString("fa_icon");
Log.e("moduleobj***",""+ICONOBJ);
JSONArray submoduleArray = jsonObject.getJSONArray("subModule");
for (int x = 0; x<submoduleArray.length();x++) {
JSONObject submoduleobj = submoduleArray.getJSONObject(x);
CryptoHandler cryptoHandler = new CryptoHandler();
String sub_name = submoduleobj.getString("sub_name");
String decryptsubname = cryptoHandler.decrypt(sub_name);
Log.e("submodulearray***",""+submoduleArray);
Log.i("submoduleobj***",""+submoduleobj);
Log.e("submodule_name***",""+decryptsubname);
Dashborad_Model dashborad_model = new Dashborad_Model();
dashborad_model.setSubName(decryptsubname);
}
String stringName = moduleobj.getString("module_name");
CryptoHandler cryptoHandler = new CryptoHandler();
String decryptmodulename = cryptoHandler.decrypt(stringName);
Log.v("ResponseOBJ***",""+decryptmodulename);
Dashborad_Model dashborad_model = new Dashborad_Model();
dashborad_model.setModuleName(decryptmodulename);
dashborad_model.setFaIcon(ICONOBJ);
dashboradModels.add(dashborad_model);
I am not able to set subName(Submodule).

how can i store muliple rows in JsonArray?

The problem is that in first row data save normally but in second row or move on data redundant Like:
public void Save(){
String register;
JSONObject jsonObj;
JSONObject json;
JSONArray jsonTempArray = new JSONArray();
JSONObject jsonObject=new JSONObject();
JSONArray jsonArray=new JSONArray();
try{
JSONObject jsonObjs=new JSONObject();
jsonObj=new JSONObject();
json=new JSONObject();
Integer.valueOf(mGeneralID);
str_UpdatedGeneralID= "6832";
String str_FMeasurementSamplesize = "";
if (txtFMeasurementSamplesize.getText().toString().equals("")){
str_FMeasurementSamplesize = "0";
}else {
str_FMeasurementSamplesize = txtFMeasurementSamplesize.getText().toString();
}
String Samplesize = txt_Sample_Size.getText().toString();
String Qtypersize = txt_Qty_per_Size.getText().toString();
String TotalnoofmeasPointsizeA = txtTotalnoOfmeasPointsizeA.getText().toString();
String TotalnoofmeasPointsizeAA = txtTotalnoOfmeasPointsizeAA.getText().toString();
String TotalnoofmeasPointsizeB = txtTotalnoOfmeasPointsizeB.getText().toString();
String TotalnoofmeasPointsizeBB = txtTotalnoOfmeasPointsizeBB.getText().toString();
String NomeasurementptoutoftolA = txtNomeasurementptoutoftolA.getText().toString();
String NomeasurementptoutoftolB = txtNomeasurementptoutoftolB.getText().toString();
String PASS = txt_pass.getText().toString();
String Fail = txt_fail.getText().toString();
String Pending = txt_pending.getText().toString();
String Remarks = txt_Remarks_F.getText().toString();
DateFormat df = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
String CreationDate = df.format(Calendar.getInstance().getTime());
int a =0;
for (int i=0; i < MeasurementArrayList.size(); i++){
String MeasurementSheetDetailID = MeasurementArrayList.get(i).getmeasurementSheetDetailID();
String MeasurementPointID = MeasurementArrayList.get(i).getmeasurementPointID();
String MeasurementPoints = MeasurementArrayList.get(i).getmeasurementPoints();
String SpecSizeA = MeasurementArrayList.get(i).getSpecSizeA();
String SpecSizeAOne = MeasurementArrayList.get(i).getSpecSizeAOne();
String SpecSizeATwo = MeasurementArrayList.get(i).getSpecSizeATwo();
String SpecSizeAThree = MeasurementArrayList.get(i).getSpecSizeAThree();
String SpecSizeAFour = MeasurementArrayList.get(i).getSpecSizeAFour();
String SpecSizeAFive = MeasurementArrayList.get(i).getSpecSizeAFive();
String SpecSizeB = MeasurementArrayList.get(i).getSpecSizeB();
String SpecSizeBOne = MeasurementArrayList.get(i).getSpecSizeBOne();
String SpecSizeBTwo = MeasurementArrayList.get(i).getSpecSizeBTwo();
String SpecSizeBThree = MeasurementArrayList.get(i).getSpecSizeBThree();
String SpecSizeBFour = MeasurementArrayList.get(i).getSpecSizeBFour();
String SpecSizeBFive = MeasurementArrayList.get(i).getSpecSizeBFive();
String Tolerance = MeasurementArrayList.get(i).gettolerance();
jsonObj.put("MeasurementSheetID", str_FMeasurementSamplesize);
jsonObj.put("GeneralID", str_UpdatedGeneralID);
jsonObj.put("Samplesize", Samplesize);
jsonObj.put("Measurement", str_sp_Measurement);
jsonObj.put("Qtypersize", Qtypersize);
jsonObj.put("Color", str_sp_Color);
jsonObj.put("SpecSizeA", str_sp_SpecSizeA);
jsonObj.put("SpecSizeB", str_sp_SpecSizeB);
jsonObj.put("TotalnoofmeasPointsizeA",TotalnoofmeasPointsizeA);
jsonObj.put("TotalnoofmeasPointsizeAA", TotalnoofmeasPointsizeAA);
jsonObj.put("TotalnoofmeasPointsizeB", TotalnoofmeasPointsizeB);
jsonObj.put("TotalnoofmeasPointsizeBB", TotalnoofmeasPointsizeBB);
jsonObj.put("NomeasurementptoutoftolA", NomeasurementptoutoftolA);
jsonObj.put("NomeasurementptoutoftolB", NomeasurementptoutoftolB);
jsonObj.put("PASS", PASS);
jsonObj.put("Fail", Fail);
jsonObj.put("Pending", Pending);
jsonObj.put("Remarks", Remarks);
jsonObj.put("CreationDate", CreationDate);
jsonObj.put("MeasurementSheetDetailID", MeasurementSheetDetailID);
jsonObj.put("MeasurementPointID", MeasurementPointID);
jsonObj.put("MeasurementPoints", MeasurementPoints);
jsonObj.put("SpecSizeA", SpecSizeA);
jsonObj.put("SpecSizeAOne", SpecSizeAOne);
jsonObj.put("SpecSizeATwo", SpecSizeATwo);
jsonObj.put("SpecSizeAThree", SpecSizeAThree);
jsonObj.put("SpecSizeAFour", SpecSizeAFour);
jsonObj.put("SpecSizeAFive", SpecSizeAFive);
jsonObj.put("SpecSizeB", SpecSizeB);
jsonObj.put("SpecSizeBOne", SpecSizeBOne);
jsonObj.put("SpecSizeBTwo", SpecSizeBTwo);
jsonObj.put("SpecSizeBThree", SpecSizeBThree);
jsonObj.put("SpecSizeBFour", SpecSizeBFour);
jsonObj.put("SpecSizeBFive", SpecSizeBFive);
jsonObj.put("Tolerance", Tolerance);
jsonTempArray.put(jsonObj);
}
jsonObject.put("jsondata",jsonTempArray);
register=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
return;
}
new save(register).execute();
}
Result: Both rows are same that`s the problem
Row 1
[{"MeasurementSheetID":"0","GeneralID":"6832","Samplesize":"10","Measurement":"INCH","Qtypersize":"5","Color":"Black","SpecSizeA":"6.5","SpecSizeB":"6.5","TotalnoofmeasPointsizeA":"30","TotalnoofmeasPointsizeAA":"125","TotalnoofmeasPointsizeB":"30","TotalnoofmeasPointsizeBB":"125","NomeasurementptoutoftolA":"0","NomeasurementptoutoftolB":"0","PASS":"d","Fail":"h","Pending":"k","Remarks":"g","CreationDate":"2018-11-305
05:04:28","MeasurementSheetDetailID":"0","MeasurementPointID":"2","MeasurementPoints":"BACK
POCKET POSITION POSITION OUTER
EDGE","SpecSizeAOne":"","SpecSizeATwo":"","SpecSizeAThree":"","SpecSizeAFour":"","SpecSizeAFive":"","SpecSizeBOne":"","SpecSizeBTwo":"","SpecSizeBThree":"","SpecSizeBFour":"","SpecSizeBFive":"","Tolerance":"+/-0.5"},
Row 2
{"MeasurementSheetID":"0","GeneralID":"6832","Samplesize":"10","Measurement":"INCH","Qtypersize":"5","Color":"Black","SpecSizeA":"6.5","SpecSizeB":"6.5","TotalnoofmeasPointsizeA":"30","TotalnoofmeasPointsizeAA":"125","TotalnoofmeasPointsizeB":"30","TotalnoofmeasPointsizeBB":"125","NomeasurementptoutoftolA":"0","NomeasurementptoutoftolB":"0","PASS":"d","Fail":"h","Pending":"k","Remarks":"g","CreationDate":"2018-11-305
05:04:28","MeasurementSheetDetailID":"0","MeasurementPointID":"2","MeasurementPoints":"BACK
POCKET POSITION POSITION OUTER
EDGE","SpecSizeAOne":"","SpecSizeATwo":"","SpecSizeAThree":"","SpecSizeAFour":"","SpecSizeAFive":"","SpecSizeBOne":"","SpecSizeBTwo":"","SpecSizeBThree":"","SpecSizeBFour":"","SpecSizeBFive":"","Tolerance":"+/-0.5"}]
You need to put this jsonObj=new JSONObject(); inside your loop.
So every time loop execute it will create new JSONObject and put it into JSONArray
JsonArray is composed by jsonObjects.
You need to empty jsonobject, populate it and put in jsonarray for every object in jsonArray.
jsonObj = new JSONObject();
Some documentation

android JSONException index out of range

I have 3 records in my database but only one shows. No idea how to fix the problem, I tried everything. HELP
public void onResponse(JSONArray response) {
JSONObject jo;
Teacher teacher;
try {
for (int i = 0; i < response.length(); i++) {
JSONArray innerJsonArray = response.getJSONArray(i);
jo = innerJsonArray.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("teacher_name");
String description = jo.getString("teacher_description");
String imageUrl = jo.getString("teacher_image_url");
teacher = new Teacher(name, description, PHP_MYSQL_SITE_URL+imageUrl);
teachers.add(teacher);
te.setText(Integer.toString(response.length()));
}
//SET SPINNER
adapter = new ListViewAdapter(c, teachers);
gv.setAdapter(adapter);
there should be 2 for loops , one for JSONArray innerJsonArray = response.getJSONArray(i); and second for JSONArray innerJsonArray = response.getJSONArray(j); that iterates through innerJsonArray
public void onResponse(JSONArray response) {
JSONObject jo;
Teacher teacher;
try {
for (int i = 0; i < response.length(); i++) {
JSONArray innerJsonArray = response.getJSONArray(i);
for (int j = 0; j < innerJsonArray.length(); j++) {
jo = innerJsonArray.getJSONObject(j);
int id = jo.getInt("id");
String name = jo.getString("teacher_name");
String description = jo.getString("teacher_description");
String imageUrl = jo.getString("teacher_image_url");
teacher = new Teacher(name, description, PHP_MYSQL_SITE_URL + imageUrl);
teachers.add(teacher);
te.setText(Integer.toString(response.length()));
}
}
//SET SPINNER
adapter = new ListViewAdapter(c, teachers);
gv.setAdapter(adapter);
}
}

how to get json which has multiple values in a string in android

I have a json which has multiple values separated by commas which is in the
form of array.I want to get skills and platforms string separately.Can you please help me?
I want to show skills string and platforms string in text.
Please help me.
The format is:
{
"data": [
{
"skills": "ANDROID SDK, ANIMATION, ANGULARJS,",
"platforms": "IOS Application, Social Networking, Online shopping Sites, Web Application"
}
],
"status": 100
}
Try this one
try {
JSONObject ob = new JSONObject(response);
int status = ob.getInt("status");
if (status == 100) {
JSONArray ja = ob.getJSONArray("data");
for (int i = 0; i < ja.length(); i++) {
values = new HashMap<>();
JSONObject vj = ja.getJSONObject(i);
String skills = vj.getString("skills "));
String platforms=vj.getString("platforms"));
data.add(values);
}
split these 2 strings using 'split()'
List<String> skillsArray = Arrays.asList(skills.split(","));
List<String> platformsArray= Arrays.asList(platforms.split(","));
String in = "your json";
JSONObject jsonObj = new JSONObject(in);
// Getting JSON Array node
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Try this
JSONObject jsonObject = new JSONObject("Your json response");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skill = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
String[] skillsArray = skill.split(Pattern.quote(","));
String[] platformsArray = platforms.split(Pattern.quote(","));
for (int j=0; j<skillsArray.length; j++)
{
Log.i("Skill Value ", "=" + skillsArray[j]);
}
for (int j=0; j<platformsArray.length; j++)
{
Log.i("platforms Value ", "=" + platformsArray[j]);
}
}
Output
First of all convert your output string into json. Note that output string is the string which contains your results of json format that you have posted above.following is the code on how to do that:
JSONObject myJsonResponse = new JSONObject(yourString);
The next one is Array. That is how you will get it and will iterate over it.
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject innerJsonObject= jsonarray.getJSONObject(i);
String skills = innerJsonObject.getString("skills");
String platforms = innerJsonObject.getString("platforms");
}
Now you have gotten your required fields and you can now perform any String functions over the String skills and platforms.
Happy coding. .
The best way is creating a model class such :
public class MyModel{
Properties [] data;
class Properties{
public String skills;
public String platforms;
}
}
then you can parse your string to model with Gson library like this :
MyModel myModel = new Gson().fromJson(yourString, MyModel.class)
so all data is in myModel object and you can access to skills with
myModel.data[0].skills
to add Gson library to your project add below to your app gradle file :
compile 'com.google.code.gson:gson:2.8.1'
You may try this,
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject("JSON_STRING");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String[] seperateData = skills.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Skill Value-> ", seperateData[j]);
}
String platforms = jsonobject.getString("platforms");
seperateData = platforms.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Platform Value-> ", seperateData[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
class Data{
public String skills;
public String platforms;
}
Gson gson = new Gson();
JSONArray dataArray = response.getJSONArray("data");
List<Data> dataList= gson.fromJson(dataArray toString(), new TypeToken<List<Data>>() {
}.getType());
Try this.. It will make parsing easier.
implementation 'com.google.code.gson:gson:2.8.0'
First Parse your JSON:
JSONObject jsonObj = new JSONObject(in);
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Then Split your string values:
String skills = "ANDROID SDK, ANIMATION, ANGULARJS";
String[] separated = CurrentString.split(",");
separated[0]; // this will contain "ANDROID SDK"
separated[1]; // this will contain " ANIMATION"
separated[2]; // this will contain " ANGULARJS"
You have to remove the space to the second String:
separated[1] = separated[1].trim();
Try this you will be getting all values of sapereted with commas
jsonString = getting string from server side
String[] separated = jsonString.split(",");
StringBuilder s = new StringBuilder(10000);
for (int i = 0; i < separated.length; i++) {
if (i == separated.length - 1) {
s.append(separated[i].trim() + "");
} else {
s.append(separated[i].trim() + ",\n");
}
}
//tvDisplayAddress.setText(s);
Log.e("VALUES: ",s+"");

how to calculate total payment in textView which is retrieve from Php server

[{"id":"1","payment":"25414"},{"id":"2","payment":"698547"},{"id":"3","payment":"98745"},{"id":"4","payment":"9857485"},{"id":"5","payment":"365214"},{"id":"6","payment":"10"},{"id":"7","payment":"965845"},{"id":"8","payment":"654123"},{"id":"9","payment":"654123"},{"id":"10","payment":"365241"}]
I want to calculate sum of total payment sum which is retrieve from php i am using JsonArray
String json = serviceClient.makeServiceCall(URL_ITEMS, ServiceHandler.GET);
// print the json response in the log
if (json != null) {
try {
paymentResult = new JSONArray(json);
int tmp = 0;
for (int i = 0; i < paymentResult.length(); i++) {
JSONObject c = paymentResult.getJSONObject(i);
String id = c.getString(TAG_ID);
Log.d("id", id);
String payment = c.getString(TAG_VAL);
Log.d("payment", payment);
try{
tmp = paymentResult.getJSONObject(i).getInt("payment");
count = count+1;
}catch (JSONException e){}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
TextView tv = (TextView)findViewById(R.id.count);
tv.setText(Integer.toString (+count));
}
But there it count the Array number
what is change to be applied here?
Try this :
paymentResult = new JSONArray(json);
int tmp = 0;
int sum = 0;
for (int i = 0; i < paymentResult.length(); i++) {
JSONObject c = paymentResult.getJSONObject(i);
String id = c.getString(TAG_ID);
Log.d("id", id);
String payment = c.getString(TAG_VAL);
Log.d("payment", payment);
temp = Integer.parseInt(payment);
sum = sum+temp;
}// loop end
... // sum is your total payment

Categories

Resources