I am using the andriod volley library to get some array of data i want to convert the data into a string but when i tried doing this am only able to get the last data in the array when they are up to ten names only the last name is been converted to string.Here is the code i am using i want to get all the name in as string separated by comma
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
response -> {
try {
JSONArray jsonArray = response.getJSONArray("users");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("name");
ArrayList<String> artistClassArrayList3 = new ArrayList<String>();
artistClassArrayList3.add(name);
StringBuilder sbString = new StringBuilder("");
for(String language : artistClassArrayList3){
sbString.append(language).append(", ");
}
String strList = sbString.toString();
if( strList.length() > 0 )
strList = strList.substring(0, strList.length() - 1);
textView.setText(strList);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error J :: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}, error -> Toast.makeText(getApplicationContext(), "Error R:: " + error.getMessage(), Toast.LENGTH_SHORT).show());
Related
I am trying to get a list of available numbers from the following json object
void doJSONParser(String str)
{
try {
JSONObject order = new JSONObject(str);
JSONArray index = order.getJSONArray("webnautes");
for(int i = 0; i < index.length(); i++)
{
JSONObject tt = index.getJSONObject(i);
name += "name: " + tt.getString("name")+"\n";
phone = new String[tt.getString("phone").length()];
//phone += "phone: " + tt.getString("phone")+"\n";
}
Log.d("JSON DATA:", name);
Log.d("JSON DATA:", phone.toString());
}
catch (JSONException e)
{
e.printStackTrace();
Log.d("JSON ERROR", e.getLocalizedMessage());
}
}
Try this
JSONArray phoneJson = tt.getJSONArray("phone");
String[] arr = new String[phoneJson.length()];
for(int i = 0; i < phoneJson.length(); i++)
arr[i] = phoneJson.getString(i);
I am getting null pointer error while converting string to json object i have tried gson,parser etc but none seems to be working.
Can somebody provide a solution for below response (I have done substring in order to remove "data: "):
data: {
"C": "abc",
"A": [{
"B": "BcastHub",
"C": "onData",
"D": [{
"ID": "1",
"One": [{
"Plus": 5.0,
"Minus": 93400.0
}, {
"Plus": 4.9,
"Minus": 8570.0
}, {
"Plus": 4.8,
"Minus": 140606.0
}],
"Two": [{
"Plus": 5.1,
"Minus": 34.0
}, {
"Plus": 5.2,
"Minus": 44622.0
}, {
"Plus": 5.3,
"Minus": 2408.0
}]
}]
}]
}
My code for Fetching
try{
URL urlData = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlData.openConnection().getInputStream(), "utf-8"));
String struct = reader.readLine();
while ((struct = reader.readLine()) != null ) {
if(!struct.equals("")) {
struct = struct.substring(6,struct.length());
JSONParser parser = new JSONParser();
JSONObject lev1 =(JSONObject) parser.parse(struct);
//JSONObject lev1 = (JSONObject) obj;
JSONObject parent = (JSONObject) lev1.get("A");
for(int j=0;j<parent.length();j++) {
JSONObject child1 = (JSONObject) parent.get("D");
JSONArray child2 = (JSONArray) child1.get("One");
for (int i = 0; i < child2.length(); i++) {
JSONObject item = child2.getJSONObject(i);
final String plus = item.getString("Plus");
final String minus = item.getString("Minus");
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Plus => " + plus + "Minus = > " + minus);
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Tell me if you want anything else. Thanks.
Edit : I am trimming the start of the string in order to make it in proper format and then converting the string to JSONObject is giving me error. at JSONObject parent = (JSONObject) lev1.get("A"); as lev1 is null.
try {
jsonResponse = new JSONObject(strJson2);
JSONObject user = jsonResponse.getJSONObject("data");
num = user.getString("C");
JSONArray user1 = user.getJSONArray("A");
for (int i = 0; i < user1.length(); i++) {
jsonChildNode = user1.getJSONObject(i);
String B = jsonChildNode.getString("B");
String c2 = jsonChildNode.getString("C");
Toast.makeText(this, B + "::" + c2.toString(), Toast.LENGTH_SHORT).show();
JSONArray jsonArraysunject = jsonChildNode.getJSONArray("D");
for (int j = 0; j < jsonArraysunject.length(); j++) {
JSONObject DD = jsonArraysunject.getJSONObject(j);
String dd = DD.getString("ID");
Toast.makeText(this, dd.toString(), Toast.LENGTH_SHORT).show();
One = DD.getJSONArray("One");
for (int k = 0; k < One.length(); k++) {
// for (int i = 0; i < lengthJsonArr; i++) {
jsonChildNodeo = One.getJSONObject(k);
type = jsonChildNodeo.getString("Plus");
num = jsonChildNodeo.getString("Minus");
makeText.add("Plus - " + type);
makeText.add("Minus - " + num);
Toast.makeText(this, makeText.toString(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "hdjeh", Toast.LENGTH_SHORT).show();
Two = jsonChildNodeo.getJSONArray("Two");
Toast.makeText(this, Two.toString(), Toast.LENGTH_SHORT).show();
for (int r = 0; r < Two.length(); r++) {
JSONObject tw = Two.getJSONObject(r);
String tplus = tw.getString("Plus");
String tminus = tw.getString("Minus");
makeText2.add("plus - " + tplus);
makeText2.add("minus - " + tminus);
Toast.makeText(this, makeText2.toString(), Toast.LENGTH_SHORT).show();
// }
}
}
Just place your json data in jsonString vairable and that's all.
try {
JSONObject mainObject=new JSONObject(jsonString);
System.out.println(mainObject.toString());
System.out.println("// First Level object(s)");
System.out.println("C--> "+mainObject.getString("C"));// First Level object C
JSONArray firstArray=mainObject.getJSONArray("A");
for(int i=0;i<firstArray.length();i++){ //First Level Array A
JSONObject arrayObject =firstArray.getJSONObject(i);
System.out.println("// Second Level object(s)");
System.out.println("B--> "+arrayObject.getString("B")); // Second Level Object B
System.out.println("C--> "+arrayObject.getString("C")); // Second Level Object C
System.out.println("//Second Level Array D");
JSONArray secondLevelArray=arrayObject.getJSONArray("D");
for(int j=0;j<secondLevelArray.length();j++){
JSONObject innerArrayObject=secondLevelArray.getJSONObject(j);
System.out.println("// Third Level object(s) ");
System.out.println("ID --> "+innerArrayObject.getString("ID"));
JSONArray thirlLevelArray1=innerArrayObject.getJSONArray("One");
for(int k=0;k<thirlLevelArray1.length();k++){
JSONObject innerMostObjects=thirlLevelArray1.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
JSONArray thirlLevelArray2=innerArrayObject.getJSONArray("Two");
for(int k=0;k<thirlLevelArray2.length();k++){
JSONObject innerMostObjects=thirlLevelArray2.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I parsed your data using Gson. The advantages of Gson are discussed previously. In addition, you can check goals of Gson.
Here is how to parse your data using Gson:
Note that I have not used code formatting standards (for example, the name of a class should use CamelCase) because you couldn't share real data.
Extracting JSON string:
While extracting JSON string use indexOf(int) instead of hard-coded 6.
jsonString = jsonString.substring(jsonString.indexOf("{"));
Parsing:
Gson gson = new Gson();
data d = gson.fromJson(reader, data.class);
for (a a1 : d.A) {
for (plusminus pm : a1.D[0].One) {
System.out.println("Plus => " + pm.Plus + " Minus => " + pm.Minus);
}
}
Required Classes:
public class data {
public String C;
public a A[];
}
public class a {
public String B;
public String C;
public d D[];
}
public class d {
public int ID;
public plusminus One[], Two[];
}
public class plusminus {
public double Plus;
public double Minus;
}
I have his json and i need to retrieve array of images from images Variable..
this my json :
{
id: 215,
title: " this is title",
image: "1464958558.jpg",
description: "description",
images: "["1464958558.jpg","1464958559.jpg","1464958561.jpg","1464958563.jpg","1464958564.jpg","1464958568.jpg","1464958569.jpg","1464958570.jpg","1464958573.jpg","1464958574.jpg"]",
user_name: "user name",
telephone: "0123456789"
}
i want to retrieve this images array and display it in grid view... and i can't find any response in logcat
my doInBackGround()
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
ID = mCursor.getString(ArticleLoader.Query._ID);
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + String.valueOf(Config.BASE_URL));
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
GridItem item;
item = new GridItem();
Log.i(TAG, "parseResult: " + jsonObj);
for (int i = 0; i < jsonObj.length(); i++) {
// if (response != null) {
String images = jsonObj.getString("images");
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
dose i retrieve data correctly ?
Is images json object string or json array? In your code is string.
If WebService changes are possible, request to given you a json array of images, this is best practice.
If not possible you must parse json image object with regex.
No your doing wrong just try below code
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
for(int i=0;i<arrayObj.length();i++)
{
String item = arrayObj.getString(i);
// now you use item string where you want
}
} catch (JSONException e) {
e.printStackTrace();
}
images should be a JSONArray, and hence you can do that to parse it (inside your for loop!):
JSONArray imagesJSON = jsonObj.getJSONArray("images");
for(int k = 0 ; k<imagesJSON.length() ; k++){
String image = imagesJSON.getString(k);
item.setImage(IMAGE_LINK + image);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + image);
mGridData.add(item);
}
I have a contacts which is in the form of JSON. Now I want to decode them into String array. There are two arrays; names and phones. I'm using this code:
String[] names;
String[] phones;
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
JSONObject jsonObject = new JSONObject(jsonArray.toString());
Log.i("INFO", String.valueOf(jsonObject.length()));
} catch (JSONException e) {
e.printStackTrace();
}
This generates an error. How can I add all names in names array and all phones in phones array. Like names[0] is assigned A which is a first name and phones[0] assigned 911 which is first phone number corresponding to first name. How can I do that, I'm new in android?
The problem is in this line
JSONObject jsonObject = new JSONObject(jsonArray.toString());
you are trying to convert JSONArray in JSONObject , which you can't. if you want to access JSONObject inside of JSONArray you have to loop through each, or you can get specific object by it's index.
String[] names;
String[] phones;
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
phones = names = new String[jsonArray.length()];
for(int i = 0 ; i < jsonArray.length(); i ++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
names[i] = jsonObject.getString("name");
phones[i] = jsonObject.getString("phone");
Log.i("INFO", "name : " + jsonObject.getString("name") + " , phone : " + jsonObject.getString("phone"));
}
} catch (JSONException e) {
e.printStackTrace();
}
You can't convert json arrya to json object like that:
try {
JSONArray jsonArray = new JSONArray(test);
for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Your code goes here..
}
} catch (JSONException e) {
e.printStackTrace();
}
here is the required code.
ArrayList<String> names = new ArrayList<>();
ArrayList<String> phones = new ArrayList<>();
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String phone = jsonObject.getString("phone");
names.add(name);
phones.add(phone);
Log.i("INFO", name + ", " + phone);
}
} catch (JSONException e) {
e.printStackTrace();
}
above you have used simple arrays they can store data only of fixed size. But arrayList and List can store data of variable size or you do not need to fix their size.
I set a column data type to CURRENT_TIMESTAMP in my table . It successfully saved current time.
2016-06-28 11:00:44 // it's actual mysql data
But when i parse it from Using GSON android i got the date string like
2016-06-28T06:09:54.000Z // parsed from json
That means space is alter with T & Z . how i remove these two field ?
My parsing Data is Like
Gson gson = new Gson();
String json = gson.toJson(args);
JSONArray test = new JSONArray(json);
Log.i("user registration", json);
//JSONArray jsonArray = new JSONArray(args);
//String aa = jsonArray.getString(0).toString();
//String aa = jsonArray.getString(0).toString();
// Log.i("user registration", aa);
String aa = test.getString(0).toString();
JSONObject jsonObject = test.getJSONObject(0);
JSONArray valueArrays = jsonObject.getJSONArray("values");
// // // // Log.e("email",newArr.getJSONObject(0).getString("email"));
for (int i = 0; i < valueArrays.length(); i++) {
JSONObject jo = valueArrays.getJSONObject(i);
String nvp = jo.getString("nameValuePairs");
jo = new JSONObject(nvp);
User user = new User();
String name = jo.getString("user_name");
user.setUserName(name);
if (name.equalsIgnoreCase(mUsername)) {
Log.i("user_matched", "I am " + mUsername);
continue;
}
user.setEmail(jo.getString("email"));
user.setSocket_id(jo.getString("socket_id"));
user.setLastSeen(jo.getString("last_seen"));
if (jo.getString("status") == "1") {
user.setStatus("online");
} else
user.setStatus("offline");
mUserList.add(user);
}
I just replace the Extra character from Date String .
Date rightFormatDateFromList(String formatted_date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
try {
Log.e("Wrong Format", "" + formatted_date);
formatted_date = formatted_date.replace('T', ' ');
formatted_date = formatted_date.replace(".000Z", "");
Log.e("Right Format", "" + formatted_date);
return dateFormat.parse(formatted_date);
} catch (Exception w) {
return null;
}
}
the Log Wrong Format: 2016-06-29T09:11:34.000Z
Right Format: 2016-06-29 09:11:34