I am rather new to JSON at the moment, but I need to convert a JSON response that contains the same key, but different values to an ArrayList to use it with my spinner.
I tried it like here: Converting JSONarray to ArrayList
But i get the whole json string, but just need the value part.
I can't figure out how to do this and found no answer that worked for me :/
What I want would be a List like:
City1
City2
City3
But i have in my spinner:
{"city":"name1"}
{"city":"name2"}
{"city":"name3"}
Code I have is:
JSONArray obj = new JSONArray(response);
Spinner availableCitySpin;
availableCitySpin = (Spinner) findViewById(R.id.avCitySp);
List<String> cityValues = new ArrayList<String>();
if (jarr != null) {
for (int i=0;i< jarr.length();i++){
cityValues.add(jarr.getString(i).toString());
}
}
ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cityValues);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
availableCitySpin.setAdapter(cityAdapter);
availableCitySpin.setSelection(0);
Change your code to something like this:
...
for (int i=0;i< jarr.length();i++){
JSONObject cityObject = jarr.getJSONObject(i);
cityValues.add(cityObject.getString("city"));
}
...
Try this:
First use split
For example: String[] result = splits[0].split(":");
you will get two item in array result. result[0]= {"city" and result[1] = "name1"}
If you want to get the key use result[0]
remove sign from result[0] using replace. Example: data = result[0].replace("\"","").replace("{","");
use it in loop, should work
Related
i have String Array like this:
String[] q1={"AAA-BBB","AAA-CCC","AAA-DDD"}
and i want result like this
temp={"BBB","CCC","DDD"}
i tried below code but the result is wrong
for(int i=0;i<q1.length;i++){
ArrayList<String> temp=new ArrayList<>(Arrays.asList(q1[i].split("AAA-")));
}
Try like this:
ArrayList<String> temp=new ArrayList<>();
for(int i=0;i<q1.length;i++){
String[] array = q1[i].split("-");
temp.add(array[1]);
}
You could use substring:
ArrayList<String> temp = new ArrayList<>();
for(int i=0; i<q1.length; i++){
temp.add(q[i].substring(q[i].indexOf('-') + 1, q[i].length()))
}
you find error Because you use split
Splits this string around matches of the given regular expression.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
q1[i].split("AAA-")
in this line you got 2 result splited 0 = "" AND 1 = "BBB"
so you need to pick the sec result
you have multi Solution
like https://stackoverflow.com/a/50234408/6998825 said
String[] array = q1[i].split("-");
temp.add(array[1]);
//change this q1[i].split("AAA-") to
q1[0].substring(4)
if your AAA- is not going to change
Have you tried creating the ArrayList outside of the loop? As previously you were creating a new ArrayList for every element in your string array
ArrayList<String> temp = new ArrayList<>();
for(int i=0;i<q1.length;i++){
temp.add(q1[i].substring(4);
}
Assuming that "AAA-" is not going to change.
I have a class called GradeModel2 that has 2 members: grade (as string) and sections (as list of strings). I am trying to get my GradeModel2s data from a json string that I've read from a server.
List<GradeModel2> gradeList = new ArrayList<>();
List<String> sectionsList = new ArrayList<>();
JSONObject jo = new JSONObject(json);
JSONArray grades = jo.getJSONArray("grades");
for (int i=0;i<grades.length();i++){
sectionsList.clear();
JSONObject grade = grades.getJSONObject(i);
JSONArray sections = grade.getJSONArray("sections");
Log.e("length",sections.length()+"");
for (int k=0;k<sections.length();k++)
sectionsList.add(sections.getString(k));
gradeList.add(new GradeModel2(grade.getString("grade"), sectionsList));
}
/**************/
for (GradeModel2 grade : gradeList) {
List<String> ss = grade.getSections();
for (String s : ss)
Log.e("section",grade.getGrade()+" : "+s);
}
/**************/
The retrieved json string looks like the following:
{"id":"596","privileges":"T","grades":[{"grade":"1","sections":["A","B","C"]},{"grade":"3","sections":["A","B"]},{"grade":"7","sections":["A"]},{"grade":"9","sections":["B"]},{"grade":"10","sections":["A"]}]}
The problem is that the sections list of all GradeModel2 objects is of length 1 and value A !!!
the first Log.e, one line before the inner for loop, shows that the length of the first item of the list is 3 (A,B, and C (see the json)). However, I am trying to print all the sections of each GradeModel2 object in the inner for loop in the second block, but all I see section A for all the grades!!! (see the pic)
the result of the two Log.e
What is going on? Why is this happening?
Your problem is in sectionsList. You are trying to reuse same object, so this line of code new GradeModel2(..., sectionsList); will just add reference to the same sectionsList. And because of sectionsList.clear(); you see "A" from last json section ({"grade":"10","sections":["A"]}) To fix this, you have to create new array each time in your for loop. Something like this:
for (int i = 0 ; i < grades.length() ; i++){
List<String> sectionsList = new ArrayList<>();
// ... your json code here
gradeList.add(new GradeModel2(grade.getString("grade"), sectionsList));
}
Can anybody please explain me how to set two items of the same category at a time from json into android dropdown(Spinner) using adapter.
josn data:
{"categories":[{"id":"1","name":"Beverages"},{"id":"2","name":"Bread"},{"id":"3","name":"Cereals"},{"id":"4","name":"Cheese"},{"id":"5","name":"Citrus Fruits"}]}
Following is code I'am using to set only one item into spinner:
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Firstly you need to parse your json for that json response convert into string
ArrayList<String> list =new ArrayList<String>();
String response ={"categories":[{"id":"1","name":"Beverages"},{"id":"2","name":"Bread"},{"id":"3","name":"Cereals"},{"id":"4","name":"Cheese"},{"id":"5","name":"Citrus Fruits"}]}
JSONObject resJsonObj =new JSONObject(response);
JSONArray arrayData=resJsonObj.getJSONArray("categories");
for (int i = 0; i < arrayData.length(); i++) {
temp="";
JSONObject arrayObj = arrayData.getJSONObject(i);
temp=arrayObj.getString("name");
//temp=arrayObj.getString("id");
list.add(temp);
}
This list pass in your array adapter as You need
you can also make a Array list generic type according to your bean class if you
want to get all element from json id
Hi im wanting to create an array of all the keys in a JSONObject. my understanding (please correct me if i'm wrong) is that i need to convert the JSONObject to a Map and then create an Array from this does anyone know how to do this?
No need to convert JSONObject to a Map and then create an Array of keys just use JSONObject.names() for getting all keys in an JsonArray then convert it to Array or ArrayList. example:
JSONObject json = new JSONObject("json object string");
JSONArray namearray=json.names(); //<<< get all keys in JSONArray
Try this:
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
String[] array = list.toArray(new String[list.size()]);
This might be a simple Java issue I'm struggling with but I'm looking to the community to assist me here as I have hit a brick wall with this situation.
I successfully have data coming in off of a MySQL database and brought to the application through JSON. During parsing I was trying to create another array to be passed onto an ArrayAdapter to be used in a ListView. Here is the code I'm having an issue with:
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
Games game_data[] = new Games[]
{
new Games(ct_id, ct_name)
};
}
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
This line: GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
More specifically the game_data is highlighted red in Eclipse. Where I am curious is why does game_data get out of reach after end of loop? I'm just trying to add specific fields within the row from JSON to the adapter here.
I also tried going through the loop within setting up the array but still no dice as new Games[] gets an error. Here is an example:
Games game_data[] = new Games[]
{
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
// Games game_data[] = new Games[]
// {
new Games(ct_id, ct_name);
// };
}
error: Variable must either provide dimension expressions or array initializer.
Hope this helps...
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
Games game_data[];
game_data[] = new Games[jArray.length()];
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
game_data[i] = new Games(ct_id, ct_name);
}
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
I am thinking that Games is your POJO class so you can better do something like this,
Create a List of the POJO class
private List<Games> games= new ArrayList<Games>();
Now you can add your content in the games list.
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
games.add(new Games(ct_id, ct_name));
}
And finally pass the list in the Adapter.
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, games);
error: Variable must either provide dimension expressions or array initializer.
=> This error is obvious because you haven't define any dimensions value to create an array and also haven't passed any initialization to this array.
So I think you are doing wrong, instead do it like:
Games game_data[] = new Games(ct_id, ct_name);
This is the correct way to call a constructor.
And i don't know what you have written inside the Games class so i just have mentioned about the calling of constructor.