I have a JSON with an array of 3 objects. So when I retrieveEventJSON(), I am simply setting the attributes to an Event object. And when I call the plotEventOnMap() from another activity, I expect to see 3 markers on the map.
public void retrieveEventJSON() throws JSONException {
String page;
JSONArray jsonArray;
try {
// Code to retrieve data from servlet
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("Events");
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void plotEventOnMap(Context context) {
graphicIcon = new PictureMarkerSymbol(res);
Point p = new Point(Double.parseDouble(eventModel.getEventX()),
Double.parseDouble(eventModel.getEventY()));
Symbol symbol = graphicIcon;
HashMap<String, Object> attrMap = new HashMap<String, Object>();
attrMap.put("eventName", eventModel.getEventName());
attrMap.put("eventBy", eventModel.getEventBy());
ENeighbourhoodActivity.graphicsLayer.addGraphic(new Graphic(p, symbol,
attrMap));
}
But with these codes, it just display the last row of record in my JSON instead of looping and plot each of them. Any guides?
Thanks in advance.
You need to call .plotEventOnMap(), or otherwise do something with the EventModel you've constructed, from inside your loop, after setting all the EventModel properties. At the moment, you're just overwriting your EventModel without ever using it.
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
}
Just before the loop ends, you need to do something with the EventModel you've now constructed. This might be plotting it, or adding it to some collection, or whatever. But at the moment, you're going straight back into the loop, and then in the next iteration, overwriting all the good work you've done. The reason you're only ending up with the last one is that when you've done the last iteration, what's left in eventModel is what you wrote the last time you went through the loop.
In fact I think you also want
EventModel eventModel = new EventModel();
as the first thing inside your loop. (I don't know if this is exactly right because we haven't seen the code for EventModel so I don't know what the constructor looks like.) If you want to keep a List (or similar) of all of them, you need to make sure they're all different instances.
I would suggest recasting like this:
List<EventModel> events = new ArrayList<EventModel>(); //NEW
for (int i = 0; i < length; i++) {
EventModel eventModel = new EventModel(); //NEW
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
events.add(eventModel); //NEW
}
After the loop has finished, you'll have a list of EventModels that you can send to your plotting method or whatever's appropriate.
eventModel.setEventName(eventName); returns the latest element added to it because on every iteration you are resetting it.
You may add the object to the list after each iteration so that the list will have the elements. Declare the your EventModel object inside the for loop to have the instance for every iteration.
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
EventModel eventModel=new eventModel();
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
list.add(eventModel);
}
Related
I have a json array of all names and contacts on my phone, looks something like this:
[{"name":"andy","phone_number":"+123"},{"name":"bob","phone_number":"+456"},{"name":"chris","phone_number":"+789"}]
I check the phone numbers against phone numbers in a db, if there's a match I want to show the name in the recycler view, if no match, then show just the number.
For example, +123, yes, it is in the db, so show andy in the cell in recyclerview. +789 is not in the db, so show +789 in the cell.
Here's what I'm working with so far: it works when there is a match, the if part, but I don't know how to deal with the else part (for when there is no match). If I uncomment my else code it always jumps straight to there.
public void onResponse(String response) {
try {
//name our JSONObject User_Private_Public_Obj, which is response from server
//the response from server will be like:
//{"private_review_ids":[{"reviewid":7,"username":"+123"},{"reviewid":14,"username":"+456"}]}
JSONObject User_Private_Public_Obj = new JSONObject(response);
//Now break up the response from server
//We want the JSON Array part, "private_review_ids"
JSONArray private_ids = User_Private_Public_Obj.getJSONArray("private_review_ids");
for
//get the number of objects in User_Private_Public_Obj
(int i = 0; i < private_ids.length(); i++)
{
//for each object in the array private_ids, name it obj
//each obj will consist of reviewid and username
JSONObject obj = private_ids.getJSONObject(i);
Review review = new Review();
//get the string from sharedpreferences, AllPhonesandNamesofContacts,
//it will be like [{"phone_number":"+123","name":"andy"}, etc...]
//we want this so we can display phone name in recyclerView, if it's a contact
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("AllPhonesandNamesofContacts", "0");
//convert the string above into a json array
JSONArray jsonArray = new JSONArray(json_array);
//set a string to the phone number from the DB,
//the phone number of the person who made the review
phoneNoInDB = obj.getString("username");
//set the setter to the phone number string, the string is
//the phone number of the person who made the review
review.setPhoneNumberofUserFromDB(phoneNoInDB);
//jsonArray is our All Phones and Names of Contacts array
int matching = jsonArray.length();
for (int n = 0; n < matching; n++) {
try {
//for every object in "All Phones and Names of Contacts" array...
JSONObject object = jsonArray.getJSONObject(n);
//if the review maker is a contact...that is,
//if the phone_number in AllPhonesandNamesofContacts equals
//the phone number in the DB
if (object.getString("phone_number").equals(phoneNoInDB)) {
//just for testing purposes...
Toast.makeText(NewActivity.this, object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
//then rip out the other part of the object, the name in
// AllPhonesandNamesofContacts
//of the person who made the review
review.setphoneNameonPhone(object.getString("name"));
//add the review to the sharedReviewList
reviewList.add(review);
}
/* else {
//just for testing...
Toast.makeText(NewActivity.this, " should be green" + object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
review.setphoneNameonPhone(object.getString("phone_number"));
//add the review to the sharedReviewList
//reviewList.add(review);
}*/
} catch (JSONException e) {
System.out.println("error in if else");
//Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
//set the adapter to show the random reviews
recyclerView.setAdapter(uAdapter);
Here I am getting my data in comma seperated format.
1,2,3,4....n
Response ids are more than 300.
requestButton = (Button) findViewById(R.id.requestButton);
I want to take first 45 on button click, then again next 45 on button click and so on.
Ids should not repeat.
Is there any way how can I do that.
try {
JSONObject rob = response.getJSONObject();
JSONArray array = rob.getJSONArray("data");
fr = new ArrayList();
for (int i = 0; i < array.length(); i++) {
friend = array.getJSONObject(i);
fr.add(friend.get("id"));
formatedString = fr.toString()
.replace("[", "")
.replace("]", "");
Log.d("uid", String.valueOf(formatedString));
}
} catch (JSONException e) {
e.printStackTrace();
}
Simply pass count as parameter in your url .Thats will fetch data from server(you have to create code). Then if you want more call the same url with increased count.
first time
url="http://androidexample.com/getPage.php?count=45";
when more button clicked call the same url with increased count
url="http://androidexample.com/getPage.php?count=90";
another way is store all the value in local database when first time data loaded from server then display listview based on the count.
I have a no. of checkboxes (20), what i did is if a user select any checkbox, its name is stored in an array (eg abc array below in code). The name of the string variable that stores the respective json is of the same name as of the checkbox. For eg if Checkbox "a" is clicked, string value "a" is stored in array and there is a string variable named "a" that stores the related json values. What I need is that if i pass the string value stored in array as InputStream is = new ByteArrayInputStream(abc.get(i).getBytes()), it should be used to parse the inputStream for json. But it gives NullPointerException since the string value "a" is not equal to string variable a. How can i solve this problem? I ran out of ideas here. Is there other ways to achieve what i want to do here?
code: String values of the selected checkboxes are stored in an array
String a = "[{\n"
+ "\t\t\t\"title\": \"title1\",\n"
+ "\t\t\t\"describ\": \"describ1\"\n"
+ "}]";
String b = "[{\n"
+ "\"title\": \"title2\",\n"
+ "\"describ\": \"describ2\"\n"
+ "}]";
String c = "[{\n"
+ "\t\t\t\"title\": \"title3\",\n"
+ "\t\t\t\"describ\": \"describ3\"\n"
+ "}]";
//and all jsons required are there
ArrayList<String> abc;
#Override
protected void beforeTestForApp(Form f) {
f.setTitle("abc");
abc = new ArrayList<>();
//I have stored "a" & "b" in the abc array here for simplicity, but it is dynamic,
//ie. if the user select checkbox c, c will be stored in abc array and so on
abc.add("a");
abc.add("b");
Button bb = new Button("go");
bb.addActionListener((e) -> {
showForm("TestForAppResult", null);
});
f.add(bb);
}
Form for json parser and displaying the values:
#Override
protected void beforeTestForAppResult(Form f) {
f.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
InputStream is;
for (int i = 0; i < abc.size(); i++) {
Label heading = new Label(abc.get(i));
f.add(heading);
//this gives error since abc.get(i) gives string value, not string variable
is = new ByteArrayInputStream(abc.get(i).getBytes());
showDetails(is, f);
}
//if i do this instead of for loop jst above, i can get the result but since what value'll be stored in an array is not known,it is not possible
//is = new ByteArrayInputStream(a.getBytes());
//showDetails(is, f);
//is = new ByteArrayInputStream(b.getBytes());
//showDetails(is, f);
}
private void showDetails(InputStream is, Form f) {
JSONParser p = new JSONParser();
Hashtable<String, Object> test;
try {
test = p.parse(new InputStreamReader(is));
Vector aVector = (Vector) test.get("root");
for (int j = 0; j < aVector.size(); j++) {
Hashtable hm = (Hashtable) aVector.get(j);
String title = (String) hm.get("title");
String describ = (String) hm.get("describ");
Label z = new Label(title);
Label zz = new Label(describ);
f.add(z);
f.add(zz);
}
} catch (IOException ex) {
}
}
tbh i didnt get your problem concretely but i still try to give you some shots so you can try out.
If i understand correctly you have 20 objects which contains values underlying?
So then you have a JSONArray, just iterate trough it and grab that JSONObject.
now just use parseJSON instead of parse as it is deprecated...
here is a short snippet of my code
JSONArray jsonTasks = new JSONArray(responseString);
for (int index = 0; index < jsonTasks.length(); index++) {
JSONObject jsonObject = (JSONObject) jsonTasks.get(index);
if (jsonObject != null) {
Map jsonMap = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(jsonObject.toString().getBytes(UTF8)), UTF8));
System.out.println(jsonMap.get("date"));
I am using temboo to get all the events for a calendar. However, i am trying to create a hashtable of the events and the days. but the for loop says its a null pointer exception even though the program is actually able to access that ith element. I have even printed it and the i is less than the size of the array. Here is the snippet code: Error is in the second line of the for loop.Errr occurs when i = 23, but items.size is 41.
GetAllEvents getAllEventsChoreo = new GetAllEvents(session);
// Get an InputSet object for the choreo
GetAllEventsInputSet getAllEventsInputs = getAllEventsChoreo.newInputSet();
// Set inputs
getAllEventsInputs.set_AccessToken(accessToken);
getAllEventsInputs.set_ClientID(clientID);
getAllEventsInputs.set_ClientSecret(clientSecret);
getAllEventsInputs.set_CalendarID(callIDs[0]);
// Execute Choreo
GetAllEventsResultSet getAllEventsResults = getAllEventsChoreo.execute(getAllEventsInputs);
results = getAllEventsResults.get_Response();
System.out.println(results);
root = jp.parse(results);
rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("items").getAsJsonArray();
System.out.println("Abour to enter the for loop\nItems:\n"+items.toString());
System.out.println("****************************\nEnter the for loop");
System.out.println("iems Size: "+items.size());
System.out.println(items.get(23).toString());
for(int i = 0;i < items.size();i++)
{
System.out.println("i: "+i);
String startTime = items.get(i).getAsJsonObject().get("start").getAsJsonObject().get("dateTime").getAsString();
System.out.println("startTime: "+startTime);
String dayKey = startTime.split("T")[0];
if(dayKey.equals(beginDate)==false | dayKey.equals(endDate)==false)
{
System.out.println(startTime + " not the one interested so skipping");
continue;
}
System.out.println("passed the first if in for loop");
String endTime = items.get(i).getAsJsonObject().get("end").getAsJsonObject().get("dateTime").getAsString();
String name = items.get(i).getAsJsonObject().get("summary").getAsJsonPrimitive().getAsString();
calendarEvent eventTemp = new calendarEvent(name,startTime,endTime);
if(table.containsKey(dayKey))
table.get(dayKey).add(eventTemp);
else
{
ArrayList<calendarEvent> schedule = new ArrayList<calendarEvent>();
schedule.add(eventTemp);
table.put(dayKey,schedule);
}
}
Set<String> key = table.keySet();
Iterator<String> it = key.iterator();
while(it.hasNext())
{
String keyValue = it.next();
System.out.println("Events on "+keyValue);
ArrayList<calendarEvent> temp = table.get(keyValue);
for(int j =0;j<temp.size();j++)
{
System.out.println(temp.get(j));
}
}
After breaking down the exception line, the exception occurs when I try to get the dateTime as string, the last part creates an exception.
Just because the ith element of an array exists, it does not mean that the element is not null.
Referencing a property or method of such an element will yield a NullPointerException.
If i went beyond the bounds of the array, you would get an ArrayIndexOutOfBoundsException instead.
Check indexed array elements for null before using them.
Sorry to be brief and not reference your code or other sources. I am on my phone. The likely source of your problem is pretty clear, though.
I have this XML file which I parse into an ArrayList
In this ArrayList I have countries and the alarmnumbers for the countries in it.
I want to search to a country and get it's police, ambulance or firedep. number.
Here is the code to help you out.
Parsing XML into ArrayList:
protected ArrayList<Alarmdiensten> getAlarmdiensten() {
ArrayList<Alarmdiensten> lijst = new ArrayList<Alarmdiensten>();
try {
DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("alarmdiensten.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i=0;i<nl.getLength();i++) {
Node node = nl.item(i);
Alarmdiensten land = new Alarmdiensten();
land.land = Xml.innerHtml(Xml.getChildByTagName(node, "naam"));
land.landcode = Xml.innerHtml(Xml.getChildByTagName(node, "code"));
land.politie = Xml.innerHtml(Xml.getChildByTagName(node, "politie"));
land.ambulance = Xml.innerHtml(Xml.getChildByTagName(node, "ambulance"));
land.brandweer = Xml.innerHtml(Xml.getChildByTagName(node, "brandweer"));
land.telamba = Xml.innerHtml(Xml.getChildByTagName(node, "telamba"));
land.adresamba = Xml.innerHtml(Xml.getChildByTagName(node, "adresamba"));
lijst.add(land);
}
} catch (Exception e) {;
}
return lijst;
}
The method that will use the alarmnumbers:
public void AlarmMenu(){
String landcode;
ArrayList<Alarmdiensten> diensten = getAlarmdiensten();
if(fakelocation = true) {
landcode = sfakelocation;
}
else {
try {
landcode = getAddressForLocation(this, locationNow).getCountryCode();
} catch (IOException e) {
e.printStackTrace();
}
}
So I have the landcode, and I want to search in the ArrayList diensten for the numbers that belong with the landcode.
How can I do this?
Well at the moment you've got an ArrayList of Alarmdiensten objects. I would suggest you might want to change that to a Map so that you are storing a Map of land codes vs your Alarmdiensten objects.
That way you get the Alarmdiensten out of the Map using the landcode and then simply call the getPolitie() etc methods on your Alarmdiensten object.
I would make sure that you encapsulate your Alarmdiensten object BTW, accessing it's private members directly is a bit of a no-no :)
So something like:
protected Map<String, Alarmdiensten> getAlarmdiensten()
{
Map<String, Alarmdiensten> alarmNumbersForCountries
= new HashMap<String, Alarmdiensten>();
try
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("alarmdiensten.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i = 0; i < nl.getLength(); i++)
{
Node node = nl.item(i);
Alarmdiensten land = new Alarmdiensten();
land.setLand(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
land.setLandcode(Xml.innerHtml(Xml.getChildByTagName(node, "code")));
land.setPolitie(Xml.innerHtml(Xml.getChildByTagName(node, "politie")));
land.setAmbulance(Xml.innerHtml(Xml.getChildByTagName(node, "ambulance")));
land.setBrandweer(Xml.innerHtml(Xml.getChildByTagName(node, "brandweer")));
land.setTelamba(Xml.innerHtml(Xml.getChildByTagName(node, "telamba")));
land.setAdresamba(Xml.innerHtml(Xml.getChildByTagName(node, "adresamba")));
alarmNumbersForCountries.put(land.getLandCode(), land);
}
}
catch (Exception e)
{
// Handle Exception
}
return alarmNumbersForCountries;
}
To get the entry out of the Map
Alarmdiensten land = alarmNumbersForCountries.get(landcode);
Another YMMV point is that you might want to split out the part of your method that builds Alarmdiensten objects from the XML parsing. "Each method should do one thing and one thign well."
Use a for loop and search for it
for(Alarmdiensten land :diensten){
if(land.landcode.equals(landcode) ){
// yes i got it, The current land.
break;
}
}
Just iterate over the list:
String landcode = getLandCode();
for (Alarmdiensten dienst:diensten) {
if (dienst.landcode.equals(landcode)) {
// do what has to be done
}
}
Consider using a map instead of a list, if you have to lookup the values more frequently:
Map<String, List<Alarmdiensten>> servicesInCountry
= new HashMap<String, List<Alarmdiensten>>();
for (Alarmdiensten dienst:diensten) {
List<Alarmdiensten> list = servicesInCountry.get(dienst.landcode);
if (list == null) {
list = new ArrayList<Alarmdiensten>();
servicesInCountry.put(dienst.landcode, list);
}
list.add(dienst);
}
// ... and later on
List<Alarmdiensten> servicesInSweden = servicesInCountry.get("SWE");