parse json file from SD card in android app - android

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.

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.

Android Hashmap issue

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.

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! :)

In Android, parsing Google places URL into a ListView?

In my Android app, I'm trying to parse JSON data from a Google Places URL into a ListView. I'm trying to list the names of nearby restaurants. It appears that the parsing works, but I don't know how to grab the "name" variable out of the JSON data. The returned list has items in it that like this:
{"id":
"6217c344be105e............"
{"id":
"2c66bf813799zr2844......"
Which to me, looks like it's parsing the "id" variable in the Google Place URL's "results" array. I want it to grab the "name" variable in the "results" array. Can someone show me the correct code to do this? Here's the JSON parsing method that I'm using:
public void parseJSON() throws ClientProtocolException, IOException, JSONException
{
String bcURL="https://maps.googleapis.com/maps/api/place/search/json?"
+ "location=" + latString + "," + longiString
+ "&radius=15000&"
+ "types=restaurant&sensor=false&key="
+ myPlaceKey;
//--- Get Places URL ----
client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(bcURL));
int statusLine = response.getStatusLine().getStatusCode();
if(statusLine == 200){
HttpEntity e = response.getEntity();
String data = EntityUtils.toString(e);
JSONObject urlData = new JSONObject(data);
JSONArray resultsArr = urlData.getJSONArray("results");
int length = resultsArr.length();
List<String> listContents = new ArrayList<String>(length);
for (int i = 0; i < length; i++)
{
listContents.add(resultsArr.getString(i));
}
ListView restListView = (ListView) findViewById(R.id.jsonList);
restListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listContents));
}
//--- END Get Places URL ----
and the listview part of the code:
JSONArray resultsArr = urlData.getJSONArray("results");
int length = resultsArr.length();
List<String> listContents = new ArrayList<String>(length);
for (int i = 0; i < length; i++)
{
listContents.add(resultsArr.getString(i));
}
ListView restListView = (ListView) findViewById(R.id.jsonList);
restListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listContents));
}
//--- END Get Places URL ----
where does the "get the name variable" bit of code go, and what would that code look like?
Take a look at here, it should describe everything you need.
Long story short: you need to retrieve from the jsonObject the value you need using JSONObject.getString("attributeName")
If you want to grab the first object of the JSON file you need to do something like this :
JSONArray samplearr = null;
samplearr = new JSONArray(String);
for(int index=0;index<samplearr.length();index++)
{
try
{
JSONObject obj = samplearr.getJSONObject(index);
JSONObject userobj = samplearr.getJSONObject(index).getJSONObject("user");
Log.d("object","sample array created");
userobj.getString("screen_name"),
obj.get("text").toString(),
userobj.getString("profile_image_url")
}catch(Exception er)
{
Log.d("exceptiom","exception found at : "+er.getMessage());
}
}
BAsically if you want to grab an object within an object then you do that. According to your question it seems the field you want is inside the "id" field so you have to parse two times through it

Android: Decoding JSON

[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}

Categories

Resources