Android Hashmap issue - android

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.

Related

How to get array number JSON android

I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".
I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>
courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);
Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.

Cannot find symbol variable Android Studio

I am working on parsing data from a JSON url.
But the JSONobjects have different keys.
I want to get all the data from each json object and when it doesn't have that key I want to give it a default message.
This is what I'm trying to use:
if(myJSONObject.has("mykey")) { <- in this case "abv"
//it has it, do appropriate processing
}
I got this variable
private static final String TAG_ABV = "abv";
I tried doing this to check if the abv key was included in the JSON and give the string a default text of "No value" when it was not inculed.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
if(c.has("abv")) {
String abv = c.getString(TAG_ABV);
} else {
String abv = "No value";
}
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ABV, abv);
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
But I have this error: cannot find symbol variable abv
I guess the abv inside the if statement is out the scope.
You're declaring abv inside the if/else blocks, which means it's only accessible inside that block. When you try to use it later (in data.put(TAG_ABV, abv); the variable you created is no longer accessible - it's out of scope. If you move the declaration of abv to the line before the if/else statement, that should fix your error.

parsing json in Android with different with inner array

I have this json url which outputs this (snippet)
{
"status":true,
"result":{
"message":"Successfully retrieved the daily feed.",
"items":{
"1376438400":[
{
"code":"DjCr3N3o",
"slug":"soulja-boy-gets-kicked-off-airplane",
"cdn_screenshot_path":"screenshots\/2013\/08\/DjCr3N3o.png",
"title":"Soulja Boy Gets Kicked Off Airplane!",
"hits":"457",
"date_added":"1376507797"
},
{
"code":"7V9eOVpX",
"slug":"dr.-dre-and-suge-knight-baby-mama-michelle-surprise-performance-she-sounds-like-a-chipmunk-but-sings-like-an-angel",
"cdn_screenshot_path":"screenshots\/2013\/08\/7V9eOVpX.png",
"title":"Dr. Dre AND Suge Knight Baby Mama Michel'le Surprise Performance! (She Sounds Like A Chipmunk But Sings Like An Angel!)",
"hits":"525",
"date_added":"1376505010"
},
{
"code":"8ovO203r",
"slug":"headless-snake-bites-itself-in-the-butt",
"cdn_screenshot_path":"screenshots\/2013\/08\/8ovO203r.png",
"title":"Headless Snake Bites Itself In The Butt!",
"hits":"361",
"date_added":"1376485812"
}
],
"1376352000":[
{
"code":"9b9jR6qs",
"slug":"show-you-how-to-do-this-son-chris-paul-hits-4-straight-jumpers-on-colleges-best-point-guards",
"cdn_screenshot_path":"screenshots\/2013\/08\/9b9jR6qs.jpg",
"title":"Show You How To Do This Son! Chris Paul Hits 4 Straight Jumpers On College's BEST Point Guards!",
"hits":"979",
"date_added":"1376443810"
},
{
"code":"p6l5pwg8",
"slug":"ttbnez-fck-da-opp-music-video",
"cdn_screenshot_path":"screenshots\/2013\/08\/p6l5pwg8.png",
"title":"TTBNEZ - F*ck Da Opp [Music Video]",
"hits":"316",
"date_added":"1376419812"
},
{
"code":"haxUoUVt",
"slug":"strip-life-the-reality-series-feat.-lanipop-entyce-trailer",
"cdn_screenshot_path":"screenshots\/2013\/08\/haxUoUVt.png",
"title":"Strip Life: The Reality Series (feat. Lanipop, Entyce) [Trailer]",
"hits":"426",
"date_added":"1376419214"
}
],
The problem I am having is figuring out how to parse it due to its format and how to reach the data such as "code", "slug" and "title". This is what I have so far, but it seems wrong as I may have to have 2 loops instead of 1 I think.
This is what I have so far
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrive JSON Objects from the given website URL in JSONfunctions.class
jsonobject = JSONfunctions
.getJSONfromURL("http://api.hoodplug.com/v1/videos/daily_feed?per_page=5&offset=0&format=json");
try {
// Locate the array name
jsonarray = jsonobject.getJSONArray("item");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("code", jsonobject.getString("code"));
map.put("slug", jsonobject.getString("slug"));
map.put("title", jsonobject.getString("title"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
You're just missing a little point here!
in here you got the first json object :
jsonobject = JSONfunctions
.getJSONfromURL("http://api.hoodplug.com/v1/videos/daily_feed?per_page=5&offset=0&format=json");
this json object is the whole big JSON object that contain status and result but you directly want to access the JSON array that inside result object! using this :
// Locate the array name
jsonarray = jsonobject.getJSONArray("items");
The right thing is you must get the result object first from the big json object with
JSONObject resultObject = jsonobject.getJSONObject("result");
then use the resultObject to get the array!
try {
// Locate the array name
jsonarray = resultObject .getJSONArray("item");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("code", jsonobject.getString("code"));
map.put("slug", jsonobject.getString("slug"));
map.put("title", jsonobject.getString("title"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
I hope you understand my answer, but if you have other question about my answer feel free to ask! :)

data from a jsonobject in android

The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.

parse json file from SD card in android app

I have an array of JSON objects on an SD card.
I get the file contents like this:
File yourFile = new File("/mnt/extSdCard/test.json");
FileInputStream stream = new FileInputStream(yourFile);
String jString = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
jString = Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
The structure is like this:
[{"name":"john"},{"name":"fred"},{"name":"sam"}]
and I want to be able to parse them to make a listView. In JavaScript I can get them as an AJAX request and then do
var people = JSON.parse(data.responseText);
and then loop through the array. But I am a complete novice at java - I have found example code that does each of those things separately but I can't put them all together. Any help much appreciated.
The problem is that the above JSON structure represents a JSONArray and not a JSONObject
JSON Syntax
So after getting your jstring just do this
JSONArray array = new JSONArray(jString);
for(int i=0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
String value = obj.getString("name");
}
If you have it as a string, you should be able to parse it to a JSONObject with something like this:
JSONObject jObj = null;
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.i(TAG, "JSON Data Parsed: " + jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
I would also put the data (in your example) into an array, so it appears as something like:
{"names": [{"name": "john"},{"name": "fred"},{"name": "sam"}]}
And then to read your object again, you can put it into an array (or something else I guess) with something like this:
// create an empty list
ArrayList<String> l = new ArrayList<String>();
// pull the array with the key 'names'
JSONArray array = jObj.getJSONArray("names");
// loop through the new array
for(int i = 0; i < array.length(); i++){
// pull a value from the array based on the key 'name'
l.add(array.getJSONObject(i).getString("name"));
}
Hope at least some of this helps out (or at least points you in the correct direction). There are PLENTY of resources on here though, too.
EDIT:
Read up on JSON formatting. [] denotes array and {} denotes object, so you have an array of objects. That is why I recommended changing your format. If you are set on your format, either go with what Mr.Me posted for his answer, or just split your string at special characters and put them into an array that way.
Try this
String[] from = new String[] {"name"};
int[] to = new int[] { R.id.name};
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
try
{
JSONArray names = new JSONArray(jsonString);
Log.i("MyList","Number of names " + names.length());
for (int j = 0; j < names.length(); j++)
{
JSONObject jsonObject = names.getJSONObject(j);
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", jsonObject.getString("name"));
fillMaps.add(map);
}
}
catch (Exception e)
{
e.printStackTrace();
}
SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to);
mListView.setAdapter(adapter);
Here mListView is your predefined ListView.
Feel free to share your doubts here, if any.

Categories

Resources