I am trying to populate a Spinner using data from MySQL data base.
public void getData() {
/*To add parameters & values for the request*/
Map < String, String > params = new HashMap < > ();
params.put("Email", sessionemail);
JSONObject parameters = new JSONObject(params);
/*Create ArrayList to store vehicle_id to later get vehicle data from DB Query*/
ArrayList < String > vehicleid = new ArrayList < > ();
ArrayList < String > tagList = new ArrayList < > ();
/*Initialize Json Object Request*/
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, parameters, response - > {
try {
//Parsing the fetched Json String to JSON Object
JSONArray jsonArray = response.getJSONArray("tags");
Log.d(String.valueOf(jsonArray), "JSON DATA");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag = jsonObject.optString("Tag");
String vehicle = jsonObject.optString("Vehicle_Id");
tagList.add(tag);
vehicleid.add(vehicle);
tagidAdapter = new ArrayAdapter < > (Alert.this, android.R.layout.simple_spinner_item, tagList);
tagidAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
tagSpinner.setAdapter(tagidAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}, Throwable::getStackTrace);
/*Adding request to the queue*/
requestQueue.add(jsonObjectRequest);
}
The below is the data I get from my PHP by doing a GET request:
{
"tags": [{
"Tag": "W1C6EZY583DB2907X4A",
"Vehicle_Id": "4"
}, {
"Tag": "6QZL43YEWR6IMMFUING",
"Vehicle_Id": "6"
}, {
"Tag": "STK6WQ8ONDOUMEFSGQF",
"Vehicle_Id": "17"
}, {
"Tag": "93RPHOC8M2AAQ2P2TUX",
"Vehicle_Id": "72"
}, {
"Tag": "UH31KR4F6EFGHJ33S82",
"Vehicle_Id": "73"
}]
}
So basically what I need is to insert the "Tag" values into the Spinner, but for some reason when I get to the jsonObjectRequest the request fails.
Changed to StringRequest and this fixed my issue.
StringRequest strRequest = new StringRequest(Request.Method.POST,
URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag = jsonObject.optString("Tag");
String vehicle = jsonObject.optString("Vehicle_Id");
tagList.add(tag);
vehicleid.add(vehicle);
tagidAdapter = new ArrayAdapter<>(Alert.this, android.R.layout.simple_spinner_item, tagList);
tagidAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
tagSpinner.setAdapter(tagidAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
Related
How can i get the values of a json key in Java here is my code
private void getWebApiData() {
String WebDataUrl = "myjsonfileurl";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("A");
String name = sourceObject.optString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
My json file
{
"books": [
{
"A": [
{
"Amazonite": {
"name": "Amazonite",
"image": "www.google.com"
},
"Amethyst": {
"name": "Amethyst",
"image": "www.google.com"
}
}
],
"B": [
{
"Beryl": {
"name": "Beryl",
"image": "www.google.com"
},
"BloodStone": {
"name": "Bloodstone",
"image": "www.google.com"
}
}
]
}
]
}
What i would like is how to get the values of data under the Alphabet A that is Amazonite and Amethyst and the value of data under Alphabet B but the could i have just give me empty text field nothing no data is being populated.
I have tried with this code but the values retures "null"
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
String name = String.valueOf(articleObject.optJSONObject("A"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am not sure what you really want, but if you just want to get "Amazonite and Amethyst" as you responded under OP, you can try this:
Code snippet
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONArray jsonArrayA = articleObject.getJSONArray("A");
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
System.out.println(obj.names());
obj.names().forEach(e -> {
System.out.println(obj.getJSONObject(e.toString()).get("name"));
});
}
}
Console output
["Amazonite","Amethyst"]
Amazonite
Amethyst
Update
I am not sure which name you want to retrieve because both Amazonite and Amethyst appear two times in JSON array A, so I provide two ways to show them as follows:
List<String> names = new ArrayList<>();
List<String> innerNames = new ArrayList<>();
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
JSONArray keys = obj.names();
for (int k = 0; k < keys.length(); k++) {
String name = keys.getString(k);
String innerName = obj.getJSONObject(keys.optString(k)).getString("name");
System.out.printf("name: %s, inner name: %s\n", name, innerName);
names.add(name);
innerNames.add(innerName);
}
}
System.out.println(names.toString());
System.out.println(innerNames.toString());
Console output
name: Amazonite, inner name: Amazonite
name: Amethyst, inner name: Amethyst
[Amazonite, Amethyst]
[Amazonite, Amethyst]
Response string is like this:
{
"images": [
{
"transaction": {
"status": "success",
"topLeftX": 325,
"topLeftY": 451,
"gallery_name": "Ironman",
"subject_id": "Tony",
"confidence": 0.99414,
"height": 630,
"width": 630,
"face_id": 1,
"quality": 1.75477
},
"candidates": [
{
"subject_id": "Tony",
"confidence": 0.99414,
"enrollment_timestamp": "1487644861022"
},
{
"subject_id": "Tony",
"confidence": 0.99414,
"enrollment_timestamp": "1487644876280"
}
]
}
]
}
I tried this code but not working..
JSONArray arr = new JSONArray(response);
JSONObject jObj = arr.getJSONObject(0);
String status = jObj.getString("status");
String message = jObj.getString("subject_id");
Use json simple lib
JSONObject json = new JSONObject(yourString);
JSONArray images = json.getJSONArray("images");
and you can loop throw this array
for (int i = 0; i < images.length(); i++) {
JSONObject o = images.getJSONObject(i);
....
}
You can use GSON to parse JSON Strings. If you just want the first object of the images array you can use this code:
JsonParser jsonParser = new JsonParser();
JsonObject obj = jsonParser.parse(responseString).getAsJsonObject();
JsonArray images = obj.getAsJsonArray("images");
String subjectId = images.get(0).getAsJsonObject().get("transaction")
.getAsJsonObject().get("subject_id").getAsString();
You can create pojo class for response
Also you can use GSON library for get response string.
use this
#Override
protected void onPostExecute(String result) {
JSONObject jsonobj;
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result != null) {
if (result.equals("failure")) {
Toast.makeText(context, "Check your Username or Password", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {//ths is getting data for vehicl_list_unread_count code, client id,restapi_key
try {
Log.d(TAG, "onPostExecute: this inner of post" + getcontent_for_validate);
jsonobj = new JSONObject(getcontent_for_validate);
System.out.println("this is get content" + jsonobj.toString()); JSONArray array = jsonobj.getJSONArray("images");for (int i = 0; i < array.length(); i++) {
JSONArray transaction = array.getJSONObject(i).getJSONArray("transaction");for (int i = 0; i < array.length(); i++)
String status = transaction.getJSONObject(i).getString("status");
Password = editText_password.getText().toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
dialog.dismiss();
Toast.makeText(context, "Check net connection", Toast.LENGTH_LONG).show();
}
}
You tried
JSONArray arr = new JSONArray(response);
but you should
JSONObject arr = new JSONObject(response);
Because your main json is json object, not JSONArray
I'm getting json from server like in this pattern.
[
{
"Response":[
{
"CategoryID":1,
"CategoryName":"Software",
"Count":1,
"Tasks":[
{
"ATId":17,
"TaskName":"Def",
"TaskId":17,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":2,
"CategoryName":"Hardware",
"Count":5,
"Tasks":[
{
"ATId":3,
"TaskName":"Def",
"TaskId":5,
"TaskDetails":"FGH"
},
{
"ATId":4,
"TaskName":"Def",
"TaskId":6,
"TaskDetails":"FGH"
},
{
"ATId":6,
"TaskName":"Def",
"TaskId":6,
"TaskDetails":"FGH"
},
{
"ATId":11,
"TaskName":"Def",
"TaskId":13,
"TaskDetails":"FGH"
},
{
"ATId":12,
"TaskName":"Def",
"TaskId":14,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":3,
"CategoryName":"Web",
"Count":1,
"Tasks":[
{
"ATId":13,
"TaskName":"Def",
"TaskId":11,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":4,
"CategoryName":"Ios",
"Count":3,
"Tasks":[
{
"ATId":5,
"TaskName":"Def",
"TaskId":7,
"TaskDetails":"FGH"
},
{
"ATId":8,
"TaskName":"Def",
"TaskId":7,
"TaskDetails":"FGH"
},
{
"ATId":15,
"TaskName":"Def",
"TaskId":15,
"TaskDetails":"FGH"
}
]
}
],
"MessageStatus":"Success",
"MessageCode":1
}
]
here I have array of objects which have inner objects also. So I tried to do it and fetched all the data but this is not in a form as i receive from server. All I need is to get a pattern in which i correctly get it. My java code is here.
#Override
public void onResponse(String response) {
ParentItems entryObj = null;
JSONObject jsonObj = null;
JSONArray jsonArr = null;
try {
jsonArr = new JSONArray(response);
// JSONArray js=jsonObj.getJSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
String code = null;
String Message = null;
try {
jsonObj = jsonArr.getJSONObject(0);
code = jsonObj.optString("MessageCode");
Message = jsonObj.optString("MessageStatus");
} catch (JSONException e) {
e.printStackTrace();
}
if (code.equals("1")) {
try {
Utilities.parentItemsList = new ArrayList < > ();
Utilities.childItemsList = new ArrayList < > ();
JSONArray array = jsonObj.getJSONArray("Response");
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
Utilities.parentItemsList.add(entryObj);
JSONArray taskArray = entryJson.optJSONArray("Tasks");
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
Utilities.childItemsList.add(childItems);
}
}
}
} else {
Toast.makeText(getContext(), "business ID is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
i need my show show data in a expandable listview in a pattern that Catagory object will be parent item and task will be child item
In your ParentItems class. Add another attribute like this:
class ParentItems {
...Other attributes
List<ChildItems> childItems;
}
Then in your parser do something like this:
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
entryObj.childItems = new ArrayList<>();
JSONArray taskArray = entryJson.optJSONArray("Tasks");
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
Utilities.childItemsList.add(childItems);
entryObj.childItems.add(childItems);
}
Utilities.parentItemsList.add(entryObj);
}
This way you will get all the children tasks as part of the parent object.
PS. For tasks like this, it's easier to use a library like GSON.
You have to make Two Model Class For This like below.
public class ParentItems{
String CategoryID;
String CategoryName;
String Count;
ArrayList<ChildItems> ChildList;
// Here Constuctor and Getter Setter
}
public class ChildItems{
String ATId;
String TaskName;
String TaskId;
String TaskDetails;
// Here Constuctor and Getter Setter
}
you have to add data like this
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
Utilities.parentItemsList.add(entryObj);
JSONArray taskArray = entryJson.optJSONArray("Tasks");
if(taskArray.length()>0){
ArrayList<ChildItems> list=new ArrayList<>();
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
list.add(childItems);
}
entryObj.setChildList(list);
}
}
For More see this link its help you. Expandable Listview Example
I'm trying to get a JSONArray from JSONObject, but get "Can't create JSONArray" in LogCat.
The error appears here:
JSONArray array = response_object.getJSONArray("post");
Here is my code:
try {
int id;
String author;
String authorUniqueId;
String authorPhotoUrl;
String message;
String createTime;
JSONObject response_object = new JSONObject(response);
JSONArray array = response_object.getJSONArray("post");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
id = jsonObject.getInt("id");
author = jsonObject.getString("author");
authorUniqueId = jsonObject.getString("author_unique_id");
authorPhotoUrl = jsonObject.getString("author_photo_url");
message = jsonObject.getString("message");
createTime = jsonObject.getString("created_at");
Log.e("NewsActivity", "Added:" + author);
data.add(new NewsDataModel(id, author, authorUniqueId, authorPhotoUrl, message, createTime));
}
} catch (Exception e) {
Log.e(TAG, "Can't create JSONArray");
}
And my JSON:
{"error":false}
{"post":[
{
"id":"6",
"author":"NAME..."
"author_unique_id":"ID...",
"message":"MESSAGE...",
"created_at":"TIME...",
"author_photo_url":"URL..."
},
{
"id":"5",
"author":"NAME..."
"author_unique_id":"ID...",
"message":"MESSAGE...",
"created_at":"TIME...",
"author_photo_url":"URL..."
},
{
"id":"4",
"author":"TEXT..."
"author_unique_id":"ID...",
"message":"MESSAGE...",
"created_at":"TIME...",
"author_photo_url":"URL..."
}
]}
I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}
Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}