json parse data set search condition is no working - android

I parse json data successfully , i can show it on my recyclerView.
it's my data source:
(had solved the issue)
I want to set a search condition about month > 5
I had set a String.equal("compareString"); before, it worked.
But when i set the month in this case, it's not working.
do i set something wrong? any help will be grateful.
private void showRoute(String route) {
try {
JSONObject jsonObject = new JSONObject(route);
String arrayData = jsonObject.getString("JsonData");
JSONArray jsonArray = new JSONArray(arrayData);
Log.d(TAG, "JSONArray" + ">>>>>>>>>>" + jsonArray);
for (int i = 467; i < jsonArray.length(); i++) {
int month=5;//set search condition, i want to show a list , it's month > 5
//here is my search condition
if (Integer.parseInt(jsonArray.getJSONObject(i).getString("STARTMONTH"))>=month) {
String EDUTITLE = jsonArray.getJSONObject(i).getString("EDUTITLE");
String STARTMONTH = jsonArray.getJSONObject(i).getString("STARTMONTH");
String STARTDAY = jsonArray.getJSONObject(i).getString("STARTDAY");
String STARTDATE = jsonArray.getJSONObject(i).getString("STARTDATE");
String SPONSER = jsonArray.getJSONObject(i).getString("SPONSER");
String EDUSCORE = jsonArray.getJSONObject(i).getString("EDUSCORE");
String EDUIN = jsonArray.getJSONObject(i).getString("EDUIN");
String HOLDER = jsonArray.getJSONObject(i).getString("HOLDER");
ActivityListItem listItem = new ActivityListItem(EDUTITLE, STARTMONTH, STARTDAY, STARTDATE, SPONSER, EDUSCORE, EDUIN, HOLDER);
arrayList.add(listItem);
}else {
recyclerView.setVisibility(View.GONE);
textForEmpty.setVisibility(View.VISIBLE);
}
//arrayListOrigin.add(listItem);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
and another question , if my data is 467~500 , my list will show 467~500 from up to down , what if i want to let it shows 500~467 from up to down , what should i do is more correct ?
I try some code like: it show empty
String month="5";
if (month.equals(jsonArray.getJSONObject(i).getString("STARTMONTH"))) {
other code...
}
but if i try to compare EDUIN like this: it works...
String eduin="0";
if (eduin.equals(jsonArray.getJSONObject(i).getString("EDUIN"))) {
other code...
}
i don't get it now :(

The issue is your if condition may not be executed because of this line
String arrayData = jsonObject.getString("JsonData");
In your response "JsonData" is a JSONArray not a String .
Try this instead.
JSONObject jsonObject = new JSONObject(route);
JSONArray jsonArray = jsonObject.getJSONArray("JsonData") ;
for (int i = 467; i < jsonArray.length(); i++) {
//rest of your code
}
Now if you want to item from 500 to 467 reverse the loop
for(int i = jsonArray.length()-1; i >= 467; i--){
if(Integer.parseInt(jsonArray.getJSONObject(i).getString("STARTMONTH"))>=month){
// rest of the code..
}}
outside the loop hide recycleview like this
if (arrayList.size() == 0) {
//hide recycleview
recyclerView.setVisibility(View.GONE);
textForEmpty.setVisibility(View.VISIBLE);
}
Or
Much more easier way
ArrayList<Element> tempElements = new ArrayList<Element>(arrayList);
Collections.reverse(tempElements);

Related

I want to list data from JSON string using an array, but why my app crashes?

I want to list data from a JSON string in ListView.
I store the strings in an array.
When I write i in the line JSONObject day = jsonArray.getJSONObject(0); the app crashes.
What did I wrong?
String json_string1 = "{\"list\":[{\"dt\":1471255200,\"temp\":{\"day\":30.04,\"min\":17.35,\"max\":30.04},\"pressure\":1018.83,\"humidity\":35,\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"de scription\":\"scattered clouds\",\"icon\":\"03d\"}],\"speed\":2.66,\"deg\":314,\"clouds\":48},{\"dt\":1471341600,\"temp\":{\"day\":29.48,\"min\":19.3,\"max\":29.95},\"pressure\":1018.63,\"humidity\":100,\"weather\":[{\"id\":501,\"main\":\"Rain\",\"des cription\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.46,\"deg\":28,\"clouds\":92,\"rain\":8.5},{\"dt\":1471428000,\"temp\":{\"day\":28.96,\"min\":17.84,\"m ax\":297.54},\"pressure\":1012.1,\"humidity\":95,\"weather\":[{\"id\":501,\"main\":\"Ra in\",\"description\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.27,\"deg\":118,\"clouds\":88,\"rain\":5.55},{\"dt\":1471514400,\"temp\":{\"day\":26.89,\"min\":17.84,\" max\":28.95},\"pressure\":1014.27,\"humidity\":83,\"weather\":[{\"id\":500,\"main\":\"R ain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.98,\"deg\":93,\"clouds\":20},{\"dt\":1471600800,\"temp\":{\"day\":30.04,\"min\":21.87,\"max\":30.04},\"pressure\":1014.65,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descrip tion\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.66,\"deg\":194,\"clouds\":11,\"rain\":0.22},{\"dt\":1471687200,\"temp\":{\"day\":31.3,\"min\":22.56,\"max\":32.3},\"p ressure\":1018.6,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descriptio n\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.69,\"deg\":180,\"clouds\":16,\"rain\":0.77},{\"dt\":1471773600,\"temp\":{\"day\":31.77,\"min\":21.67,\"max\":30.77},\"pressure\":1016.93,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":2.49,\"deg\":227,\"clouds\":14,\"rain\":2.2}]}";
JSONObject jsonObject;
String[] days_array = new String[7];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
jsonObject = new JSONObject(json_string1);
JSONArray jsonArray = jsonObject.optJSONArray("list");
int lengthJsonArr = jsonArray.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject day = jsonArray.getJSONObject(0);
JSONObject temp = day.getJSONObject("temp");
int min = temp.getInt("min");
int max = temp.getInt("max");
JSONArray weather = day.getJSONArray("weather");
JSONObject zero = weather.getJSONObject(0);
String main = zero.getString("main");
double speed = day.getDouble("speed");
days_array[i] = max + "/" + min + ", " + main + ", Wind=" + speed;
}
} catch (JSONException e) {
e.printStackTrace();
}
ListView ListView = (ListView) findViewById(R.id.list_view);
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_layout, R.id.item_name, days_array);
ListView.setAdapter(adapter);
}
You had two wrong property names: "m ax" and " max". This fixed json will work:
String json_string1 = "{\"list\":[{\"dt\":1471255200,\"temp\":{\"day\":30.04,\"min\":17.35,\"max\":30.04},\"pressure\":1018.83,\"humidity\":35,\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"de scription\":\"scattered clouds\",\"icon\":\"03d\"}],\"speed\":2.66,\"deg\":314,\"clouds\":48},{\"dt\":1471341600,\"temp\":{\"day\":29.48,\"min\":19.3,\"max\":29.95},\"pressure\":1018.63,\"humidity\":100,\"weather\":[{\"id\":501,\"main\":\"Rain\",\"des cription\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.46,\"deg\":28,\"clouds\":92,\"rain\":8.5},{\"dt\":1471428000,\"temp\":{\"day\":28.96,\"min\":17.84,\"max\":297.54},\"pressure\":1012.1,\"humidity\":95,\"weather\":[{\"id\":501,\"main\":\"Ra in\",\"description\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.27,\"deg\":118,\"clouds\":88,\"rain\":5.55},{\"dt\":1471514400,\"temp\":{\"day\":26.89,\"min\":17.84,\"max\":28.95},\"pressure\":1014.27,\"humidity\":83,\"weather\":[{\"id\":500,\"main\":\"R ain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.98,\"deg\":93,\"clouds\":20},{\"dt\":1471600800,\"temp\":{\"day\":30.04,\"min\":21.87,\"max\":30.04},\"pressure\":1014.65,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descrip tion\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.66,\"deg\":194,\"clouds\":11,\"rain\":0.22},{\"dt\":1471687200,\"temp\":{\"day\":31.3,\"min\":22.56,\"max\":32.3},\"p ressure\":1018.6,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descriptio n\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.69,\"deg\":180,\"clouds\":16,\"rain\":0.77},{\"dt\":1471773600,\"temp\":{\"day\":31.77,\"min\":21.67,\"max\":30.77},\"pressure\":1016.93,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":2.49,\"deg\":227,\"clouds\":14,\"rain\":2.2}]}";
To ensure that it does not happen again, you can use online tools such as the next https://jsoneditoronline.org/ to validate your future jsons before thinking that you have any error in your code.
One more thing, you could also improve the name of your variable String json_string1 byString jsonString1 to keep java's camel case convention

How do I show my json array of phone numbers in listview alongside other numbers?

I get a JSON Array from the server that consists of some of the phone contacts on the phone of the person who is using my app. I want these phone numbers to be displayed to the user in a ListView as 'Already a contact'.
The JSON Array, called JsonArrayMatchingContacts, might be, for example:
[{"contact_phonenumber":"+12345678"},{"contact_phonenumber":"+23456789},
{"contact_phonenumber":"+34567890"}]
Here's my code, but it's not working. It works for an individual value - for example if I have if (phoneNumberofContact.equals("+12345678")) etc.. it comes up with Already a Contact but I need to have it working for my JSON Array. Can you help?
SelectPhoneContact selectContact = new SelectPhoneContact();
ArrayList<String> MatchingContacts = new ArrayList<String>();
try {
JSONArray Object = new JSONArray(JsonArrayMatchingContacts);
for (int x = 0; x < Object.length(); x++) {
final JSONObject obj = Object.getJSONObject(x);
MatchingContacts.add(obj.getString("contact_phonenumber"));
}
} catch(Exception e) {
e.printStackTrace();
}
if (phoneNumberofContact.equals(MatchingContacts))
{
phoneNumberofContact= "Already a contact";
selectPhoneContacts.add(selectContact);
} else {
selectPhoneContacts.add(selectContact);
}
selectContact.setName(name);
selectContact.setPhone(phoneNumberofContact);
You are comparing a string ( phoneNumberofContact ) with a list ( MatchingContacts ).
You should check if the string is contained in the list.
if (MatchingContacts.contains( phoneNumberofContact )) {
put your if condition in loop..you will get it.try this
SelectPhoneContact selectContact = new SelectPhoneContact();
ArrayList<String> MatchingContacts = new ArrayList<String>();
try {
JSONArray Object = new JSONArray(JsonArrayMatchingContacts);
for (int x = 0; x < Object.length(); x++) {
final JSONObject obj = Object.getJSONObject(x);
if (phoneNumberofContact.equals(MatchingContacts))
{
phoneNumberofContact= "Already a contact";
selectPhoneContacts.add(selectContact);
} else {
selectPhoneContacts.add(selectContact);
}
}
} catch(Exception e) {
e.printStackTrace();
}
selectContact.setName(name);
selectContact.setPhone(phoneNumberofContact);

not getting the specific result json object and how to compare the two string's

i want to get only gender but it shows {"face":[{"gender": {"value": "Male"}}]}
i only want gender
please help me how it solve JSONArray jArray = rst.getJSONArray("face");
for (int i = 0; i < jArray.length(); i++) {
String gender=jArray.getJSONObject(i).getJSONObject("attribute").getString("gender");
String jsonText;
jsonText = gender;
textview2.setText("GENDER" + jsonText);
Check this code:-
Case 1:This code generate only one toast
String result = "{\"face\":[{\"gender\": {\"value\": \"Male\"}}]} ";
try {
JSONArray objJsonArray = new JSONObject(result).getJSONArray("face");
String gender = new JSONObject(objJsonArray.getJSONObject(0).getString("gender")).getString("value");
Toast.makeText(this, "Gender is==>" + gender, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
Case 2:-This code generate two toasts.
String result = "{\"face\":[{\"gender\": {\"value\": \"Male\"}},{\"gender\": {\"value\": \"Female\"}}]}";
try {
JSONArray objJsonArray = new JSONObject(result).getJSONArray("face");
for (int i = 0; i < objJsonArray.length(); i++) {
String gender = new JSONObject(objJsonArray.getJSONObject(i).getString("gender")).getString("value");
Toast.makeText(this, "Gender is==>" + gender, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope it solves your problem
Try this on the last line:
textview2.setText("GENDER" + jsonText.value);
On this line you are getting the entire array:
JSONArray jArray = rst.getJSONArray("face");<br>
A JSONArray is an Array of json objects.
The json object is a name value pair.
It looks like this:
jArray[{name:”John” , gender:”male”},
{name:”jane” , gender:”female”},
{name:”Mike” , gender:”male”}]<br>
This next line loops through the array that you have. Each time pulling a different json object:
1st time through = [{name:”John” , gender:”male”}
2nd time through = {name:”jane” , gender:”female”}
3rd time through = {name:”Mike” , gender:”male”}
for (int i = 0; i < jArray.length(); i++) { String
On the first look i = 0
This following line is saying: retrieve the json data where the name is gender.
This returns {gender:”male”} “gender” being the name, “male” being the value.
gender=jArray.getJSONObject(i).getJSONObject("attribute").getString("gender").value; <br>
String jsonText; jsonText = gender;
textview2.setText("GENDER" + jsonText);
I believe there are other more efficient ways to handle this same code, but I hope this helps none the less.
try {
JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("face");
for(int i=0; i<jsonArray.length(); i++){
String gender = jsonArray.getJSONObject(i).getJSONObject("gender").getString("value");
}
} catch (JSONException e) {
e.printStackTrace();
}
if you have JsonArray length 1 then no need of for loop just replace i with 0

Parsing json array from the JSON object in Android

I am trying to parse a JSON array from a string which I receive from the server.
Example of the array is
{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}
I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = (JSONArray) o.get("data");
Iterator i = ((List<NameValuePair>) slideContent).iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
int title = (Integer)slide.get("id");
String Status = (String)slide.get("status");
String name = (String)slide.get("name");
String number = (String)slide.get("number");
Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
// System.out.println(title);
}
What should be the correct way of parsing it?
It makes sense as a JSONArray cannot be cast to a List<>, nor does it have an iterator.
JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.
So, considering all these, you may wish to write something like this:
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");
for(int i = 0 ; i < slideContent.length() ; i++) {
int title = slideContent.getInt("id");
String Status = slideContent.getString("status");
// Get your other values here
}
you should do like this:
JSONObject o = new JSONObject(result.toString());
JSONArray array = jsonObject.getJSONArray("data");
JSONObject jtemp ;
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;
for(int i=0;i<array.length();i++)
{
mData = new MData();
jtemp = array.getJSONObject(i); //get i record of your array
//do some thing with this like
String id = jtemp.getString("id");
mData.setId(Integer.parseInt(id));
///and other details
dataArray.put(mData);
}
and MData.class
class MData{
private int id;
/....
public void setId(int id){
this.id = id;
}
//.....
}

android how to convert json array to string array

I have an app where I fetch data from server(json) in the form of array & by using the index i used in my app, like below.
JSONObject topobj = new JSONObject(page);
JSONObject innerobj = topobj.getJSONObject("restarutant");
JSONArray phone = innerobj.getJSONArray("phone");
textViewPhone.setText("Phone: " + phone.get(0).toString() + " ,"
+ phone.get(1).toString());
for small size array I can get like this. But when array contains 'n' no of elements and dynamically i have to use this, at that time it required to convert into String Array.
Can anybody tell me how I convert the json array to String array ?
Thank you
This should help you.
Edit:
Maybe this is what you need:
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Assume that you already have JSONArray jsonArray:
String[] stringArray = new stringArray[jsonArray.length()];
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
String jsonString = jsonArray.getString(i);
stringArray[i] = jsonString.toString();
}
catch (JSONException e) {
e.printStackTrace();
}
}
This I think is what you searching for
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
for (int i=0;i<jsonArray.length();i++){
list.add(jsonArray.get(i).toString());
}
I just did this yesterday! If you're willing to use a 3rd party library then you can use Google GSON, with the additional benefit of having more concise code.
String json = jsonArray.toString();
Type collectionType = new TypeToken<Collection<String>>(){}.getType();
Collection<String> strings = gson.fromJson(json, collectionType);
for (String element : strings)
{
Log.d("TAG", "I'm doing stuff with: " + element);
}
You can find more examples in the user guide.
Another elegant kotlin way:
val list = jsonArray.map { jsonElement -> jsonElement.toString() }
And just convert to array if needed
If you are using org.json package, Here is the kotlin way of converting json array to string array.
// get json array
val jsonArray = json.getJSONArray("field")
// convert to string array
val stringArray = Array(jsonArray.length()) { jsonArray.getString(it) }

Categories

Resources