How to add values to a string array in android - android

I have a problem with my code,
I have a json array
[{"Response":{"data":"sibin1"}},{"Response":{"data":"sibin2"}},
{"Response": {"data":"sibin3"}}]
And iam trying to extract the json data using the below code,Here i added only some parts of the coode
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
for (int i = 0; i < finalResult.length(); i++)
{
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
System.out.println(result);
}
The code is worked very well
when the value of
i=0 ,result is sibin1
i=1 ,result is sibin2
i=2 ,result is sibin3
But my problem is , i need to store the result in a string array of length finalresultlength inside the given for loop, also i need to print the values in the string array in a for loop outside the given for loop
if anybody knows please help me...........

You could do this way as well.
Create an ArrayList of size 'finalresultlengt' and the add the values in.
list.add(result); // variable 'result' in your case is the value from JSON
If you have more values to be added, create a POJO class.
class POJO {
private String dataVal;
public void setDataVal(String dataVal) {
this.dataVal = dataVal;
}
public String getDataVal() {
return dataVal;
}
}
Then create an ArrayList of type POJO.
ArrayList<POJO> list = new ArrayList<POJO>(finalresultlengt);
EDIT
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
ArrayList<String> list = new ArrayList<String>(finalresultlengt);
for (int i = 0; i < finalResult.length(); i++) {
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
list.add(result);
}
Populate values from ArrayList.
for(String value : list)
System.out.println(value);

Related

How To store json values in a set of arrays in android

i have a json file like so :
http://da.pantoto.org/api/files
i want to store these values in variables to be used later. The values should be stored in some String array variables like id[], uploadDate[], url[].
i can find examples using ListView and ArrayAdapter. but thats not what i really want. Anyone can help??
This is only an example to show how you can get the values from JSON. You need to store these values as you need.
JSONObject jsonObject = new JSONObject("your response");
JSONArray filedetails = jsonObject.getJSONArray("files");
for(int i=0; i<filedetails.size();i++){
String id = filedetails.get(i).getString("id");
JSONArray tagsdetails= filedetails.get(i).getJSONArray("tags");
for(int i=0; i<tagsdetails.size();i++){
//fetch values in it
}
}
You can't do it exactly that way, You have to iterate trough the array and get each object properties individually and then if you want you could create an array to store each object property.
//From the example: http://da.pantoto.org/api/files
JSONArray files = null;
//Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://da.pantoto.org/api/files", ServiceHandler.GET);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
files = jsonObj.getJSONArray("files");
//YOUR NEW ARRAY
String[] ids = new String[20];
String[] urls = new String[20];
//etc
//looping through All files
for (int i = 0; i < files.length(); i++) {
JSONObject c = files.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
//etc
//HERE IS WHAT YOU COULD DO OPTIONALLY IF YOU WANT HAVE IT ALL ON A SINGLE ARRAY WITHOUT OBJECTS:
ids[i] = id;
urls[i] = url;
//etc
}
this is a simple way to do this. see i also done this kind of string array and later use
try {
JSONObject jObj = new JSONObject(strDocketListResponse);
JSONArray jsonArray = jObj.getJSONArray("GetManifestDocketListResult");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject detailsObject = jsonArray.getJSONObject(i);
String strDktNo = detailsObject.getString("Docketno");
String strDocketDate = detailsObject.getString("DocketDate");
String strOrigin = detailsObject.getString("Origin");
String strDestination = detailsObject.getString("Destination");
String[] strDocketNoDkt = new String[]{strDktNo};
String[] strDocketDateDkt = new String[]{strDocketDate};
String[] strDocketOriginDkt = new String[]{strOrigin};
String[] strDocketDestnDkt = new String[]{strDestination};
for (int sanjay = 0; sanjay < strDocketNoDkt.length; sanjay++) {
ItemCheckList itemCheckList = new ItemCheckList();
itemCheckList.setDocket_NO(strDocketNoDkt[sanjay]);
itemCheckList.setDocket_Date(strDocketDateDkt[sanjay]);
itemCheckList.setDocket_Origin(strDocketOriginDkt[sanjay]);
itemCheckList.setDocket_Destination(strDocketDestnDkt[sanjay]);
checkLists.add(itemCheckList);
}
checkAdapter = new ItemCheckAdapter(ActivityManifestEntry.this, checkLists, check_all);
manifestListView.setAdapter(checkAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}

How to convert the json array to string array in android?

I am converting an json array to string array thats doesn't exist any tag. I tried with all tricks but not succeeded.
json array:-
"validValues":["01_Abacus","02_AlarmClock","03_Basketball","04_Beaker","55_Watch"]
Code for convert the json array to string values
if (jsonComponentObj.has(TAG_VALID_VALUES)) {
String value = jsonComponentObj.getString(TAG_VALID_VALUES);
Logs.e("value " + value);
if (!value.equals("null")) {
JSONArray jsonArray = jsonComponentObj
.getJSONArray(TAG_VALID_VALUES);
if (jsonArray != null) {
ArrayList<String> stringArray = new ArrayList<String>();
for (int j = 0; j < jsonArray.length(); j++) {
try {
JSONObject jsonObject = jsonArray
.getJSONObject(j);
stringArray.add(jsonObject.toString());
} catch (JSONException e) {
Logs.e("Exception: "+e.toString());
e.printStackTrace();
}
}
}
}
}
Exception:
org.json.JSONException: Value 01_Abacus at 0 of type java.lang.String cannot be converted to JSONObject
If anyone have idea. Please reply. Thanks in advance..
Because validValues JSONArray contain only Strings instead of JSONObject.so get all values from JSONArray as:
for (int j = 0; j < jsonArray.length(); j++) {
String str_value = jsonArray.optString(j);
stringArray.add(str_value);
}
Your json array contains Strings not json object.Therefore to get Strings from json array directly use getString(),So
Change
JSONObject jsonObject = jsonArray.getJSONObject(j);
stringArray.add(jsonObject.toString());
to
stringArray.add(jsonArray.getString(j));
or
stringArray.add(jsonArray.optString(j));
You should use optString(int) to coerce a string value from array. Using getString(int) would cause problems if ever the values in the array were not strings.
for (int j = 0; j < jsonArray.length(); j++) {
String value = jsonArray.optString(j);
stringArray.add(value);
}
If you want to give a default value, use optString(int, String).
try JSONObject jsonObject = jsonArray.getString(j);
instead of JSONObject jsonObject = jsonArray.getJSONObject(j);

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;
}
//.....
}

Parse simple JSON Array without key

I need help with parsing simple JSONArray like this:
{
"text":[
"Morate popuniti polje tekst."
]
}
I have tried with this but I failed:
if (response_str != null) {
try {
JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");
for (int i = 0; i < arrayJson.length(); i++) {
JSONObject obj = arrayJson.optJSONObject(i);
error = obj.getString("text");
}
}
Your JSONArray is an array of Strings. You can iterate this way
JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");
for (int i = 0; i < arrayJson.length(); i++) {
String error = arrayJson.getString(i);
// Do something with each error here
}
You have a JSONArray text. There is no array of JSONObject.
{ // Json object node
"text":[ // json array text
"Morate popuniti polje tekst." // value
]
}
Just use
for (int i = 0; i < arrayJson.length(); i++) {
String value = arrayJson.get(i);
}
In fact there is no need for a loop as you have only 1 element in json array
You can just use
String value = (String) arrayJson.get(0); // index 0 . need to cast it to string
Or
String value = arrayJson.getString(0); // index 0
http://developer.android.com/reference/org/json/JSONArray.html
public Object get (int index)
Added in API level 1
Returns the value at index.
Throws
JSONException if this array has no value at index, or if that value is the null reference. This method returns normally if the value is JSONObject#NULL.
public boolean getBoolean (int index)
getString
public String getString (int index)
Added in API level 1
Returns the value at index if it exists, coercing it if necessary.
Throws
JSONException if no such value exists.
Try this:
JSONObject jsonObject = new JSONObject(response_str);
JSONArray arrayJson = jsonObject.getJSONArray("text");
String theString = arrayJson.getString(0);

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