I am facing an issue while saving a HashMap on Parse and then retrieving it.
Below is the code to put data in the ParseObject.
HashMap<Object, Object> eventInfo = new HashMap<>();
eventInfo.put(ParseTable.Column.AllDay, allday);
JSONArray dateSet = new JSONArray();
JSONObject sdObj = new JSONObject();
sdObj.put("__type", "String");
sdObj.put("iso", sdf.format(sdate));
JSONObject edObj = new JSONObject();
edObj.put("__type", "String");
edObj.put("iso", sdf.format(rEnd.getTime()));
dateSet.put(sdObj);
dateSet.put(edObj);
eventInfo.put(ParseTable.Column.DateSet, dateSet);
eventInfo.put(ParseTable.Column.EventType, eType.getText().toString());
eventInfo.put(ParseTable.Column.Location, loc.getText().toString());
eventInfo.put(ParseTable.Column.Points, points.getText().toString());
obj.put(ParseTable.Column.EventInfo, eventInfo);
Now when I get this data from the same object in which I have set it, its correct.
{eventType=Default, location=, allDay=false, dateSet=[{"__type":"String","iso":"2015-02-25T21:18:00Z"},{"__type":"String","iso":"2015-02-28T00:00:00Z"}], points=}
This also saves properly on server:
{"allDay":false,"dateSet":[{"__type":"String","iso":"2015-02-25T21:18:00Z"},{"__type":"String","iso":"2015-02-28T00:00:00Z"}],"eventType":"Default","location":"","points":""}
But when I retrieve the same data from Parse server, this is what it returns, when I log the HashMap:
{eventType=Default, location=, allDay=false, dateSet=[null, null], points=}
Don't know why this is happening.
The reason why you are getting a blank field is because you are calling getMap on a blank/empty event object.
Map<String, Object> oinfo = event.getMap(ParseTable.Column.EventInfo);
I can't see where your event object comes from but I also don't see that you have saved any of this data to the database.
So make sure that obj has been saved:
obj.saveInBackground()
Then you can get your eventInfo out after making a query:
ParseQuery q = ParseQuery.getQuery("YourClass");
q.whereEqualTo("someColumnName", "someValue");
q.findInBackground(new FindCallback() {
#Override
public void done(List objects, ParseException paramParseException) {
for (Object o: objects){
Map<String, Object> oinfo = o.getMap(ParseTable.Column.EventInfo);
}
}
});
If you are actually saving the obj already to the database and only attempting to grab data from a populated event object then please update your question with each step you are taking to get the data from the server. I would like to see the entire lifecycle of the event object.
Related
I'm fairly new to Android Studio and Java, and I'm working on an app that takes data from Unsplash's API and displays it. However, I'm getting a JSON typeMismatch error, and I'm not sure how to correctly extract the data. Technically I'm getting back an array of JSONObjects, but I'm finding that simply changing JSONObject to JSONArray is not the correct approach.
I believe the problem is with the following lines of code: What I want to do is get the user (photographer) name and profile image, and the image they're posting.
Any help is greatly appreciated!
private NewPhotos getNewPhotos(String jsonData) throws JSONException {
JSONObject unsplash = new JSONObject(jsonData);
JSONObject user = unsplash.getJSONObject("user");
return new NewPhotos();
}
This is the JSON I'm getting back
This is the error message
You need first, cast JSON ARRAY.
You didn't put all json file, but it seems to be an array first.
private NewPhotos getNewPhotos(String jsonData) throws JSONException {
JSONArray unsplash = new JSONArray(jsonData);
for (int i = 0; i < unsplash.length(); i++) {
JSONObject jsonObj = (JSONObject) unsplash.get(i);
JSONObject user = jsonObj.getJSONObject("user");
// Do something with user
}
// Your implementation
return new NewPhotos();
}
This doesn't work for you? :
JSONObject unsplash = new JSONObject(jsonData);
JSONArray user = unsplash.getJSONArray("user");
Cause in your code you're trying to assign jsonArray to jsonObject.
You can't convery JSON Array into a Json object. Rafaela is right. You need to pass the string in Json array and then loop through each object to access user json.
I would like to ask if someone here knows how to convert a HashMap to JSON Array to be used on a Adapter. The logic is when you logged in, it will fetch data on a web server using Volley, store it on SQLite database and at the same time it will show the retrieve data on a custom listview. The thing is, if you will move to another fragment on the application and then go back, it will request again on the volley which it will take time. I wanted that if you will go back the data stored on the SQLite database will be retrieved and if the user wanted to update the data using SwipeRefresh, that's the time to update for new data.
Here is my code.
public void LoadMarkets()
{
Map<String,String>tmpRate = new HashMap<String,String>();
RateDb db = new RateDb(getActivity().getApplicationContext());
Cursor rs = db.getData();
if(rs!=null && rs.getCount()>0)
{
if(rs.moveToFirst())
{
while(rs.moveToNext())
{
tmpRate.put("rateID",rs.getString(rs.getColumnIndex(RateDb.rateID)));
tmpRate.put("Name",rs.getString(rs.getColumnIndex(RateDb.rateName)));
tmpRate.put("Rate",rs.getString(rs.getColumnIndex(RateDb.rateRate)));
tmpRate.put("Date",rs.getString(rs.getColumnIndex(RateDb.rateDate)));
tmpRate.put("Time",rs.getString(rs.getColumnIndex(RateDb.rateTime)));
tmpRate.put("Ask",rs.getString(rs.getColumnIndex(RateDb.rateAsk)));
tmpRate.put("Bid",rs.getString(rs.getColumnIndex(RateDb.rateBid)));
tmpRate.put("Balance",rs.getString(rs.getColumnIndex(RateDb.rateBalance)));
//Log.d("MyDebug",rs.getString(rs.getColumnIndex(RateDb.rateName)));
}
}
}
rs.close();
db.close();
JSONObject jsonObject = new JSONObject(tmpRate);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
RowAAdapter rowAAdapter = new RowAAdapter(getActivity(),jsonArray);
lvMarkets.setAdapter(rowAAdapter);
swipeRefreshLayout.setRefreshing(false);
}
The problem is that when i load this function, it only shows the last data.
I hope you can help me with my problem.
Thank you very much.
You can put the values directly into the jsonObject instead of adding it to the hashmap like this :
public void LoadMarkets()
{
RateDb db = new RateDb(getActivity().getApplicationContext());
Cursor rs = db.getData();
if(rs!=null && rs.getCount()>0)
{
if(rs.moveToFirst())
{
while(rs.moveToNext())
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("rateID",rs.getString(rs.getColumnIndex(RateDb.rateID)));
jsonObject.put("Name",rs.getString(rs.getColumnIndex(RateDb.rateName)));
jsonObject.put("Rate",rs.getString(rs.getColumnIndex(RateDb.rateRate)));
jsonObject.put("Date",rs.getString(rs.getColumnIndex(RateDb.rateDate)));
jsonObject.put("Time",rs.getString(rs.getColumnIndex(RateDb.rateTime)));
jsonObject.put("Ask",rs.getString(rs.getColumnIndex(RateDb.rateAsk)));
jsonObject.put("Bid",rs.getString(rs.getColumnIndex(RateDb.rateBid)));
jsonObject.put("Balance",rs.getString(rs.getColumnIndex(RateDb.rateBalance)));
jsonArray.put(jsonObject);
//Log.d("MyDebug",rs.getString(rs.getColumnIndex(RateDb.rateName)));
}
}
}
rs.close();
db.close();
RowAAdapter rowAAdapter = new RowAAdapter(getActivity(),jsonArray);
lvMarkets.setAdapter(rowAAdapter);
swipeRefreshLayout.setRefreshing(false);
}
The problem with your code is that :
You're putting the values with keys "rateID", "Name"... etc. in the while loop again and again, so the previous values are being replaced with the new values and finally you've just one set of data in your hashmap. That's why you're getting only the last set of data.
Try the above code. It should work as expected.
This will work as it creates a new JsonObject in the loop and adds it to the jsonArray when the data is successfully added to it.
I have a piece of code which basically synchronises data between an online database. However I am getting an error on one particular line of code (map.put("id", obj.get(mydb.WEB_ID).toString());) where an integer value is obtained from the android sqlite databasse and submitted to the online database. The full cose is as displayed below :
public void updateSQLite(String response){
ArrayList<HashMap<String, String>> syncL;
syncL = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has userid and username
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("web_id"));
System.out.println(obj.get("phone_id"));
System.out.println(obj.get("msg_id"));
mydb.updateWebSync(obj.get(obj.get("phone_id").toString(), obj.get("msg_id").toString(), obj.get("web_id").toString());
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", obj.get(mydb.WEB_ID).toString());
map.put("p_id", obj.get(mydb.COLUMN_ID).toString());
map.put("s", "1");
syncL.add(map);
}
updateMySQLSyncSts(gson.toJson(syncL), "syncsts");
Toast.makeText(getApplicationContext(), "Download Messages success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Download Messages error!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
In my android sqlite database, the value of mydb.WEB_ID is stored as an integer. Any assistance is appreciated.
Hashmap<String,String>
it only contains String values. So you have to convert it to String.
with using
toString()
function it ll give you error.
Try with
String.ValueOf(obj.get("web_id"))
it ll convert the interger value to String and your problem gets resolved.
Happy coding. :P
I figured out my mistake...I was calling the database column name in the HashMap which is different from the json variable. Thanks all for your assistance.
I've created a JSON encode where you enter a HashTable (public Hashtable<?, ?> JSonDecode(String data) {... return objJS.toString(); } ) and get a string in JSON format. That is:
If I have a Hashtable with this (Hashtable in Hashtable):
Example Hashtable:
Hashtable<String, Object> exampleHT = new Hashtable<String, Object>();
exampleHT.put("Color", "Red");
exampleHT.put("OtherKey", "OtherValue");
exampleHT.put("OtherKey2", "OtherValue2");
Hashtable<String, Object> country = new Hashtable<String, Object>();
country.put("Spain", "Madrid");
country.put("France","Paris");
country.put("Italy", "Rome");
Hashtable<String, String> pokemon = new Hashtable<String, String>();
pokemon.put("Pikachu", "Electric");
pokemon.put("Charmander","Fire");
country.put("Pokemons", pokemon);
exampleHT.put("Countries", country);
I use my function(JSonEncode(exampleHT);) and I get this string:
{
"Color":"Red",
"Countries":{
"Spain":"Madrid",
"France":"Paris",
"Italy":"Rome",
"Pokemons":{
"Pikachu":"Electric",
"Charmander":"Fire"
}
},
"OtherKey":"OtherValue",
"OtherKey2":"OtherValue2"
}
It works perfectly! My problem is to create the reverse process, with JSonDecode.
Hashtable<?, ?> hashUnknown = JSonDecode(jsonStringExample);
public Hashtable<?, ?> JSonDecode(String data) {
// I do not know how to parse json in Hashtable, without indicating the tags manually.
}
I do not know how to parse json in Hashtable, without indicating the tags manually.
That is, without it:
JSONArray menuObject = new JSONArray (jObject.getString ("Color"));
JSONArray menuObject = new JSONArray (jObject.getString ("Countries"));
This should be dynamic without knowing json content without writing manually Color, Countries, ....
Any ideas or advice? Thanks,
You can get an Iterator object (java.util.Iterator) over the keys of your JSONObject (jObject)
So you can write something like this:
Iterator<String> it = jObject.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
key = it.next();
value = jObject.get(key);
// Then test the instance of the value variable
// and perform some logic
}
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);
}