How to get single row data from json response in android - android

Hello I am new to android,working on a snippet where I am getting my json data as
{"students":[{"id":"26","name":"aaa","abbr":"A"},{"id":"27","name":"bbb","abbr":"B"},{"id":"28","name":"ccc","abbr":"C"}]}
I want to get this record as single row, like id=26,name="aaa",abbr="A"
JSONObject json;
JSONArray jsonarray_student;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
jsonarray_student = json.getJSONArray("students");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("name", json.getString("name"));
map.put("abbr", json.getString("abbr"));
arraylist.add(map);
map will give me all id's all name's and all abbr's
Do i need to store them in List iterate???

Try this way,hope this will help you to solve your problem.
String response = "{\"students\":[{\"id\":\"26\",\"name\":\"aaa\",\"abbr\":\"A\"},{\"id\":\"27\",\"name\":\"bbb\",\"abbr\":\"B\"},{\"id\":\"28\",\"name\":\"ccc\",\"abbr\":\"C\"}]}}";
try{
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
JSONObject responeJsonObject = new JSONObject(response);
JSONArray studentsJsonArry = responeJsonObject.getJSONArray("students");
for (int i=0;i<studentsJsonArry.length();i++){
HashMap<String, String> studentData = new HashMap<String, String>();
studentData.put("id", studentsJsonArry.getJSONObject(i).getString("id"));
studentData.put("name", studentsJsonArry.getJSONObject(i).getString("name"));
studentData.put("abbr", studentsJsonArry.getJSONObject(i).getString("abbr"));
studentList.add(studentData);
}
for (HashMap<String,String> student : studentList){
System.out.print("id"+student.get("id"));
System.out.print("name"+student.get("name"));
System.out.print("abbr"+student.get("abbr"));
}
}catch (Throwable e){
e.printStackTrace();
}

Yes there is a way for you to get in one line and my favorite is the use of the Gson Libray which will allow you to parse your string and get a list of object "Students" (List) where you then only need to do :
TextView id = (TextView) findViewById(R.Id.textview);
TextView name = (TextView) findViewById(R.Id.textview);
TextView abbr = (TextView) findViewById(R.Id.textview);
id.setText(student.getId());
name.setText(student.getName());
abbr.setText(student.getAbbr());
Where student is an entry in the List
Hope this can help you out with your problem =)

Related

How to output json to a single textview not in a listview

kinda new to android. I am outputing json to a listview and it is working, now my problem is how do i output a single textview that is not in a listview?
Here is my code
private void showResult1(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String ss_update_time = jo.getString(Config.TAG_ss_update_time);
HashMap<String,String> match = new HashMap<>();
match.put(Config.TAG_ss_update_time, ss_update_time);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
Standings.this, list, R.layout.standings,
new String[]{Config.TAG_ss_update_time},
new int[]{ R.id.ss_update_time});
TextView.setAdapter(adapter);
}
I dont know what to change in the setAdapter. It just gives me a red error
You have to convert your JSON response into a String and then set it in your textView. It may look like this.
TextView yourTextView = (TextView) findViewById(R.id.your_textview);
StringBuilder stringBuilder = new StringBuilder();
for (HashMap<String, String> elementInList : list) {
for (String value : elementInList.values()) {
stringBuilder.append(value);
}
}
textView.setText(stringBuilder.toString());
Long story short: ListAdapter is an object used to work with ListView. You don't need to create List Adapter to display Json string using TextView.
So to show String output you just need to do this:
TextView.setText(some_string_variable);
Hope I have understood you correctly.

how to parse JSONArray in android NullPointerException

I want to parse jsonObject passed by another activity
intent.putextra("result", json.toString());
It shows everything right with name, branch and session. but it shows NullPointerException while fetching array. at here
mSubList.add(map);
this array has 6 rows.
this is my code. please tell me exactly where Im wrong.
JSONObject json;
ListView sub_list;
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mSubList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_page);
name = (TextView)findViewById(R.id.name_roll);
branch= (TextView)findViewById(R.id.branchname);
session = (TextView)findViewById(R.id.Session);
sub_list = (ListView)findViewById(R.id.sub_list);
try {
json = new JSONObject(getIntent().getStringExtra("result"));
name.setText(json.getString("REGNO")+" - "+json.getString("STUDENTNAME"));
branch.setText(json.getString("BRANCHNAME"));
session.setText(json.getString("SESSIONNAME"));
mComments = json.getJSONArray("DATA");
// looping through all subjects according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String code = c.getString("CCODE");
String subject = c.getString("COURSENAME");
String passfail = c.getString("PASSFAIL");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put("CCODE", code);
map.put("COURSENAME", subject);
map.put("PASSFAIL", passfail);
// adding HashList to ArrayList
mSubList.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mSubList,
R.layout.singlesubject, new String[] { "CCODE", "COURSENAME",
"PASSFAIL" }, new int[] { R.id.sub_id, R.id.sub_name,R.id.sub_res });
sub_list.setAdapter(adapter);
}catch(Exception e){
e.printStackTrace();
}
}
}
if I want to change each listitem background(R.layout.singlesubject) if "PASSFAIl"=P then Green color else Red color. then what changes i have to do ?
mSubList.add(map);
this line of code is failing because you do not initialize the array before adding the map
You can initialize it by using...
mSubList = new ArrayList<Hashmap<String, String>>();
init your mSubList before add item
mSubList = new ArrayList<HashMap<String, String>>();
I think you forgot to initialize mSubList before adding data to it:
mSubList = new ArrayList<HashMap<String, String>>();

Create JSON android

I want to have an output like this
{"content":{
"A":["a1","a2","a3"],
"B":"b1String",
"C":["c1","c2"]}}
As of now, I am getting this.
{"content":{
"A":"[a1, a2, a3]",
"C":"[c1, c2]",
"B":"b1String"}}
Below is my code
Map <String, Object> myMap = new HashMap<String, Object>();
myMap.put("A",arrayOfA); //which is ArrayList<String>
myMap.put("B", myB1String);//which is String
myMap.put("C", arrayOfC);//which is ArrayList<String>
JSONObject jsonAll = new JSONObject(myMap);
Map <String, Object> mapAll = new HashMap<String, Object>();
mapAll.put("content", jsonAll);
JSONObject finalObject=new JSONObject(mapAll);
Log.e("JSON", finalObject.toString());
Any help woulld be much appreciated. Thanks
If you want to display it in an array then you need to add all your string arrays in a JSONArray and add it to the object to display it as an array.
sample:
JSONArray s2 = new JSONArray();
s2.put("a1");
s2.put("a2");
s2.put("a3");
myMap.put("A",s2); //which is ArrayList<String>
myMap.put("B", "b1String");//which is String
myMap.put("C", s2);
//which is ArrayList<String>
JSONObject jsonAll = new JSONObject(myMap);
Map <String, Object> mapAll = new HashMap<String, Object>();
mapAll.put("content", jsonAll);
JSONObject finalObject=new JSONObject(mapAll);
Log.d("JSON", finalObject.toString());
result:
{"content":{"A":["a1","a2","a3"],"B":"b1String","C":["a1","a2","a3"]}}
Try this way,hope this will help you to solve your problem.
String[] stringArrayOfA = new String[]{"a1","a2","a3"};
String[] stringArrayOfC = new String[]{"c1","c2"};
try {
JSONArray jsonArrayA = new JSONArray();
for (String str : stringArrayOfA){
jsonArrayA.put(str);
}
JSONArray jsonArrayC = new JSONArray();
for (String str : stringArrayOfC){
jsonArrayC.put(str);
}
JSONObject innerJsonobject = new JSONObject();
innerJsonobject.put("A",jsonArrayA);
innerJsonobject.put("B","b1String");
innerJsonobject.put("C",jsonArrayC);
JSONObject outerJsonObject = new JSONObject();
outerJsonObject.put("content",innerJsonobject);
Log.e("JSON", outerJsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Result :{"content":{"A":["a1","a2","a3"],"B":"b1String","C":["c1","c2"]}}

Android: How to sort data for ListView?

I have some JSON data I am pulling down from a server. One of the fields in this data is a distance value. I need to have the data sorted by distance from lowest to highest in the ListView. I am not sure how to go about doing this?
Any help appreciated.
This is my code to grab the data not sure how to get it sorted properly?
// Hashmap for ListView
ArrayList<HashMap<String, String>> bathroomList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_search);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
bathrooms = json.getJSONArray(TAG_BATHROOMS);
// looping through All Contacts
for(int i = 0; i < bathrooms.length(); i++){
JSONObject c = bathrooms.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String access = c.getString(TAG_ACCESS);
String city = c.getString(TAG_CITY);
String comment = c.getString(TAG_COMMENT);
String directions = c.getString(TAG_DIRECTIONS);
String name = c.getString(TAG_NAME);
String street = c.getString(TAG_STREET);
String bathroomtype = c.getString(TAG_BATHROOMTYPE);
String distance = c.getString(TAG_DISTANCE);
String distanceTrimmed = distance.substring(0,4) + " " + "miles away";
String avail = c.getString(TAG_AVAIL);
String country = c.getString(TAG_COUNTRY);
String state = c.getString(TAG_STATE);
String postal = c.getString(TAG_POSTAL);
//System.out.println(name);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_ACCESS, access);
map.put(TAG_CITY, city);
map.put(TAG_COMMENT, comment);
map.put(TAG_DIRECTIONS, directions);
map.put(TAG_NAME, name);
map.put(TAG_STREET, street);
map.put(TAG_BATHROOMTYPE, bathroomtype);
map.put(TAG_DISTANCE, distanceTrimmed);
map.put(TAG_AVAIL, avail);
map.put(TAG_COUNTRY, country);
map.put(TAG_STATE, state);
map.put(TAG_POSTAL, postal);
// adding HashList to ArrayList
bathroomList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, bathroomList,
R.layout.list_item,
new String[] { TAG_ID, TAG_NAME, TAG_STREET, TAG_CITY, TAG_STATE, TAG_POSTAL,TAG_COUNTRY, TAG_DISTANCE, TAG_DIRECTIONS, TAG_COMMENT, TAG_AVAIL, TAG_BATHROOMTYPE, TAG_ACCESS}, new int[] {
R.id.key,R.id.name, R.id.street, R.id.city, R.id.state, R.id.postal,R.id.country, R.id.distance, R.id.directions, R.id.comments, R.id.availability, R.id.bathroomtype, R.id.access });
setListAdapter(adapter);
Sort the list using Collections.sort() with a custom comparator.
Collections.sort(bathroomList, new Comparator<HashMap<String, String>>()
{
#Override
public int compare(HashMap<String, String> a, HashMap<String, String> b)
{
return a.get(TAG_DISTANCE).compareTo(b.get(TAG_DISTANCE));
}
});
same problem with mine but I've get it work now, Thanks to #rusmus. Take a Look Sorting Double Data (distance) on ListView
Try this code:
Collections.sort(bathroomList, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> o1,
HashMap<String, String> o2) {
return Double.compare(Double.parseDouble(o1.get(TAG_DISTANCE)), Double.parseDouble(o2.get(TAG_DISTANCE))); // error
}
});

ArrayAdapter : Json data to be sent to spinner

Hi I have created an activity which pulls data from json format text and displays in a spinner view. But im a little confused with the last part. The contactList is a ArrayList type, ArrayAdapter is not accepting contactList as its arugument.
Is
Here's my code
public class RegisterForEventActivity extends Activity {
private static String url = "http://10.0.2.2/Contacts.txt";
private static final String TAG_NAME = "name";
private static final String TAG_CONTACTS = "contacts";
JSONArray jsonArray = null;
Spinner areaspinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
jsonArray = json.getJSONArray(TAG_CONTACTS);
final String[] array_spinner = new String[jsonArray.length()];
// looping through All Contacts
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactList.add(map);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, contactList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaspinner.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is because you are passing a list of HashMap, and not an array of String. Make an array of String, add your contact data in it and pass it to the array.
instead of using this
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
use this
ArrayList<String> contactList = new ArrayList<String>();
Yes, I figured it out!
sp=(Spinner)findViewById(R.id.spinner1);
// Hashmap for ListView
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
System.out.println("Hello");
try {
// Getting Array of Contacts
jsonArray = json.getJSONArray(TAG_CONTACTS);
final String[] items = new String[jsonArray.length()];
// looping through All Contacts
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
items[i]=c.getString(TAG_NAME);
System.out.println("Hello events "+items);
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources