Android: Pulling a String Array from a HashMap - android

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);

Related

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.

How To store json values in a set of arrays in android

i have a json file like so :
http://da.pantoto.org/api/files
i want to store these values in variables to be used later. The values should be stored in some String array variables like id[], uploadDate[], url[].
i can find examples using ListView and ArrayAdapter. but thats not what i really want. Anyone can help??
This is only an example to show how you can get the values from JSON. You need to store these values as you need.
JSONObject jsonObject = new JSONObject("your response");
JSONArray filedetails = jsonObject.getJSONArray("files");
for(int i=0; i<filedetails.size();i++){
String id = filedetails.get(i).getString("id");
JSONArray tagsdetails= filedetails.get(i).getJSONArray("tags");
for(int i=0; i<tagsdetails.size();i++){
//fetch values in it
}
}
You can't do it exactly that way, You have to iterate trough the array and get each object properties individually and then if you want you could create an array to store each object property.
//From the example: http://da.pantoto.org/api/files
JSONArray files = null;
//Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://da.pantoto.org/api/files", ServiceHandler.GET);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
files = jsonObj.getJSONArray("files");
//YOUR NEW ARRAY
String[] ids = new String[20];
String[] urls = new String[20];
//etc
//looping through All files
for (int i = 0; i < files.length(); i++) {
JSONObject c = files.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
//etc
//HERE IS WHAT YOU COULD DO OPTIONALLY IF YOU WANT HAVE IT ALL ON A SINGLE ARRAY WITHOUT OBJECTS:
ids[i] = id;
urls[i] = url;
//etc
}
this is a simple way to do this. see i also done this kind of string array and later use
try {
JSONObject jObj = new JSONObject(strDocketListResponse);
JSONArray jsonArray = jObj.getJSONArray("GetManifestDocketListResult");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject detailsObject = jsonArray.getJSONObject(i);
String strDktNo = detailsObject.getString("Docketno");
String strDocketDate = detailsObject.getString("DocketDate");
String strOrigin = detailsObject.getString("Origin");
String strDestination = detailsObject.getString("Destination");
String[] strDocketNoDkt = new String[]{strDktNo};
String[] strDocketDateDkt = new String[]{strDocketDate};
String[] strDocketOriginDkt = new String[]{strOrigin};
String[] strDocketDestnDkt = new String[]{strDestination};
for (int sanjay = 0; sanjay < strDocketNoDkt.length; sanjay++) {
ItemCheckList itemCheckList = new ItemCheckList();
itemCheckList.setDocket_NO(strDocketNoDkt[sanjay]);
itemCheckList.setDocket_Date(strDocketDateDkt[sanjay]);
itemCheckList.setDocket_Origin(strDocketOriginDkt[sanjay]);
itemCheckList.setDocket_Destination(strDocketDestnDkt[sanjay]);
checkLists.add(itemCheckList);
}
checkAdapter = new ItemCheckAdapter(ActivityManifestEntry.this, checkLists, check_all);
manifestListView.setAdapter(checkAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}

Imageadapter and listview with image from json

I have yet another question regarding displaying image on listview from json object. I checked almost every possible answers on stackoverflow but did not find any solution. I have following implementation
contact = json.getJSONArray(TAG_CONTACT);
for(int i = 0; i < contact.length(); i++){
JSONObject c = contact.getJSONObject(i);
//put json obkject on variable
String fname = c.getString(TAG_NAME);
String uname = c.getString(TAG_UNAME);
String type = c.getString(TAG_TYPE);
String email = c.getString(TAG_EMAIL);
String thumb = c.getString(TAG_THUMB);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, fname);
map.put(TAG_UNAME, uname);
map.put(TAG_TYPE, type);
map.put(TAG_EMAIL, email);
map.put(TAG_THUMB, thumb);
contactlist.add(map);
// Finding the list view
list=(ListView)findViewById(R.id.contactlist);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
// Put data on listview content
ListAdapter adapter = new SimpleAdapter(ContactPage.this, contactlist,
R.layout.contact_list,
new String[] {TAG_NAME,TAG_UNAME,TAG_TYPE,TAG_EMAIL,TAG_THUMB}, new int[] {
R.id.contact_name,R.id.contact_usertype,R.id.contact_status,R.id.contact_email,R.id.contact_image});
list.setAdapter(adapter);
Now where and how shall I implement the imgLoader.DisplayImage(url, imageView) in my code if I have image URL on thumb , i.e c.getString(TAG_THUMB);
Thanks in advance.

Sometimes json Array appears with images and sometimes empty array

Sometime json array appears with image url's and sometimes it is empty. I am using the following code where array with image url displaying data and image in listview but when array is empty then data is also not displaying. How can i slove this? Any answer will be appreciated
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
JSONArray posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
String slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
String url = thumbnail.getString(KEY_URL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);

Issue converting JSON to HashMap in Android

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++) {
....
}

Categories

Resources