Android storing arraylist data into multimap using same key - android

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

Related

Data from API parsing in for cycle with bad result

I parse data from API (https://statsapi.web.nhl.com/api/v1/standings) in for cycle. In debug mode, I see, that data are correct from API, but when I write first record to "tabulkaTimov", and for cycle have j=1 (j=2,j=3, ... etc), my first record is replace by next team.
Screenshot of my app:
https://ctrlv.cz/shots/2019/01/03/bbEf.png
It is table of NHL league.
public static List<TableTeamsModel> convertJsonToTableTeams(JsonObject data){
List<TableTeamsModel> tabulkaTimov = new ArrayList<>();
JsonArray pocetDivizii = data.get("records").getAsJsonArray();
for(int i=0;i<pocetDivizii.size();i++){
TableTeamsModel tabulka = new TableTeamsModel();
JsonObject division = pocetDivizii.get(i).getAsJsonObject();
tabulka.setDivisionName(division.get("division").getAsJsonObject().get("name").getAsString());
JsonArray teams = division.get("teamRecords").getAsJsonArray();
for(int j=0;j<teams.size();j++) {
JsonObject teamRecords = teams.get(j).getAsJsonObject();
tabulka.setTeamName(teamRecords.get("team").getAsJsonObject().get("name").getAsString());
tabulka.setGoalsGot(teamRecords.get("goalsAgainst").getAsInt());
tabulka.setGoalsScored(teamRecords.get("goalsScored").getAsInt());
tabulka.setPoints(teamRecords.get("points").getAsInt());
tabulka.setGamesPlayed(teamRecords.get("gamesPlayed").getAsInt());
tabulkaTimov.add(tabulka);
}
}
return tabulkaTimov;
}
Looks like you are creating a new tabulka object outside of your for loop and then add it multiple times in the same arraylist.
This will add it once (reference) and just update its content.
Here is what you can do
public static List<TableTeamsModel> convertJsonToTableTeams(JsonObject data){
List<TableTeamsModel> tabulkaTimov = new ArrayList<>();
JsonArray pocetDivizii = data.get("records").getAsJsonArray();
for(int i=0;i<pocetDivizii.size();i++){
// Remove the creation of the tabulka object from here
JsonObject division = pocetDivizii.get(i).getAsJsonObject()
JsonArray teams = division.get("teamRecords").getAsJsonArray();
for(int j=0;j<teams.size();j++) {
JsonObject teamRecords = teams.get(j).getAsJsonObject();
// And then put the object creation here.
// as we did't have it above, the division name has to be set here too.
TableTeamsModel tabulka = new TableTeamsModel();
tabulka.setDivisionName(division.get("name").getAsString());
tabulka.setTeamName(teamRecords.get("team").getAsJsonObject().get("name").getAsString());
tabulka.setGoalsGot(teamRecords.get("goalsAgainst").getAsInt());
tabulka.setGoalsScored(teamRecords.get("goalsScored").getAsInt());
tabulka.setPoints(teamRecords.get("points").getAsInt());
tabulka.setGamesPlayed(teamRecords.get("gamesPlayed").getAsInt());
tabulkaTimov.add(tabulka);
}
}
return tabulkaTimov;
}
This way you will add a different/new object each time you go over the loop into your ArrayList; - instead of adding the same reference of the same object every time with its data updated.

Android button click next display of listview of data in JSON

hi can you help me how to display the next 10 data in json by click the next button. i have 50 data and i want to display first 10. Then when I click the next button, 11-20 will display in listview. Ill post my code below and i dont have any idea how to do it. Also when i click previous button it will go back to previous listview which is 1-10. Thanks!
doctordata = new ArrayList<Map<String, String>>();
try {
jsonObject = new JSONObject(d);
jsonArray = jsonObject.optJSONArray("Doctors");
int arraylength = jsonArray.length();
for (int i = 0; i < arraylength; i++) {
Map<String, String> doctormap = new HashMap<String, String>();
JSONObject jsonChildNode = jsonArray.getJSONObject(i);
doctor = jsonChildNode.optString("Name").toString();
specialty = jsonChildNode.optString("Specialty").toString();
doctormap.put("name", doctor);
doctormap.put("specialty", specialty);
doctordata.add(doctormap);
}
String[] from = {"name", "specialty"};
int[] views = {R.id.doctorlist_name, R.id.doctorlist_specialty,};
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, doctordata, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
} catch (JSONException e) {
e.printStackTrace();
}
Define a class called Doctors, with fields String name and String Specialty, and add the Doctors to a list that you can iterate or convert to Array.
class Doctors {
private final String specialty;
private final String name;
public Doctors (){
specialty= "Spe1";
name = "name";
}
}
public String convertToJson(){
Gson gson = new Gson();
return gson.toJson(this);
}
Ok, there are several ways to do what do you want to achieve. I will explain you how I would do it:
Firts, in the doctorData arraylist you have all the items (50 items) that you need to show.
Create a partialDoctorData arraylist and assing to it only the first 10 items from doctorData, ok? and add this new arraylist to the SimpleAdaper.
So you will need to do instead of your code:
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, **partialDoctorData**, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
So when the user click in the next button, you can clean the partialDoctorData content, add from the 11-20 items from the original doctorData arrayList and and and directly call to the
myadapter.notifyDataSetChanged();
(you don't have to repeat the step to create a new SimpleAdapter, only changing the values of the arraylist and calling to this method, the content of the list is going to be updated with the content of the partialDoctorData)
Try ;)
Try this one:
Android ListView with Load More Button
You can use pagination when 10 items will be loaded after that you will call agin api to get next 10 items

How to get the multiple text from string in Android?

I am developing the Android for Xively. I get the following text data and store into string.
{"id":111111177,"title":"G-sensor","private":"true","feed":"https://api.xively.com/v2/feeds/111111177.json","auto_feed_url":"https://api.xively.com/v2/feeds/111111177.json","status":"frozen","updated":"2014-08-05T07:14:29.783670Z","created":"2014-08-01T08:29:17.156043Z","creator":"https://xively.com/users/x22819","version":"1.0.0","datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"}
There has id and the current_value in the above data , and I want to get the data of id and the current_value from the above text like following text.
GPIO1 1
GPIO2 0
GPIO3 1
GPIO4 0
GPIO5 1
GPIO6 0
How do I capture the the data of id and the current_value from the above text ?
Can somebody teach me how to do ?
Thank in advance.
Try this:
String resultJSON = "datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},
{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"};
JSONObject jsonRoot = new JSONObject(resultJSON);
JSONArray jsonData = jsonRoot.getJSONArray("Data");
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonOBject = jsonData.getJSONObject(i);
Log.d(TAG, "json ("+i+") = "+jsonOBject.toString());
// do what you want with your JSONObject , i.e :add it to an ArrayList of paresed result
String ID = jsonOBject.getString("id");
}
Hope this may help you
dataList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
myarray = jsonObj.getJSONArray("datastreams");
// looping through All myarray
for (int i = 0; i < myarray.length(); i++) {
JSONObject c = myarray.getJSONObject(i);
String id = c.getString("id");
String date = c.getString("at");
// tmp hashmap for single data
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ID, id);
data.put(TAG_DATE, date);
// adding data to data list
dataList.add(data);
}
The data you have is actually a JSON so you can simply parse it to java POJO. I would suggest to use one of 2 most popular open source parsers GSON or Jackson.
What you have to do is:
Create java POJOs for chosen parser. To make it easier use this online tool http://www.jsonschema2pojo.org/
Copy generated java classes to your project.
Use JSON parser e.g. GSON
Let's say you named your main class as Example, with GSON you can parse it like this:
Gson gson = new Gson();
String data = ....//your JSON data
Example example = gson.fromJson(data, Example.class);
Data you would like to get will have own Java representation and will be available through getter method, e.g.:
List<Datastream> datastreams = example.getDatastreamList();
for (DataStream data : datastreams) {
String id = data.getId();
String currentValue = data.getCurrentValue();
}
Then you can do whatever you like. Please know that GSON can also read streams, so if you already parse stream to string you can skip it and pass that stream to Gson object directly.
If you don't want redundant POJOs or their parameters, you can remove them. GSON will handle it and simply ignore these values. Just make sure that data you are interested in keep the generated structure.
That's how I would do it.

JSON Parsing - JSONObject without JSONArray

I have a api like this
-{
- meta {
item1: value;
item2: value;
item3: value;
},
- object [
{
- category {
id: 1;
...
}
- File {
...
}
},
{
- category {
id:2;
...
}
- File {
...
}
}
]
I dont have any problem to parse JSONArray of "obejct" and it's JSONObjects...
I do like this:
private static final String TAG_NOD = "object";
private static final String TAG_CAT = "category";
private static final String TAG_CAT_ID = "id";
private static final String TAG_CAT = "File";
JSONArray Items = null;
JSONObject jsonObj = new JSONObject(jsonstr); // jsonstr is loaded url by httpcal
Items = jsonObj.getJSONArray(TAG_NOD);
for ( int i=0; i<Items.length(); i++){
JSONObject childs = Items.getJSONObject(i);
JSONObject category= child.getJSONOBject(TAG_CAT);
// getting category items in string like String ID = category.getString(TAG_CAT_ID);
JSONObject file = Item.getJSONObject(TAG_FILE)
// getting file items in string like file.getString(String name)
HashMap<String, String> items = new HashMap<String, String>();
items.put(TAG_CAT_ID, ID);
.
.
.
ItemLis.add(items); //Itemlist is a ArrayList<HashMap<String, String>>()
}
but my problem is to parsing jsonobject of "meta" and add its data to my ListItem Arraylist
any solution appreciated :D
Like this:
JSONObject meta = jsonObj.getJSONObject("meta");
Iterator<String> iterator = meta.keys();
HashMap<String,String> metaMap = new HashMap<String,String>();
while (it.hasNext()) {
String key = iterator.next();
String value = meta.getString(key);
metaMap.put(key,value);
}
ItemLis.add(items);
Also, if I may, here are a couple of quick suggestions on some things I've noticed that could improve your coding style:
Per Java naming conventions, variables and member names start with a lower case letter, so it should be itemLis instead of ItemLis. You already do this on most of your names except for ItemLis and Items. While this is not a must, following convention will make your code more readable, not only to you, but also when you seek help here on SO.
Unless you specifically require that the items in ItemLis be HashMaps (that is, your algorithm will not work with any other Map implementation), it's usually considered good practice to hide that detail from the implementation. I.e. instead of HashMap<...> items = new HashMap, go like Map<...> items = new HashMap, and change the type of ItemLis from <ArrayList<HashMap<...>> to List<Map<...>>. That way, if you ever decide to change the implementation backing the list or map, your code changes will be confined to only one place, instead of breaking much of your code. As a rule of thumb: Try to declare types with the most abstract type you require.
You can use the GSON lib. Very simple and fast implemented. Best practise at this case.
Just create an object which looks like your json string.
Then call:
Gson gson = new Gson();
YourObject obj = gson.fromJson(jsonString, YourObject.class);
Then you have the data in an object and can use it with getter and setter. Maybe you have to annotate the variables in the object. For that take a look here: https://code.google.com/p/google-gson/

JSonarray to Arraylist and Arraylist in ListAdapter doesn't work. (In Android)

I've got a little problem, and i don't see it.
I retrieve Json data (the JSONArray) and i wanted to make a List of all the names in the JSONArray, something like this.
List list = new ArrayList<String>();
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
And i wanted to take this list in an `ListView' so i did this :
ArrayList<String> test = history_share.list;
names_list = (String[]) test.toArray();
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
setListAdapter(adapter);
(history_share is one of the method i created to take json data from an api .
Eclipse doesn't see any error, and me neither.
Can somebody help me please ?
Why do your methods have underscores in their names? Methods by convention begin with a lowercase letter. For example myMethod(). Class names begin with uppercase letters like MyClass. You should stick to that.
Also history_share is not a method the way you posted your code plus you won't be able to retrieve anything from a method by calling it that way.
A getter method just returns the defined member. I'm very surprised that Eclipse doesn't highlight that. Are you sure error checking is turned on?
Update: Naming your classes like already existing classes is generally a very bad idea and it gets even worse if you plan to use the original class somewhere or any class deriving that class. In the original Connection class I cant spot any static member called list which leads to the assumption that you've created your own Connection class. This doesn't have to be the problem here but it may raise problems in the future if you continue to do that.
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
.getString("names") returns String, remove .toString()
Also,
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
replace with
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names_list);
You try this using ArrayList with Hashmap:
ArrayList<HashMap<String, String>> comunitylist = new ArrayList<HashMap<String, String>>();
String url =_url + _uid + uid;
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(url,apikey);
Log.e("kPN", json);
try
{
JSONObject jobj = new JSONObject(json);
Log.e("kPN", json.toString());
System.out.print(json);
JSONArray comarray = jobj.getJSONArray(TAG_COMMU);
for(int i = 0; i <= comarray.length(); i++){
JSONObject c = comarray.getJSONObject(i);
Log.w("obj", c.toString());
JSONObject d = c.getJSONObject(TAG_PERSON);
Log.w("obj", d.toString());
String name =d.getString(TAG_NAME);
Log.w("name", name);
String nick =d.getString(TAG_NICK);
String home = d.getString(TAG_HOME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_NICK, nick);
}
}
catch (JSONException ie)
{
}
list=(ListView)findViewById(R.id.list);
adapter=new Lazycommunity(this,listz);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Having Trouble with this line, how to retrieve value???
HashMap<String, String> map2 = (HashMap<String, String>) list.getAdapter().getItem(position);
Intent in = new Intent(getApplicationContext(), Communityprofile.class);
in.putExtra(TAG_NAME, map2.get(TAG_NAME));
in.putExtra(TAG_IMG, map2.get(TAG_IMG));
startActivity(in);
}
});

Categories

Resources