I'm already able to get the JSON ArrayList and display the data using RecyclerView.
Here's how I display the JSON array using RecyclerView :
public void onResponse(Call<List<Fame>> call, Response<List<Fame>> response) {
List<Fame> fame = response.body();
mFameList.addAll(fame);
adapter.notifyDatasetChanged();
progressDialog.dismiss();
rv.setVisibility(View.VISIBLE);
title_text.setVisibility(View.VISIBLE);
}
However, for one activity, I only need to get the values and store them to variables. I'm thinking of looping through the list but not really sure if what I'm doing is right. After storing the values to variables, I'll be able to display images based on the values. Any help is much appreciated.
Here's what I've tried so far, but it's giving me a nullpointer exception error. It works if the JSON array contains only 1 result/item.
progressDialog.dismiss();
List<Profile> p = response.body();
if(p!=null && p.size()>0){
pid = p.get(0).getPid();
fname =p.get(0).getFname();
lname = p.get(0).getLname();
}
Here's a sample of the JSON:
[
{
"Pid": "testID",
"Fname": "testfname1",
"Lname": "testlname1",
},
{
"Pid": "testID",
"Fname": "testfname2",
"Lname": "testlname2",
}
]
So here's how I managed to solve the problem:
List<Fame> fame = response.body();
for(Fame f: fame ){
if(f.getfName.toString() == "testfname1"){
//do something if condition is met
}
//repeat step for others
}
I'm not sure if it's the best way to do it but it satisfies my requirements for now. :)
Related
I'm loading a json array in my app.but i need to know if the json array is exist or not? because if the json array isn't exist, the app will crash.
for example, I have this json:
{
"music1":
[
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
]
}
and I want to know is there any json object named "music1" in my code or not, and then if there was I want to get the json array and show it in a list in my android app.
I'm looking forward a hero that could help me!
I wish this explanation would fit in a comment.
Anyway:
{
"music1":
[
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
}
]
}
Let call the above json object o.
So to check if o has music1, all you need to check is write the following line:
if(o.has("music1")){
JSONArray array= o.getJSONArray("music1");
}
Then you extract the objects of the json array :
for(int i=0;i<array.length();i++){
array.getJSONObject(i);
}
Check the availability of field:
if(jsonObj.has("music1")){
//yes
}
or this case:
JSONArray mJSONArray = jsonObj.optJSONArray("nmusic1");
If array is not available mJSONArray will be null
I am trying to retrieve the Restaurant Name data from Firebase and output them in individual lines on ListView. I created a sample of the data which only consists of numbers(strings).
Retrieving the data seems fine as I could output them line by line in console, but my Hashmap is saving everything into the same "node" or "field"
Can anyone help me understand what I did wrong?
#Override
public void onDataChange(DataSnapshot Snapshot) {
int x = 1;
//Do some stuff once
for (DataSnapshot RestNames : Snapshot.getChildren()) {
name = RestNames.getValue().toString();
//System.out.println(name);
map.put(x, name);
x=x+1;
}
System.out.println(map);
Items.add(map);
System.out.println(Items);
listView.setAdapter(mgadapter);
}
The Output in the console is as follows :
{8=3456, 11=9, 9=34567, 5=3, 3=3, 4=4, 10=0, 1=1, 7=345, 6=34, 2=2}
Android emulator shows the same value for every single row.
I want to display each value on a separate row.
Thank you!
EDIT: SNIPPET OF JSON
{
"Eat": {
"Name": {
"-Jy3yehAkgqhg4knlxx_": "1",
"-Jy3yjQT2AxtZMqD2kov": "2",
"-Jy3yk96Mo5MKOEEzviJ": "3",
"-Jy3yksamL08R0BckxNZ": "4",
"-Jy5JBJYZUTxZQtmdDmi": "3",
"-Jy5JIXT_lDZrUOkF3T1": "34",
"-Jy5JJ0oMqGrs2vfFge2": "345",
"-Jy5JJTyET830PYOT3yA": "3456",
"-Jy5JJu-jDGMDXncWDKf": "34567",
"-Jy5JVejdsUtggM8vBoi": "0",
"-Jy5JbwEoWrKAi6XIVQY": "9"
}
}
}
Since we're missing some code in your snippet, I completed it an ran it locally:
Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/32367022/Eat/Name");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
int x = 1;
Map<Integer,Object> map = new HashMap<Integer, Object>();
for (DataSnapshot child: snapshot.getChildren()) {
String name = child.getValue().toString();
System.out.println(name);
map.put(x, name);
x=x+1;
}
System.out.println(map);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
This prints out the following for me:
1
2
3
4
3
34
345
3456
34567
0
9
{1=1, 2=2, 3=3, 4=4, 5=3, 6=34, 7=345, 8=3456, 9=34567, 10=0, 11=9}
The first lines show the output from inside the for loop. The last lines shows the HashMap.
I use the most basic of Java classes, and this behavior seems correct to me.
I expect that the System.out.println(name); inside the for loop will display the same output as above for you, because the Firebase SDK handles ordering there.
If the order in the loop is correct, either your map or your Items object changes the order. It is impossible to say without seeing the types of these.
But in general, the approach above is how you should troubleshoot this problem: isolate it to a single object/class and then either fix what's wrong with that class (if it's your code) or replace it with a class that works for your use-case (if it comes from a library).
Update: I created a minimal app that shows the numbers in the correct order in a list view in this Github repo.
I am using Parse.com as my backend, and I want to download data from server. I have tags which filter these data. Unfortunately it works wrong. Lets say I have two tags "city1" and "city2", now I only get data for "city1".
public ArrayList<Dataset> getDatasetFromServer(Context context) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Dataset");
List<String> cities = DatabaseAdapter.getCityNames(context);
//cities list contains "city1" and "city2"
query.whereContainedIn("cities", Arrays.asList(cities.toArray(new String[cities.size()])));
ArrayList<Dataset> dataset = new ArrayList<>();
try {
List<ParseObject> parseDataset = query.find();
dataset = setDatasetList(parseDataset);
} catch (ParseException e) {
e.printStackTrace();
}
return dataset;
}
The problem is with this : Arrays.asList(cities.toArray(new String[cities.size()]).
Don't know why, but this convertion works wrong with Parse.
However, if I change above line to this
String[] array = {"city1", "city2"};
query.whereContainedIn("cities", Arrays.asList(array));
Everything works fine and I get data for city1 and city2.
My question is, what's the difference between these two solutions and how to fix this so the first solution works?
EDIT :
This also doesn't work :
query.whereContainedIn("cities", DatabaseAdapter.getCityNames(context));
getCityNames returns List<String>
Instead of converting your list to an array and then back to a list, just do this:
query.whereContainedIn("cities", cities);
The problem was my fault. Both solutions work good.
The reason it didn't worked was that my method
DatabaseAdapter.getCityNames(context) put a whitespace on the beggining of second element which I didn't saw.
I found a lot of tutorials here, how to parse JSON Data of an JSON Array.
But my JSON File is a little bit complicate (for me). It has the following structure:
JSON File (excerpt)
{
"data": {
"schedule_id": {
"12": {
"name": "CP",
"d_id": [
"7"
]
},
"17": {
"name": "WT",
"d_id": [
"88",
"14"
]
}
}
}
}
Java Code (excerpt)
Info: I've parsed the json into "json" using HTTP GET in another Activity.
JSONObject dataJsonData = json.getJSONObject("data").getJSONObject("schedule_id");
Now I would parse through the ids using a "for"-loop:
ArrayList<String> parsedNameList = new ArrayList<String>();
for (int i = 0; i < idontknow; i++) {
String s = new Integer(i).toString();
parsedNameList.add(dateJsonData.getJSONObject(i).getString("name"));
}
This would add each value of "name" to the ArrayList.
But there are 2 problems:
1. The "schedule_id"s are messed up and incomplete. For example, there is no id "0" and, like in given json, the ids "13, 14, 15, 16" are missing.
2. The "schedule_id"s will be changed every day and will be mixed.
So I don't think, that I can use the predefined integer "i" because some integers aren't a "schedule_id". I could use this loop and would ignore empty entries in the ArrayList, but the JSON contains more than 200 ids - I think it would be more efficient, if there is another way to parse through this json.
I found some informations of the getJSONArray method, but the "d_id"s are Arrays - not the "schedule_ids".
Does anyone has an idea? Is there maybe a placeholder for the parameter of the getString method?
PS: Excuse my english, I'm from germany :)
I think this should work
Iterator keys = dataJsonData.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
String currentDynamicValue = dataJsonData .getString(currentDynamicKey);
parsedJsonList.add(currentDynamicValue );
}
Source: How to parse a dynamic JSON key in a Nested JSON result?
According to your context, it is better to change the json structure,if you have access to web service.
Request for json structure to be like this,
{
"data":{
"schedule":[
{
"id":12,
"name":"CP",
"d_id":[
"7"
]
},
{
"id":12,
"name":"CP",
"d_id":[
"7",
"88"
]
},
{
"id":200,
"name":"AT",
"d_id":[
"7",
"88"
]
}
]
}
}
Otherwise too much iteration can slow down you CPU.
I have a JSON as below
{
"shippingGroupListJson":[
{
"lineId":123,
"shippedTo":{
"country":"US"
},
"cartons":1,
"group":"4",
"shipInscription":{
"municipalInscription":"",
"inscriptionType":"",
"stateInscription":"",
"suframaInscriptionNumber":"",
"inscriptionBranch":"",
"contributorClass":"",
"inscriptionDigit":"",
"inscriptionNumber":""
},
"shipCartonDetails":[
],
"shippedContact":{
"firstName":"Mjjkk",
"email":"nob#gmail.com",
"fax":"--",
"phone":"80-121",
"lastName":"Henry"
},
"mobilityShipStatus":"Not Yet Shipped",
"shipDate":"13 Dec 2014"
},
{
"lineId":0,
"shippedTo":[
],
"cartons":0,
"group":"5",
"shipInscription":[
],
"shipCartonDetails":[
],
"shippedContact":[
],
"mobilityShipStatus":"",
"shipDate":"",
"shipStatus":""
}
]
}
If you see in this above JSON in key "shippedTo", when there is value , I get a JSON Object and when no value is present then i get a Blank JSONArray.
I need to fix this issue. I cannot communicate with the service team to change this as they won't make changes to it. Can any one tell me how can i do the required changes.
I know this is not the rite way, but i need to do something..
I tried using String.replaceAll(oldChar,newChar);
You say you are using GSON, in which case JsonArray and JsonObject are both subclasses of JsonElement.
But you do not say if you are using the DOM or Streaming technique with GSON.
You should show your parsing code, or the class that's being automatically used for the parsing.
In the meantime, based on what you have said, I would define my shippedTo field in my class as an Object. That should parse correctly (if using DOM), and after that you can analyse exactly what you have in that field.
Instead of:
private MyCountryType shippedTo;
Have:
private Object shippedTo;
You could simply check its type at runtime i.e
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
if(js.get("shippedTo") instanceof JSONArray){
//Treat it as an array
}
else{
//Treat it as a single json object
}
}
Furthermore if you need it as an JSONObject immaterial of it being a single element then do this to get your customized string
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
JSONObject js=new JSONObject(json_data);
if(js.get("shippedTo") instanceof JSONArray){
js.put("shippedTo",new JSONObject()); //purge the original array with this new blank element
}
else{
//Do your normal stuff
}
}
String curmodstring=jsPar.toString();
Hope you get the general idea.