I'm trying to retrieve the objects inside a json array such as id and brand within creditcard.
{
"result_count": "2",
"total_no_of_rows": "2",
"status": {
"status_code": "-1",
"status_text": "Success"
},
"cards": [
{
"creditCard": {
"id": "CRC-9C7I2BGN8RJY",
"brand": "AMEX",
"first6": "376449",
"last4": "3005",
"store": true
},
"method": "CREDIT_CARD"
},
{
"creditCard": {
"id": "CRC-FXDA9E2YCWWQ",
"brand": "ELO",
"first6": "636297",
"last4": "7013",
"store": true
},
"method": "CREDIT_CARD"
}
]
}
I'm using the request below unsuccessfully because it returns card with no values.
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url, null, response -> {
arrayData.clear();
try {
JSONArray cards = response.getJSONArray("cards");
for (int i = 0; i < cards.length(); i++) {
JSONObject token = cards.getJSONObject(i);
CardList card = new CardList(
token.getString("id"),
token.getString("brand"),
token.getString("first6"),
token.getString("last4"),
token.getBoolean("store"));
arrayData.add(card);
}
Log.v("arrayData", String.valueOf(arrayData));
} catch (JSONException e) {
Log.v("arrayDataError", String.valueOf(e));
e.printStackTrace();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("arrayDataError", String.valueOf(error));
}
});
Could someone help? Thanks.
Follows the solution for those who need it:
JSONArray cards = response.getJSONArray("cards");
for (int i = 0; i < cards.length(); i++) {
JSONObject token = cards.getJSONObject(i);
JSONObject creditCard = token.getJSONObject("creditCard");
card_method = token.getString("method").equals("CREDIT_CARD") ?
getString(R.string.creditcard) : getString(R.string.debitcard);
CardList card = new CardList(
creditCard.getString("id"),
creditCard.getString("brand"),
creditCard.getString("first6"),
creditCard.getString("last4"),
creditCard.getBoolean("store"));
arrayData.add(card);
}
Related
I am making use of cardview and every card has a pop menu which opens another activity. "data" array is displayed on the card and I want the respective array "document_list" to be displayed on opening of other activity. Below is the code but all of the items are getting displayed. So how do I limit or restrict ? data(id) == document_list(property_id).
CARDVIEW FRAGMENT
StringRequest stringRequest = new StringRequest(Request.Method.POST,"URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONObject object = new JSONObject(response);
if (object.getInt("status") == 200) {
JSONArray jsonArray = object.getJSONArray("data");
// String userData = jsonArray.getString(0);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pobj = jsonArray.getJSONObject(i);
pobj.getString("id");
JSONObject pobj1 = new JSONObject(pobj.getString("owner_details"));
mylistList.add(new Mylist(
//other elements
pobj.getString("sas_application_no"),
pobj1.getString("name"),
pobj1.getString("mobile")
));
}
}
CARDVIEW ADAPTER
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
popup.inflate(R.menu.options_menu);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_document:
//handle menu2 click
id = mylist.getId();
Bundle bundle = new Bundle();
bundle.putString("id",id);
DocFragment newfragment1 = new DocFragment();
FragmentTransaction fragmentTransaction1 =((AppCompatActivity)mCtx).getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.container_view1, newfragment1);
fragmentTransaction1.addToBackStack(null);
fragmentTransaction1.commit();
NavigationActivity.container_view1.setVisibility(View.VISIBLE);
break;
}
return false;
}
});
Doc_fragment is the new activity which opens the cardview with below code. So on click of R.id.menu_document: I need to pass the "id" which is to fetched from CARDVIEW FRAGMENT? How do I do it?
public class DocFragment extends Fragment {
//a list to store all the products
List<DocList> docList;
DocAdapter docAdapter;
//the recyclerview
RecyclerView recyclerView;
private String sid = "";
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_doc, container, false);
if (getArguments() != null) {
sid = getArguments().getString("id");
Toast.makeText(getActivity(), sid, Toast.LENGTH_LONG).show();
}
docList = new ArrayList<>();
recyclerView = (RecyclerView) root.findViewById(R.id.recyclerView1);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//docList.add(new DocList("abc","123","asdf"));
//creating recyclerview adapter
docAdapter = new DocAdapter(getContext(), docList);
recyclerView.setAdapter(docAdapter);
loadMenuData();
return root;
}
public void loadMenuData() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
//String selectedId = getIntent().getStringExtra("selectedId");
JSONObject object = new JSONObject(response);
if (object.getInt("status") == 200) {
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pobj = jsonArray.getJSONObject(i);
if (!sid.equals(pobj.optString("id", "")))
continue;
JSONArray jsonArray1 = pobj.getJSONArray("document_list");
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject dobj = jsonArray1.getJSONObject(j);
docList.add(new DocList(
dobj.getString("document_name"),
dobj.getString("description"),
dobj.getString("doc_no")
));
}
}
}
//creating adapter object and setting it to recyclerview
docAdapter = new DocAdapter(getContext(), docList);
recyclerView.setAdapter(docAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getContext()).add(stringRequest);
}
}
{
"status": 200,
"data": [
{
"id": "5",
"property_type": "AGRICULTURAL",
"name": "A D ",
"site_no": "SY NO 21",
"p_id_no": "21",
"sas_application_no": "13",
"latitude": "12",
"longitude": "33",
"status": "OWNED",
"purchase_year": "2007",
"owner_details": {
"name": "A D",
"mobile": "776006"
},
"size": "41724",
"unit": "SQF",
"document_list": [
{
"property_id": "5",
"document_type_id": "4",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "Encumbrance Certificate",
"description": null,
"doc_no": null
},
{
"property_id": "5",
"document_type_id": "3",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "Mother Deed",
"description": null,
"doc_no": null
},
{
"property_id": "5",
"document_type_id": "84",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "MUTATION COPY ",
"description": null,
"doc_no": null
},
{
"property_id": "5",
"document_type_id": "87",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "OLD E C",
"description": null,
"doc_no": null
},
{
"property_id": "5",
"document_type_id": "83",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "OTHER DOCUMENTS ",
"description": null,
"doc_no": null
},
]
},
{
"id": "9",
"property_type": "AGRICULTURAL",
"name": "A D ",
"site_no": "SY NO 19/1 ",
"p_id_no": "19/1",
"sas_application_no": "12",
"latitude": "12",
"longitude": "45",
"status": "OWNED",
"purchase_year": "2007",
"owner_details": {
"name": "A D ",
"mobile": "7760906"
},
"size": "2",
"unit": "ACR",
"document_list": [
{
"property_id": "9",
"document_type_id": "4",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "Encumbrance Certificate",
"description": null,
"doc_no": null
},
{
"property_id": "9",
"document_type_id": "43",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "GPA",
"description": null,
"doc_no": null
},
]
},
You can do something like this:
In your CardViewFragment set the arguments when the card is selected like following:
switch (item.getItemId()) {
case R.id.menu_document:
//handle menu2 click
Bundle bundle = new Bundle();
bundle.putString("selectedId",selectedId);//get this id from your object/model .e.g list.get(postion).getId() , do it as per your strcuture setup.
DocFragment newfragment1 = new DocFragment();
newfragment1.setArguments(bundle);
FragmentTransaction fragmentTransaction1 =((AppCompatActivity)mCtx).getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.container_view1, newfragment1);
fragmentTransaction1.addToBackStack(null);
fragmentTransaction1.commit();
NavigationActivity.container_view1.setVisibility(View.VISIBLE);
break;
}
In your DocFragment create a global variable and match it with the data coming from your source.
private String selectedId = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
selectedId = getArguments().getString("selectedId");
}
}
Then match that id while fetching in DocFragment
try {
//converting the string to json array object
JSONObject object = new JSONObject(response);
if (object.getInt("status") == 200) {
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pobj = jsonArray.getJSONObject(i);
// compare id passed from main activity, which was selected by user
if (!selectedId.equals(pobj.optString("id", "")))
continue;
JSONArray jsonArray1 = pobj.getJSONArray("document_list");
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject dobj = jsonArray1.getJSONObject(j);
docList.add(new DocList(
dobj.getString("document_name"),
dobj.getString("description"),
dobj.getString("doc_no")
));
}
}
}
} catch (Exception e) {
}
I have the following JSON response i want to get separate values like CHIL SEZ IT Park,Coimbatore,Tamil Nadu,India
JSON String is:
[
{
"value": "CHIL SEZ IT Park",
"offset": 0
},
{
"value": "Coimbatore",
"offset": 18
},
{
"value": "Tamil Nadu",
"offset": 30
},
{
"value": "India",
"offset": 42
}
]
Try this:
ArrayList<String> arrayList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(responseStr);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String value = jsonObject.getString("value");
arrayList.add(value);
}
} catch (JSONException e) {
e.printStackTrace();
}
Place this function and pass the jsonString. You will get the ArrayList from the JSON.
public ArrayList<String> getPlaceName(String jsonString){
ArrayList<String> places = new ArrayList<>();
try{
JSONArray array = new JSONArray(jsonString);
for(int x=0;x<array.length();x++){
places.add(array.getJSONObject(x).getString("value"));
}
}catch (JSONException e){}
return places;
}
I got the json data using this
``
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
``
Here is the json data.
``
{
"Questions": [
{
"Question": "Which animal is Carnivorous?",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Cow"
},
{
"Answer": "Lion"
},
{
"Answer": "Goat"
},
{
"Answer": "Elephant"
}
]
},
{
"Question": "Humans need",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Oxygen"
},
{
"Answer": "Nitrogen"
},
{
"Answer": "CarbonDioxide"
},
{
"Answer": "Hydrogen"
}
]
},
{
"Question": "Choose the Amphibian ",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Frog"
},
{
"Answer": "Owl"
},
{
"Answer": "Goat"
},
{
"Answer": "Fox"
}
]
},
{
"Question": "---- is part of Earth`s Atmosphere.",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Unisphere"
},
{
"Answer": "Troposphere"
},
{
"Answer": "Oxysphere"
},
{
"Answer": "Carbosphere"
}
]
},
]
}
After getting the json data
All I need now is to randomize it.
Help a brother please, I have tried everything but nothing is working
Thanks in advance
After
quesList = quesObj.getJSONArray("Questions"); // Right place to shuffle PeterOla,add this to randomize questions list:
List<JSONObject> questionsList = new ArrayList<JSONObject>(quesList.length());
for(int i=0,size=quesList.length();i<size;++i){
try {
questionsList.add(quesList.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
long seed = System.nanoTime();
Collections.shuffle(questionsList, new Random(seed));
Put values into a list, then you can shuffle it easily. Use this:
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
Collections.shuffle(listdata);
try {
JSONObject jsonObject = new JSONObject(response);
String current_page = jsonObject.optString("current_page");
NextPageUrl = jsonObject.optString("next_page_url");
if (current_page.equals("1")){
lifeHomeModels.clear();
JSONArray data = jsonObject.getJSONArray("data");
for (int i =0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String id = jsonObject1.optString("id");
String post_user_id = jsonObject1.optString("user_id");
String post_id = jsonObject1.optString("post_id");
String post_details = jsonObject1.optString("post_details");
}
Family_HomeModel inputModel = new Family_HomeModel();
inputModel.setId(id);
inputModel.setPost_user_id(post_user_id);
inputModel.setPost_id(post_id);
inputModel.setPost_details(post_details);
lifeHomeModels.add(inputModel);
}
long seed = System.nanoTime();
Collections.shuffle(lifeHomeModels, new Random(seed));
}
lifeHomeAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
i want to parse userinfo Array and some string in it. and getuserlistdata array and some string in it. please help me how to parse this response.This is my respons.
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test",
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India"
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
},
],
]
}
}
Sir, This my code.
protected Void doInBackground(Void...arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
String url_links = "http://192.168.0.65/hostandguest/android/viewprofile?uid=77";
Log.d("url_links: ", "> " + url_links);
String jsonStr = sh.makeServiceCall(url_links, ServiceHandler2.GET);
Log.v("Profile:", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
status = obj.getString("status");
data = obj.getString("data");
if (status.equalsIgnoreCase("false")) {
} else {
jsonarr = obj.getJSONArray("userinfo");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject c = jsonarr.getJSONObject(i);
String fname = c.getString("firstname");
Datein_arr.add(fname);
String id = c.getString("id");
}
jsonarr2 = obj.getJSONArray("getuserlistdata");
for (int j = 0; j < jsonarr2.length(); j++) {
JSONObject jo = jsonarr2.getJSONObject(j);
address = jo.getString("address");
Log.v("address", "" + address);
Log.v("Profile:", "777777777777777777777777777777777777");
hostimgrr2 = obj.getJSONArray("hostImage");
if (hostimgrr2.length() == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
det_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
} else {
for (int k = 0; k < hostimgrr2.length(); k++) {
JSONObject js = hostimgrr2.getJSONObject(k);
img = js.getString("images");
Log.v("img", "" + img);
if (k == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try like below code to parse JSONArray.
try {
private ArrayList<UserInfo> userInfoList = new ArrayList<UserInfo>();
JSONObject jsonObject = new JSONObject(jsonData); // jsonData is your reponse string
JSONArray userinfo = jsonData.getJSONArray("userinfo");
for(int i = 0; i < userinfo.length(); i++) {
JSONObject jObject = userinfo.getJSONObject(i);
UserInfo userInfo = new UserInfo();
userInfo.setId( jObject.getString("id") );
userInfo.setFirstname( jObject.getString("firstname") );
userInfoList.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
UserInfo class as follow.
public class UserInfo {
public String id = "";
public String firstname = "";
public String getID() {
return coursePrice;
}
public void setID(String id) {
this.id = id;
}
public String getFirstname() {
return coursePrice;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
First you have to validate your jsondata.
You can goto JSONLint to check whether your json is valid or not
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test"
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India",
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
}
]
}
]
}
}
And You are parsing a JSONObject as String.
ie, it should be obj.getJSONObject("data"); instead of obj.getString("data");
Also check for other parsing issues like this.
I am parsing some JSON that has arrays within arrays, and I just cant seem to get the data of the arrays within the first array.
My JSON looks like this (I cut it off in the end so it wasn't that long):
{"TrackingInformationResponse": {
"shipments": [
{
"shipmentId": "03015035146308",
"uri": "\/ntt-service-rest\/api\/shipment\/03015035146308\/0",
"assessedNumberOfItems": 1,
"deliveryDate": "2013-05-13T11:47:00",
"estimatedTimeOfArrival": "2013-05-13T16:00:00",
"service": {
"code": "88",
"name": "DPD"
},
"consignor": {
"name": "Webhallen Danmark ApS",
"address": {
"street1": "Elsa Brändströms Gata 52",
"city": "HÄGERSTEN",
"countryCode": "SWE",
"country": "Sverige",
"postCode": "12952"
}
},
"consignee": {
"name": "Lene Bjerre Kontor & IT Service",
"address": {
"street1": "Lene Bjerre",
"street2": "Ørbækvej 8, Hoven",
"city": "TARM",
"countryCode": "???",
"postCode": "6880"
}
},
"statusText": {
"header": "Forsendelsen er udleveret",
"body": "Forsendelsen blev leveret 13-05-2013 kl. 11:47"
},
"status": "DELIVERED",
"totalWeight": {
"value": "0.55",
"unit": "kg"
},
"totalVolume": {
"value": "0.005",
"unit": "m3"
},
"items": [
{
"itemId": "03015035146308",
"dropOffDate": "2013-05-08T17:18:00",
"deliveryDate": "2013-05-13T11:47:00",
"status": "DELIVERED",
"statusText": {
"header": "Forsendelsen er udleveret til modtageren",
"body": "Forsendelsen blev udleveret 13-05-2013 kl. 11:47"
},
I can get the content of the "shipments" array just fine, but I have no idea how to get the contents of the "items" array. My code looks like this:
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
How would I do the same with the "items" array as I did with the "shipments" array?
You have to get the items array from inside the Shipment array, like you did the shipments, then iterate through that, like you did the shipments.
It might look something like:
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items");
//get items stuff
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
items is a JSON Array located inside the shipments array, so you need to get the items array within the shipments, maybe like this :
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items"));
//iterate over items
}
Hope this helps, Good luck
Try bellow code:
JSONObject jObject = new JSONObject(yourJSONString);
JSONObject trackInfo = jObject.getJSONObject("TrackingInformationResponse");
JSONArray shipMents = trackInfo.getJSONArray("shipments");
JSONArray items = shipMents.getJSONArray("items");