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
Related
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.
I am trying to use HashMap to pass the values over to the other class but I am not sure why I got such weird results. I did a system.out.println and got [{Latitude=1.224119, username=borrow, Longitude=103.930041}],[{Latitude=1.224119, username=borrow, Longitude=103.930041}] repeatably but it shouldn't be the case as I have two different coordinates.
And when I pass it to the other class, it only returns me one coordinate and not two.
Anything went wrong with my code?
Get coordinates from db and pass to another class:
protected void onPostExecute(JSONObject json) {
ArrayList<HashMap<String, String>> list=new ArrayList<HashMap<String,String>>();
HashMap<String, String> h1=new HashMap<String, String>();
if (json != null) {
Toast.makeText(Borrower_AP.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
dataJsonArr = json.getJSONArray("Posts");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
Longitude = c.getDouble("longitude");
Latitude = c.getDouble("latitude");
String s_lat = Latitude.toString();
String s_long = Longitude.toString();
h1.put("Latitude",s_lat);
h1.put("Longitude",s_long);
h1.put("username",username);
list.add(h1);
Intent i = new Intent(this, BorrowerMap.class);
i.putExtra("list", list);
System.out.print(list);
startActivity(i);
}
Get the values out:
ArrayList<HashMap<String, String>> list=new ArrayList<HashMap<String,String>>();
list=(ArrayList<HashMap<String, String>>) getIntent().getExtras().get("list");
String Latitude=list.get(0).get("Latitude");
String Longitude=list.get(0).get("Longitude");
String s_lat = Latitude.toString();
String s_long = Longitude.toString();
System.out.println(Latitude);
System.out.println(Longitude);
If i follow your question than make the intent call after the loop body.Because it is getting only one list item and making the intent call in each loop process.
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
Longitude = c.getDouble("longitude");
Latitude = c.getDouble("latitude");
String s_lat = Latitude.toString();
String s_long = Longitude.toString();
h1.put("Latitude",s_lat);
h1.put("Longitude",s_long);
h1.put("username",username);
list.add(h1);
}
Intent i = new Intent(this, BorrowerMap.class);
i.putExtra("list", list);
System.out.print(list);
startActivity(i);
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);
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
I have JSONArray and when I decode JSON to HashMap at that time HashMap take last value of JSONArray.
here my code:
QjArray = new JSONArray(Questionresult);
JSONObject json_data = new JSONObject();
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
json_data = QjArray.getJSONObject(i);
jQuestionName =json_data.getString("QuestionName");
objJMap.put("QuestionName",jQuestionName);
jQuestiontypeid = json_data.getInt("Questiontypeid");
String Qid = jQuestiontypeid.toString();
objJMap.put("Questiontypeid", Qid);
jAnswertypeid = json_data.getInt("Answertypeid");
String Aid = jAnswertypeid.toString();
objJMap.put("Answertypeid", Aid);
}
My JSONArray:
This is question list[{"QuestionID":"1","QuestionName":"when you come","Questiontypeid":"1","Answertypeid":"1"},{"QuestionID":"2","QuestionName":"about your words","Questiontypeid":"1","Answertypeid":"2"},{"QuestionID":"3","QuestionName":"you want extra service?","Questiontypeid":"1","Answertypeid":"3"},{"QuestionID":"4","QuestionName":"performance of quality ?","Questiontypeid":"1","Answertypeid":"4"},{"QuestionID":"5","QuestionName":"performance of staff?","Questiontypeid":"1","Answertypeid":"5"},{"QuestionID":"6","QuestionName":"when you left room ?","Questiontypeid":"2","Answertypeid":"1"},{"QuestionID":"7","QuestionName":"your words about roomservice ?","Questiontypeid":"2","Answertypeid":"2"},{"QuestionID":"8","QuestionName":"you like roomservice ?","Questiontypeid":"2","Answertypeid":"3"},{"QuestionID":"9","QuestionName":"performance room service ?","Questiontypeid":"2","Answertypeid":"4"},{"QuestionID":"10","QuestionName":"performance room service staff?","Questiontypeid":"2","Answertypeid":"5"}]
I think there are certain problems in your logic. For every JSON object u are creating new HashMap object inside for loop, so u will loose any previous data. Also HashMap will override new Data, so you will have only final data. What u can do is that create an arrayList of Hashmap....
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<STring, String>>();
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
........
data.add(objJMap);
...}
This is because your code re initializes the HashMap after every loop.
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
....
}
Place the HashMap outside the loop and it will work fine.
objJMap = new HashMap<String, String>();
for (int i = 0; i<QjArray.length(); i++) {
....
}