I have this arraylist hashmap
tasklist = new ArrayList>();
then I store its contents to a preference
temp = new HashMap<String, String>();
temp.put("action", spinnerAction.getSelectedItem().toString());
temp.put("task", spinnerCourse.getSelectedItem().toString() + ": " + spinnerChapter.getSelectedItem().toString());
tasklist.add(temp);
adapterShowTask.notifyDataSetChanged();
editor.putString("taskpref", tasklist.toString());
editor.commit();
here is how I retrieve it:
String storedCollection = sPrefs.getString("taskpref", "");
the contents of storedCollection looks like this:
["{action= some text, task= some text}", "{action= some text 2, task= some text 2 }" ]
My question is, how do I retrieve the specific string (Action and task) and load it again to the arraylist hashmap?
That's the JsonString you need to get using jsonparser,I suggested you to learn How to parse the String json,There is been a lot of great tutorial online
String storedCollection = sPrefs.getString("taskpref", "");
JSONArray jarray=new JSONArray(stroredCollection);
ArrayList<String> action=new ArrayList<String>();
ArrayList<String> task=new ArrayList<String>();
for(i=0;i<jarray.length();i++){
String action=jarray.getJSONObject(i).getString("action");
String task=jarray.getJSONObject(i).getString("task");
}
Related
I am making a request from my app to a server which is returning an array. I want to put that array into a listView but the the whole array is treated as a single listItem.
As the response is recieved in a string variable i want to convert it to a string array?
any help is appretiated.. Thanks
Just replace arr with your String Array variable name:
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Firstly string response data split by space[Available special character] or assign string array.
String yourdata = "A B C D E F G H";
String[] yourtDataArr = yourdata.split(" ");
ArrayList<String> list = new ArrayList<String>();
for(i =0;i<yourtDataArr.length;i++){
list.add(yourtDataArr[i]);
}
Then use your list on ListView. You can see following example.
http://www.vogella.com/tutorials/AndroidListView/article.html
https://www.tutorialspoint.com/android/android_list_view.htm
http://windrealm.org/tutorials/android/android-listview.php
I have a JSONObject like this
{"message":{"context":"ws","data":"","id":"12345","http_accept":"json","method":"GET","search_key":"cat"},"response":{"1":"cat", "2":"catte"},"status":"OK","code":200}.
I am trying to get the result of a search webservice. I want the value of the pairs from the "response" key to add them to an ArrayList.
For example, from this "response" I want "cat" and "catte". How can I parse to get them?
Use a JSON Iterator to loop over all the keys and collect the response values.
JSONObject root = new JSONObject(jsonInput);
JSONObject resp = root.getJSONObject("response");
List<String> respList = new ArrayList<String>();
for (Iterator<String> iterator = resp.keys(); iterator.hasNext();) {
String key = iterator.next();
respList.add(resp.getString(key));
System.out.println(key + " = " + resp.getString(key));
}
System.out.println(respList);
Output :
1 = cat 2 = catte [cat, catte]
"response"s structure is map. You can easily parse it with Gson. example here
I've a json output which returns something like this :
[
{
"title":"facebook",
"description":"social networking website",
"url":"http://www.facebook.com"
},
{
"title":"WoW",
"description":"game",
"url":"http://us.battle.net/wow/"
},
{
"title":"google",
"description":"search engine",
"url":"http://www.google.com"
}
]
I am familiar with parsing json having the title object, but i've no clue about how to parse the above json as it is missing the title object. Can you please provide me with some hints/examples so i can check them and work on parsing the above code?
Note : I've checked a similar example here but it doesn't have a satisfactory solution.
Your JSON is an array of objects.
The whole idea around Gson (and other JSON serialization/deserialization) libraries is that you wind up with your own POJOs in the end.
Here's how to create a POJO that represents the object contained in the array and get a List of them from that JSON:
public class App
{
public static void main( String[] args )
{
String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
"\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
"\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
"\"url\":\"http://www.google.com\"}]";
// The next 3 lines are all that is required to parse your JSON
// into a List of your POJO
Gson gson = new Gson();
Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
List<WebsiteInfo> list = gson.fromJson(json, type);
// Show that you have the contents as expected.
for (WebsiteInfo i : list)
{
System.out.println(i.title + " : " + i.description);
}
}
}
// Simple POJO just for demonstration. Normally
// these would be private with getters/setters
class WebsiteInfo
{
String title;
String description;
String url;
}
Output:
facebook : social networking website
WoW : game
google : search engine
Edit to add: Because the JSON is an array of things, the use of the TypeToken is required to get to a List because generics are involved. You could actually do the following without it:
WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class);
You now have an array of your WebsiteInfo objects from one line of code. That being said, using a generic Collection or List as demonstrated is far more flexible and generally recommended.
You can read more about this in the Gson users guide
JSONArray jsonArr = new JSONArray(jsonResponse);
for(int i=0;i<jsonArr.length();i++){
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}
use JSONObject.has(String name) to check an key name exist in current json or not for example
JSONArray jsonArray = new JSONArray("json String");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonobj = jsonArray.getJSONObject(i);
String title ="";
if(jsonobj.has("title")){ // check if title exist in JSONObject
String title = jsonobj.getString("title"); // get title
}
else{
title="default value here";
}
}
JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
.....
}
I have worked in soap message, and to parse the value from Webservice, the values are stored in ArrayList.
Example:
values are Employee name (Siva) and Employee id (3433fd), these two values are stored in arraylist, but I want to stored in Dictionary, How?
you can use HashMap like this
Map <String,String> map = new HashMap<String,String>();
//add items
map.put("3433fd","Siva");
//get items
String employeeName =(String) map.get("3433fd");
You can use Bundle.
as it offers String to various types of Mapping.
Bundle b = new Bundle();
b.putInt("identifier", 121);
b.putString("identifier", "Any String");
b.putStringArray("identifier", stringArray);
int i = b.getInt("identifier");
...
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText textview = (EditText) findViewById(R.id.editTextHash);
EditText textviewNew = (EditText) findViewById(R.id.editTextHash2);
Map<String, String> map = new HashMap<String,String>();
map.put("iOS", "100");
map.put("Android", "101");
map.put("Java", "102");
map.put(".Net", "103");
String TextString = "";
// Set<E> keys = map.keySet();
Set keys = map.keySet();
System.out.println("keys "+keys);
for (Iterator i = keys.iterator(); i.hasNext();)
{
String key = (String) i.next();
System.out.println("key "+key);
String value = (String) map.get(key);
System.out.println("value "+value);
textview.append(key + " = " + value);
TextString+=(key + " = " + value);
}
//textviewNew.setText(TextString);
// Iterator iterator = map.keySet().iterator();
//
// while (iterator.hasNext())
// {
// String object = (String) iterator.next();
// textview.setText(object);
// }
//
// //textview.setText(map.get("Siva"));
//
// System.out.println(map);
}
}
A Dictionary is an abstract class that maps keys to values and there is Dictionary Class in android refer link you can find a note at Class Overview
Do not use this class since it is obsolete. Please use the Map
interface for new implementations.
An attempt to insert either a null key or a null value to a dictionary will result to a NullPointerException,but you can use Map interface,it provides the exact same functionality of a dictionary.you can use it as bellow
//put values
Map Message = new HashMap();
Message.put("title", "Test message");
Message.put("description", "message description");
Message.put("email", "email#gmail.com");
//get values
Log.d("get Message","Message title -"+Message.get("title"));
you can also use A custom class as below
public class MessageObject {
String title;
String description;
String email;
}
you can use Getters and Setters to get and put values,not needed to remember the key names every time you may get some other advantages by this way.
Hi friends i got stucked into these problem at the last stage of my program.Here is some description about my project:i am calling a web service with the help of Ksoap and getting the JSON response from the server than,i am parsed that response and store it into the correspondent arraylist.Till here everything is working fine.Now the problem starts here i want to store all these AppID,AppName,AppTabID,Icon,Tabname into a multimap with same key for the same index.How can i achieve that ?Any help would highly appreciated!
private SoapPrimitive response;
ArrayList<String> AppID = new ArrayList<String>();
ArrayList<String> AppName = new ArrayList<String>();
ArrayList<String> AppTabId = new ArrayList<String>();
ArrayList<String> Icon = new ArrayList<String>();
ArrayList<Drawable> drawables=new ArrayList<Drawable>();
ArrayList<String> TabName = new ArrayList<String>();
<!--here are the Arraylist declaration->
public String parse(String a) throws Exception {
JSONArray jsonArry1 = new JSONArray(res); // create a json object from a string
// JSONArray jsonEvents = jsonObj.optJSONArray("AppItems"); // get all events as json objects from AppItems array
System.out.println("Length of array for AppItem tag is.. "+jsonArry1.length());
for(int i = 0; i < jsonArry1.length(); i++){
JSONObject event = jsonArry1.getJSONObject(i); // create a single event jsonObject
String AppID=event.getString("AppId");
System.out.println("AppId is "+AppID);
String AppName=event.getString("AppName");
System.out.println("AppName is "+AppName);
String AppTabId=event.getString("AppTabId");
System.out.println("AppTabId is "+AppTabId);
String Icon=event.getString("Icon");
System.out.println("Icon is "+Icon);
TabHtml=event.getString("TabHtml");
System.out.println("TabHtml = "+TabHtml);
}
System.out.println("return"+TabHtml);
return TabHtml;
}
the above code i am using for saving all the content into arraylist object.From here i want to set all these diferent Arraylist into same MultiMap.How can i achieve that?
I'd just define an AppData container class to hold all data related to a single response, and then just put AppData objects into your multimap.
On this link (Java Map Interface) search for multimap which gives a straight forward implementation of a multimap.
However from what I understand of your question, you'll have to put all your Lists into a List and that would go into a MultiMap (which will just be a HashMap<String,ArrayList<ArrayList>>).
It is not very good approach to have all these different lists for different fields in response, but as you have implemented almost completed, I would lead this approach further:
You can have a Map into map to resolve this prob:
All you need to have follow the below loop:
HashMap<Integer, HashMap<String, String> parsed=new HashMap<Integer, HashMap<String, String>();
for(int i=0;i<AppID.size();i++)
{
HashMap<String, String> keyValues= new HashMap<String, String>();
keyValues.put("id", AppName .get(0));
keyValues.put("id", AppTabId .get(0));
keyValues.put("id", Icon .get(0));
.....
parsed(new Integer(i), keyValues);
}