Json LatLong values to mapActivity - android

i received lat and long values through Json and saved in ArrayList And then i passed this Array list to MapAcitivity
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_Lat);
Log.d("matchId", matchId);
String teamA = c.getString(TAG_Lon);
Log.d("teamA", teamA);
// hashmap for single match
matchFixtures = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixtures.put(TAG_Lat matchId);
matchFixtures.put(TAG_Long, teamA);
matchFixtureList.add(matchFixtures);
this is how i passed the values
Iterator myVeryOwnIterator = matchFixtures.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String value=(String)matchFixtures.get(key);
and this is how i recieved in map acitivity
HashMap<String, String> hm = (HashMap<String, String>) getIntent().getExtras().get("hashMapKey");
Iterator myVeryOwnIterator = hm.keySet().iterator();
while (myVeryOwnIterator.hasNext()) {
String key = (String) myVeryOwnIterator.next();
String value = (String) hm.get(key);
for (int i = 0; i <=1; i++){}
but now i dont have any idea how to get these values in such order that fits specific latlog to show places on map its basically for multiple markers on maps

I'd suggest you use a model class for this.
class Model {
public float homeLat;
public float homeLng;
public float universityLat;
public float universityLng;
}
You can create an object of a model class for each of the entry and put it in a list.
Model model = new Model();
model.homeLat = <The Value from Json>
...
matchFixtureList.add(model);
and then in your activity when you read the list values you can get specific lat and long to show a marker.

Related

Store json array keys data in separate arrayLists

I have this kind of json data returning from url as shown in Image1 Image2 Image3
Basically there are dates inside data and then within these dates there are further 5 different things i.e. session_from, session_to, rate, bookingFound and promotion. What i want is that i want to store all these dates data in separate arraylist.
For example:
sessionfrom0 contains data for 09-09-2018 and all its objects
sessionfrom1 contains data for 10-09-2018 and all its objects
sessionfrom2 contains data for 11-09-2018 and all its objects
I have tried with following piece of code but its not working correctly
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
JSONObject datesObject1 = datesArray.getJSONObject(i);
JSONObject datesObject2 = datesArray.getJSONObject(i);
sessionsfrom0.add(datesObject0.getString("session_from") + " - " +datesObject0.getString("session_to");
sessionsfrom1.add(datesObject1.getString("session_from") + " - " +datesObject1.getString("session_to");
sessionsfrom2.add(datesObject2.getString("session_from") + " - " +datesObject2.getString("session_to");
} }
This code not working correctly, as you can see that date 09-09-2018 contains further array of size 4 and and in those array there are further 5 items inside each jjson object so i want to store all this in first arraylist i.e. sessionfrom0 and then go to next date and pick all its arrays and json objects and store data in sessionfrom1 arraylist and so on.
Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
switch (key) {
case "2018-09-09":
fillSessions(datesArray, sessionsfrom0);
break;
case "2018-10-09":
fillSessions(datesArray, sessionsfrom1);
break;
....so on....
}
}
You can create a function instead of rewriting the for loop logic on each case:
void fillSessions(JSONArray jsonArray, List<String> sessionList) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
sessionList.add(datesObject.getString("session_from") + " - " +datesObject0.getString("session_to");
}
}
You can do this by using HashMap
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
HashMap<String, ArrayList<String>> map = new HashMap<>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
list.add(datesObject0.getString("session_from") + " - " + datesObject0.getString("session_to");
}
map.put(key, list);
}
Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Map<String, ArrayList<String>> map = new TreeMap<>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> tmp = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
tmp.add(datesObject.getString("session_from") + " - "+datesObject.getString("session_to"));
}
map.put(key, tmp);
}
Probably you don't have all keys inside data so using switch case is not sensitive.

arraylist with multiple latitude longitude

i have arraylist which have multiple atitude longitude having different
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_MATCHID);
Log.d("matchId", matchId);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_MATCHID, matchId);
matchFixtureList.add(matchFixture);
HashMap<String,String>[] stockArr = new HashMap[matchFixtureList.size()];
stockArr = matchFixtureList.toArray(stockArr);
for(HashMap<String,String> map : stockArr)
for(Map.Entry<String,String> entry : map.entrySet()){
Log.d("debug", entry.getKey() + ","+ entry.getValue());
}
}
i have no idea how to send this to MapActivity
public void setdaata(View view){
Intent intent = new Intent(this, Registration.class);
String[] myStrings = new String[] {"test", "test2"};
intent.putExtra("strings", myStrings);
startActivity(intent);
}
help me please that how to send this and use in MapActivity
You can send ArrayList between activities. But, if the object in array is not primitive data type(like below, MyObject), it has to implement Parcelable.
In current activity
ArrayList<MyObject> list = new ArrayList<>();
list.add(new MyObject(..));
list.add(new MyObject(..));
list.add(new MyObject(..));
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putParcelableArrayListExtra("list", list);
startActivity(intent);
In target activity
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Intent intent = this.getIntent();
ArrayList<MyObject> list = (ArrayList<MyObject>)intent
.getParcelableArrayListExtra("list");
}
Edit
The above approach ideal for passing data when switching activities
(Your actual question).
If you want to access your fetched json data from every point of
app, it must be stored on your device.
Easy way of storing json data : Combine gson library and shared preferences. Check this link to get idea

sum for loop quantity values?

i have this code..
JSONObject jsonObjcart = new JSONObject(myJSONCartProducts);
jsonarrayCartProducts = jsonObjcart.getJSONArray("cartproducts");
cartarraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarrayCartProducts.length(); i++) {
HashMap<String, String> lmap = new HashMap<String, String>();
JSONObject p = jsonarrayCartProducts.getJSONObject(i);
// Retrive JSON Objects
lmap.put("products_id", p.getString("products_id"));
lmap.put("products_name", p.getString("products_name"));
lmap.put("products_price", p.getString("products_price"));
lmap.put("products_image", p.getString("products_image"));
lmap.put("customers_basket_quantity", p.getString("customers_basket_quantity"));
lmap.put("products_price_total", p.getString("products_price_total"));
lmap.put("pcustomersid", customersid);
lmap.put("pcountryid", countryid);
lmap.put("customers_basket_id", p.getString("customers_basket_id"));
// Set the JSON Objects into the array
cartarraylist.add(lmap);
}
i want to sum the quantity p.getString("customers_basket_quantity") and set to my textview..
i tried to do create an
int qtySum=0;
int qtyNum;
and do this inside for loop..
qtyNum = Integer.parseInt(p.getString("customers_basket_quantity"));
qtySum += qtyNum;
and set qtySum to my textview
textTotalitems.setText(qtySum);
but i got error, the app crashed..
this is updated code with sum i tried..
JSONObject jsonObjcart = new JSONObject(myJSONCartProducts);
jsonarrayCartProducts = jsonObjcart.getJSONArray("cartproducts");
cartarraylist = new ArrayList<HashMap<String, String>>();
int qtySum=0;
int qtyNum;
for (int i = 0; i < jsonarrayCartProducts.length(); i++) {
HashMap<String, String> lmap = new HashMap<String, String>();
JSONObject p = jsonarrayCartProducts.getJSONObject(i);
// Retrive JSON Objects
lmap.put("products_id", p.getString("products_id"));
lmap.put("products_name", p.getString("products_name"));
lmap.put("products_price", p.getString("products_price"));
lmap.put("products_image", p.getString("products_image"));
lmap.put("customers_basket_quantity", p.getString("customers_basket_quantity"));
lmap.put("products_price_total", p.getString("products_price_total"));
lmap.put("pcustomersid", customersid);
lmap.put("pcountryid", countryid);
lmap.put("customers_basket_id", p.getString("customers_basket_id"));
// Set the JSON Objects into the array
qtyNum = Integer.parseInt(p.getString("customers_basket_quantity"));
qtySum += qtyNum;
cartarraylist.add(lmap);
}
textTotalitems.setText(qtySum);
Use
textTotalitems.setText(String.valueOf(qtySum));
instead of
textTotalitems.setText(qtySum);
With your current implementation your trying to set a resource-Id to your TextView, because TextView has an overloaded setText(int resId)-method.

Android: Pulling a String Array from a HashMap

I'm building a a Gallery app using GridView and ViewPager. I'm getting the image URLs from JSON. I've got the GridView displaying the images correctly, and now I'm moving on to the ViewPager. What I think I need to do is generate a String array of the image URLs for the ViewPager Adapter. In the GridView Activity, I've created a HashMap with the id, URL, and image description strings stored. My question now is: Is it possible to generate a String Array by retrieving all the stored URL strings from the HashMap? What I need is this from the HashMap:
public static final String[] imagesStr = new String[] {
"http://www.mysite/images/building0001.jpg",
"http://www.mysite/images/building00011.jpg",
"http://www.mysite/images/building0010.jpg" };
Here's how I'm generating the HashMap:
#Override
protected Void doInBackground(Void... params) {
// Retrieve JSON Objects from the given URL address
galleryArrList = new ArrayList<HashMap<String, String>>();
jsonobject = JIJSONfunctions.getJSONfromURL(urlPathStr);
try {
// Locate the array name in JSON
JSArrGallery = jsonobject.getJSONArray("gallery");
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
idStr = galleryJO.getString(TAG_ID);
urlStr = galleryJO.getString(TAG_URL);
descrStr = galleryJO.getString(TAG_DESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_URL, urlStr);
map.put(TAG_DESCR, descrStr);
galleryArrList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
I'm a bit unclear on how a HashMap works, but I assume that the code is going through the JSON Array and pulling each URL string out and storing it in the HashMap, right? So now can I pull all the gathered URL Strings and create a String Array with them? How would I do that?
Seems straightforward enough. After you have populated your List<HashMap<String,String>>, iterate over each map and pull the value you need from it to add to a String[]. Please refer to the following snippet:
galleryArrList = new ArrayList<HashMap<String, String>>();
jsonobject = JIJSONfunctions.getJSONfromURL(urlPathStr);
try { ... }
final int length = galleryArrList.size();
final String[] imagesStr = new String[length];
for (int i = 0; i < length; i++) {
final Map<String, String> map = galleryArrList.get(i);
imagesStr[i] = map.get(TAG_URL);
}
You might try using an ArrayList and add the URLs to the ArrayList within the for loop. When the loop is done, you can use the ArrayList.toArray(T[] array) method copy the URLs from the ArrayList to a String array.
ArrayList.toArray
ArrayList arlist = new ArrayList();
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
idStr = galleryJO.getString(TAG_ID);
urlStr = galleryJO.getString(TAG_URL);
descrStr = galleryJO.getString(TAG_DESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_URL, urlStr);
map.put(TAG_DESCR, descrStr);
galleryArrList.add(map);
arlist.add(urlStr);
}
// Create a String array to hold the URLs
String[] arUrls = new String[arlist.size()];
// Copy the URLs from the ArrayList to the String array
arlist.toArray(arUrls);

Android json parsing by category wise

I have a Json Array like below:
[{"item":{"category Name":"T-e-PBS","SubCategory Name":"T-e-PBS"}},
{"item":{"category Name":"T-e-PBS","SubCategory Name":"Animals"}},
{"item":{"category Name":"T-e-PBS","SubCategory Name":"Birds"}},
{"item":{"category Name":"T-e-PBS","SubCategory Name":"Vegetables"}},
{"item":{"category Name":"T-e-PBS","SubCategory Name":"Colors"}},
{"item":{"category Name":"Rhymes","SubCategory Name":"Rhymes"}},
{"item":{"category Name":"Rhymes","SubCategory Name":"Animated Rhymes"}},
{"item":{"category Name":"Rhymes","SubCategory Name":"Cartoon Rhymes"}},
{"item":{"category Name":"Rhymes","SubCategory Name":"Prayers"}}]
I have tried but don't know how to get Category wise information as I have lots of Subcategories under Categories:
I want to Parse this JSON String and populate the data According to Category.
If I click on T-e-PBS button I should be able to get All Subcategories in a gridview like AnimalsImage, BirdsImages, etc in gridview.
And if I click on Rhymes category I should be able to get All Subcategories in a gridview.
Could anyone help?
I have tried:
JSONArray ja = new JSONArray(json);
int size = ja.length();
Log.d("tag","No of Elements " + ja.length());
for (int i = 0; i < size; i++) {
String str = ja.getString(i);
}
In the for loop, retrieve required JSON Objects using
JSONObject c = ja.getJSONObject(i);
And then store Json item in a variable using,
String str = c.getString("category Name");
JSON Objects are represented using {. So depending on your JSON structure, parse it and retrieve desired item.
You can use HashMap to store the separate Category List, and you can easily get the desired list of Category like T-e-PBS, Rhymes, etc.
// Which hold the category basis of category Type
HashMap<String, List<String>> category = new HashMap<String, List<String>>();
List<String> cat_name = new ArrayList<String>();
List<String> subcat_name = new ArrayList<String>();
try {
JSONObject script = new JSONObject("YOUR RESPONSE STRING");
JSONArray listOfCategory = script.getJSONArray("YOUR_ARRAY");
for (int j = 0; j < listOfCategory.length(); j++) {
JSONObject item = listOfCategory.getJSONObject(j).getJSONObject("item");
String cat = item.getString("category Name");
if (cat.equalsIgnoreCase("T-e-PBS")) {
cat_name.add(item.getString("SubCategory Name"));
} else if (cat.equalsIgnoreCase("Rhymes")) {
subcat_name.add(item.getString("SubCategory Name"));
}
}
category.put("T-e-PBS", cat_name);
category.put("Rhymes", subcat_name);
// To get the according to Category Name
List<String> retrieveCatList1 = category.get("T-e-PBS");//Key is T-e-PBS
List<String> retrieveCatList2 = category.get("Rhymes");//Key is Rhyme
} catch (Exception e) {
}
You can use a HashMap of ArrayLists
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
try {
JSONArray array = new JSONArray(str);
// Where str is your response in String form
for (int i=0; i<array.length(); i++){
String category = item.getString("category Name");
String subcategory = item.getString("SubCategory Name");
ArrayList<String> categoryFromMap = map.get("category");
if (categoryFromMap == null){
// Not initiated
categoryFromMap = new ArrayList<String>();
}
categoryFromMap.put(subcategory);
map.put(category, categoryFromMap);
}
} catch (JSONException ex){
ex.printStackTrace();
}
// Accessing your data
for (String key : map.keySet()){
// key contains your category names
ArrayList<String> subcategories = map.get(key);
Log.d("CATEGORY", key);
for (String subcat : subcategories){
Log.d("SUBCATEGORY", subcat);
}
}
// Getting a single category
ArrayList<String> rhymes = map.get("Rhymes");
The Log.d sentences should give this output:
CATEGORY T-e-PBS
SUBCATEGORY T-e-PBS
SUBCATEGORY Animals
SUBCATEGORY Birds
SUBCATEGORY Vegetables
SUBCATEGORY Colors
CATEGORY Rhymes
SUBCATEGORY Rhymes
SUBCATEGORY Animated Rhymes
SUBCATEGORY Cartoon Rhymes
SUBCATEGORY Prayers

Categories

Resources