Hi in the code I am using recyclerview to displaying a listview .I am calling the APi and rending the list .But in that list contains data are chnaging with the content.
I want to filter the list and display it into single list item
For example list items contains name and details and unique no.want to display all the contents are name
sample json response:
"blocks": [
{
"label": "Basic Information",
"fields": [
{
"name": "sales_stage",
"value": "Opportunity",
"label": "Sales Stage",
"uitype": "15",
"type": {
"defaultValue": null
}
},
{
"name": "potentialname",
"value": "GVN hospital-Falco",
"label": "Opportunity Name",
"uitype": "2",
"type": {
"defaultValue": null
}
},
{
"name": "assigned_user_id",
"value": {
"value": "19x84",
"label": "Chandra Mouli N"
},
"label": "Assigned To",
"uitype": "53",
"type": {
"defaultValue": {
"value": "19x1",
"label": "Administrator"
}
}
},
{
"name": "potential_no",
"value": "GW/OPP/100743",
"label": "Opportunity Number",
"uitype": "4",
"type": {
"defaultValue": null
}
}
{"label": "Products",
"fields": [
{
"name": "productid",
"value": {
"value": "14x33080",
"label": "CS 30"
},
"label": "Item Name",
"uitype": "10",
"type": {
"defaultValue": null
}
},]
}
]
}]
"blocks": [
{
"label": "Basic Information",
"fields": [
{
"name": "sales_stage",
"value": "Opportunity",
"label": "Sales Stage",
"uitype": "15",
"type": {
"defaultValue": null
}
},
{
"name": "potentialname",
"value": "GVN hospital-Falco",
"label": "Opportunity Name",
"uitype": "2",
"type": {
"defaultValue": null
}
},
{
"name": "assigned_user_id",
"value": {
"value": "19x84",
"label": "Chandra Mouli N"
},
"label": "Assigned To",
"uitype": "53",
"type": {
"defaultValue": {
"value": "19x1",
"label": "Administrator"
}
}
},
{
"name": "potential_no",
"value": "GW/OPP/100743",
"label": "Opportunity Number",
"uitype": "4",
"type": {
"defaultValue": null
}
}]
{"label": "Products",
"fields": [
{
"name": "productid",
"value": {
"value": "14x33080",
"label": "CS 30"
},
"label": "Item Name",
"uitype": "10",
"type": {
"defaultValue": null
}
},]
}]
Actual output:
example: list1:
name :xyz
product:123
list2:
name :xyz
product:abc
list3:
name :xyz
product:1234
Expected output:
list:
name :xyz
product:123,abc,1234
Java:
private void fetchJSONForSales(){
handler.postDelayed(new Runnable() {
#Override
public void run() {
sessionId = getActivity().getIntent().getStringExtra("sessionId");
String operation = "syncModuleRecords";
String module = "Potentials";
String syncToken="";
String mode="public";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<SyncModule> call = service.GetSyncModuleList(operation, sessionId, module,syncToken,mode);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<SyncModule>() {
#Override
public void onResponse(Call<SyncModule> call, Response<SyncModule> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
SyncModule syncModule = response.body();
String success = syncModule.getSuccess();
if (success.equals("true")) {
SyncResults results = syncModule.getResult();
Sync sync=results.getSync();
ArrayList<SyncUpdated> syncUpdateds=sync.getUpdated();
for(SyncUpdated syncUpdated:syncUpdateds){
ArrayList<SyncBlocks> syncBlocks=syncUpdated.getBlocks();
String title = "";
String value = "";
String potentialValue = "";
String potentialNo = "";
String assigned = "";
String contact = "";
String location = "";
String related = "";
String winprobValue = "";
String valueAndQty = "";
String productValue = "";
String quantity = "";
String salesstageValue="";
String employee="";
String leadsource="";
String remark_sales_person="";
String segment="";
String modality="";
String circle="";
String prospect_type="",equ_details="",sale_type="",createdtime="",modifiedtime="",modifiedby="",closingdate="",exp_delivery_date="",pndt="",demo_done="",s_i="",demo_date="",fun_req="",site_read="",
support_person="",support_type="",opportunity_type="",department="",rating="",interest_type="",
txt_adj="",hdnS_H_Amount="",pre_tax_total="",hdnSubTotal="",listprice="",comment="",discount_amount="",tax1="",tax2="",tax3="",lost_reason="",
competition_name="",price_quoted="",general_remark="",description="",termsnconditions="";
String mobie = sharedPreferences.getString("mobiles", null);
for (SyncBlocks syncBlocks1 : syncBlocks) {
String label = syncBlocks1.getLabel();
//Basic Information
if (label.equals("Basic Information")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (name.equals("sales_stage")) {
salesstageValue = String.valueOf(values);
} else if (name.equals("potentialname")) {
potentialValue = String.valueOf(values);
} else if (name.equals("assigned_user_id")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
// assigned_tos.add(v);
assigned = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("related_to")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
// assigned_tos.add(v);
related = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("contact_id")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
contact = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("potential_no")) {
potentialNo = String.valueOf(values);
} else if (name.equals("location")) {
location = String.valueOf(values);
}else if (name.equals("employee")) {
employee = String.valueOf(values);
}else if (name.equals("leadsource")) {
leadsource = String.valueOf(values);
}else if (name.equals("cf_954")) {
remark_sales_person = String.valueOf(values);
}else if (name.equals("segment")) {
segment = String.valueOf(values);
}else if (name.equals("modality")) {
modality = String.valueOf(values);
}else if (name.equals("circle")) {
circle = String.valueOf(values);
}
}
} else if (label.equals("Opportunity Details")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (name.equals("cf_996")) {
title = String.valueOf(values);
} else if (name.equals("cf_897")) {
winprobValue = String.valueOf(values);
}else if (name.equals("cf_960")) {
prospect_type = String.valueOf(values);
}else if (name.equals("cf_1010")) {
equ_details = String.valueOf(values);
}else if (name.equals("cf_992")) {
sale_type = String.valueOf(values);
}else if (name.equals("createdtime")) {
createdtime = String.valueOf(values);
}else if (name.equals("modifiedtime")) {
modifiedtime = String.valueOf(values);
} else if (name.equals("modifiedby")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
modifiedby = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
}else if (name.equals("closingdate")) {
closingdate = String.valueOf(values);
}else if (name.equals("cf_1000")) {
exp_delivery_date = String.valueOf(values);
}else if (name.equals("cf_998")) {
pndt = String.valueOf(values);
}else if (name.equals("demo_done")) {
demo_done = String.valueOf(values);
}else if (name.equals("cf_903")) {
s_i = String.valueOf(values);
}else if (name.equals("demo_date")) {
demo_date = String.valueOf(values);
}else if (name.equals("cf_899")) {
fun_req = String.valueOf(values);
}else if (name.equals("cf_1002")) {
site_read = String.valueOf(values);
}else if (name.equals("cf_1004")) {
support_person = String.valueOf(values);
}else if (name.equals("cf_1006")) {
support_type = String.valueOf(values);
}else if (name.equals("opportunity_type")) {
opportunity_type = String.valueOf(values);
}
}
}
}
String rupee = getResources().getString(R.string.Rs);
int paswd = (int) Double.parseDouble(quantity);
String qty=String.valueOf(paswd);
ModelTest modelTest = new ModelTest(potentialValue,related,assigned,contact,location,productValue,rupee.concat(valueAndQty),
potentialNo,mobie,competition_name,circle,closingdate,comment,createdtime,demo_date,demo_done,department
,description,discount_amount,equ_details,employee,exp_delivery_date,fun_req,general_remark,hdnS_H_Amount,hdnSubTotal,
interest_type,lost_reason,leadsource,listprice,modality,modifiedby,modifiedtime,opportunity_type,pre_tax_total,pndt,price_quoted,prospect_type,
rating,remark_sales_person,sale_type,support_type,s_i,segment,site_read,txt_adj,tax1,tax2,tax3,termsnconditions,winprobValue,support_person,qty,salesstageValue);
if(salesstageValue.equals("Opportunity")){
listSalesStageOpportunity.add(modelTest);
opportunityAdapter.notifyDataSetChanged();
As you are passing the complete model class i.e "modelTest object" to the adapter by adding it to "listSalesStageOpportunity list". All you have to change is your layout. Inflate the recycler view for item containing the names only that you want to show. If you are creating different textviews in recycler view for each data then you just need to setVisibility to View.VISIBLE for names only or you can do so by declaring it in XML layout.
HI you need to add the check there where do you want to select the name
if("name").equals.("xyz"){
append("data yo want to append")
}
How to parse this json and loop through each item and get its key string and value string.(keys are generated dynamically)
{
"business_industry_type": {
"11": "dummy1",
"2": "dummy2",
"44": "dummy3",
"4": "dummy4",
"5": "dummy5",
"34": "dummy6",
"7": "dummy7",
"88": "dummy8",
"9": "dummy9"
},
"status": "success",
"description": "Successfully ListedType",
"DES_CODE": "NC08"
}
Maybe this will help, try using Iterator to solve your problem.
Iterator<?> permisos = jsonObject.keys();
try {
while(permisos.hasNext() ){
String key = (String)permisos.next();
if(jsonObject.get(key) instanceof JSONObject) {
Iterator<?> tipo = jsonObject.getJSONObject(key).keys();
while (tipo.hasNext()) {
String key2 = (String) tipo.next();
Log.e("TAG", "Key: "+ key2 +" Value: "+jsonObject.getJSONObject(key).getString(key2).toString() );
}
}
else
Log.e("TAG", "Key: "+ key +" Value: "+jsonObject.getString(key) );
}
} catch (JSONException e) {
e.printStackTrace();
}
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 want to get only some selected values from the JSON response.For example if JSON contains 100 string values then i need to take the values which are starting with # symbol from that 100 values.
How can I do that ?
Following is my JSON,
[{"Obj" :
{ "ID":"11",
"NAME":"XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
}]
Here I need to fetch Name which having # symbol
You can use below method to get the Name which start with # :
JSONObject jsonObject = new JSONObject(response);// u can change it as per your need
JSONArray jArray = jsonObject.getJSONArray("Obj");// if your `Obj` is an JsonArray
for (int i = 0; i < jArray.length(); i++) {
String json_name = jArray.getJSONObject(i).getString("NAME");
if(json_name.startsWith("#"))
{
Log.d(TAG,"It start with #");
}
}
Try out as below:
private void parseJSON(String json) {
try {
JSONArray items = new JSONArray(<your Json Response>);
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
System.err.println("Object---" + item.getString("Obj"));
JSONObject obj=item.getJSONObject("Obj");
for (int j = 0; j < obj.length(); j++) {
String Name=obj.getString("NAME");
if(obj.getString("NAME").toString().contains("#"))
{
Log.d("Name starts with-->", Name);
}
else
{
Log.d("Name does not start with-->", Name);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try this.
first of all that's not a valid json may be below json is correct format
[
{
"Obj": [
{
"ID": "11",
"NAME": "XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
}
]
}
]
if your response like above try below code this may help you.
try {
JSONArray jsoArray = new JSONArray(json);
JSONArray JobjArray = jsoArray.getJSONObject(0).getJSONArray("Obj");
for(int i=0; i < JobjArray.length(); i++)
{
JSONObject Jobj = JobjArray.getJSONObject(i);
Iterator<String> iter = Jobj.keys();
while (iter.hasNext()) {
String key = iter.next();
Log.v("key--", key);
try {
Object value = Jobj.get(key);
Log.v("value--", ""+value);
String str_value = value.toString().trim();
if(str_value.startsWith("#"))
{
Log.d(""+str_value,"value started with #");
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}