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>>();
Related
I have a fragment that contains a listView that i want to be updated whenever a new record is added. Im trying to call .notifyDataSetChanged() in onResume() in fragment but the adapter = null.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_log,
container, false);
exmaplePrefs = this.getActivity().getSharedPreferences(PREFS, 0);
json = exmaplePrefs.getString("jsonString", "cant find json");
JSONObject MainObj = null;
JSONArray JsonArray = null;
try {
MainObj = new JSONObject(json);
JsonArray = MainObj.getJSONArray("Events");
for(int i = 0; i < JsonArray.length(); i++){
JSONObject c = JsonArray.getJSONObject(i);
// Storing JSON item in a Variable
String time = c.getString("time");
String event = c.getString("event");
String player = c.getString("player");
String from[] = {"time","event", "player"};
int to[] = {R.id.time,R.id.event, R.id.player};
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put("time", time);
map.put("event", event);
map.put("player",player);
newItemlist.add(map);
listV=(ListView)rootView.findViewById(android.R.id.list);
adapter = new SimpleAdapter(getActivity(), newItemlist, R.layout.custom_list_row, from, to);
listV.setAdapter(adapter);
}
} catch (Exception e) {
// TODO: handle exception
System.out.print("ERROR");
}
return rootView;
}
#Override
public void onResume(){
super.onResume();
System.out.println("worked");
if (adapter != null){
adapter.notifyDataSetChanged();
}
}
I think this is something to do with the adapter being created onCreateView() and is not visible when I return to the Fragment.
Looking at this, I see a few problems.
It's generally very poor practice to catch ( Exception ex). Try catching only the specific Exceptions you are worried about, it makes fixing problems easier.
Why is your ArrayAdapter created inside of a for loop? You probably wand something like this:
ArrayList list=new ArrayList(); //Specify what type of value is in the ArrayAdapter
adapter = new SimpleAdapter(getActivity(), newItemlist, R.layout.custom_list_row,list);
listV.setAdapter(adapter);
MainObj = new JSONObject(json);
JsonArray = MainObj.getJSONArray("Events");
for(int i = 0; i < JsonArray.length(); i++){
JSONObject c = JsonArray.getJSONObject(i);
// Storing JSON item in a Variable
String time = c.getString("time");
String event = c.getString("event");
String player = c.getString("player");
String from[] = {"time","event", "player"};
int to[] = {R.id.time,R.id.event, R.id.player};
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put("time", time);
map.put("event", event);
map.put("player",player);
newItemlist.add(map);
listV=(ListView)rootView.findViewById(android.R.id.list);
adapter.add(map);
}
I'm not quite sure what SimpleArrayAdapter is, but you want to create a new one once outside of the loop, and add things to it inside of the loop most likely, re-creating it seems like a poor choice. You'll probably need to do some playing with the adapter.add(map) command in particular, but this general pattern should help. You'll also need to change the ArrayList list to something like ArrayList<String> list=new ArrayList<String>(), to whatever your ArrayAdapter is storing (Looks like HashMap<String,String>)
If an Exception is thrown, you will directly move to the catch block, hence skipping adapter's initialization. This probably means that there is an error parsing your JSON string.
I have followed a tutorial online and tweaked some of the code, I would like the application to read information from a different location. Currently the app is correctly reading the data from here. Now I would like to read data from here. I'm looking to attain Observation Time, Temp_C & Visibility, I imagine I would need to change my code within the try { bracket in order to read this data? Any suggestions?
public class MainActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_DATA = "contacts";
private static final String TAG_OBSERV = "name";
private static final String TAG_TEMP = "email";
private static final String TAG_VISIB = "gender";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParse jParser = new JSONParse();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_OBSERV);
String email = c.getString(TAG_TEMP);
String gender = c.getString(TAG_VISIB);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_OBSERV, name);
map.put(TAG_TEMP, email);
map.put(TAG_VISIB, gender);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_OBSERV, TAG_TEMP, TAG_VISIB }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_OBSERV, name);
in.putExtra(TAG_TEMP, cost);
in.putExtra(TAG_VISIB, description);
startActivity(in);
}
});
}
}
How to parse JSON data to Android?
So at first you should move your code where you are attempt to perfrom network connection(fetching data from JSON) to background Thread. Actually you're doing it at Main(UI) Thread and it's not very good and correct. If your app will be installed on a device that runs on Android 3.0+ you will get NetworkOnMainThreadException and it's not nice, ins't?
Second, save your JSON and make some formatting to see its structure better. Multiset bracket { indicates JSONObject and bracket [ indicated JSONArray.
Now you should be able to parse JSON. Now i write you a little snippet of code how to start:
JSONObject o = new JSONObject(sourceString);
if (o != null) {
JSONObject data = o.getJSONObject("data"); // getting JSONObject with key data
if (data != null) {
JSONArray current = data.getJSONArray("current_condition");
}
}
...
The easiest and prettiest way would be to create a DTO with the wanted properties and then use a library such as Jackson or Gson to map the JSON to object(s). Then it would be 2 lines of code instead of that 'manual parsing'.
Here is the way you should parse and get your values from that json :
JSONObject mMainObject = new JSONObject(myResponseString);
if(mMainObject != null){
JSONObject data = mMainObject.getJSONObject("data");
if(data != null){
JSONArray currentCondition = data.getJSONArray("current_condition");
if(currentCondition != null){
for(int i = 0; i < currentCondition.lenght(); i++){
JSONObject obj = currentCondition.get(i);
if(obj != null){
String observation_time = obj.getString("observation_time");
String temp_C = obj.getString("temp_C");
String visibility = obj.getString("visibility");
}
}
}
}
}
Doing that you should consider the proper way to download the data from internet using AsyncTask for example. In this way it will not block your UI and your app will be more responsive.
Hope this help! : )
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
}
});
I have parsed the JSON data and storing the parsed JSON data into ArrayList HashMap with the key value ,when I want to display the parsed data I am getting only the last value of the parsed Data rest all data are not displayed for reference
public HashMap<String,String> map = new HashMap<String, String>();
create HASHmap then arraylist
public static ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
void parsing(JSONObject json)
{
String id="";
String countryn="";
try
{
countryobj = json.getJSONArray("country_details");
for(int i = 0;i<countryobj.length(); i++)
{
JSONObject items = countryobj.getJSONObject(i);
Log.e("i","value==="+i);
if(items.has("countryid"))
{
id = items.getString("countryid");
map.put("countryid",id);
Log.e("id","valueID==="+id);
}
if(items.has("country"))
{
countryn= items.getString("country");
map.put("country",countryn);
Log.e("counyrt","valueName==="+countryn);
}
contactList.add(i,map);
Log.e("lisvaluet","val--"+i +contactList.get(i));
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
in Log I am getting only 08-20 12:13:45.830: E/--ID---(654): value--{countryid=275, country=Palestinian Territory} with 269 times can any help me out where I am doing wrong in storing the parsed data , I am stuck here.
Check this.
private JSONObject[] items;
JSONArray countryobj = json.getJSONArray("country_details");
items = new JSONObject[countryobj.length()];
for(int i=0, i < countryobj.length(); i++)
{
items[i] = countryobj.optJSONObject(i);
id = items[i].getString("countryid");
map.put("countryid",id);
countryn= items[i].getString("country");
map.put("country",countryn);
contactList.add(i,map);
}
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();
}