Get data from JSON object and array - android

Searching for solution of that. Sample of Java code:
public void loadPositions(JSONObject result){
try {
JSONObject jObject = result.getJSONObject("points");
Iterator<String> keys = jObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Log.v("list key", key);
if(jObject.get(key) instanceof JSONObject) {
JSONObject innerJObject = jObject.getJSONObject(key);
String lat = innerJObject.getString("lat");
String lon = innerJObject.getString("lon");
Log.i("details", "lat = " + lat + ", " + "lon = " + lon);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
JSON data:
{
"points":{
"C50D15525":[
{
"lat":"51.643257329609156",
"lon":"17.798963651975885"
},
{
"lat":"51.643257329609156",
"lon":"17.798963651975885"
}
],
"BFFCDE4AF":[
{
"lat":"51.6434779",
"lon":"17.7993028"
},
{
"lat":"51.6434779",
"lon":"17.7993028"
},
{
"lat":"51.6434779",
"lon":"17.7993028"
}
]
}
}
Code above give me only list key, but I want LAT & LON from many points like "BFFCDE4AF" and "C50D15525". I've tried in many ways... JSON data is valid.

You can achive it through this
For example
points.C50D15525["lat"]
but you need to extract json through apply any looping and associative concept.

Inside the "points" object your JSON has an Array object, which you need to get with the getJSONArray() method. Loop through the JSONArray and get the "lat" and "lon" objects.
public void loadPositions(JSONObject result){
try {
JSONObject jObject = result.getJSONObject("points");
Iterator<String> keys = jObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Log.v("list key", key);
JSONArray jArray = jObject.getJSONArray(key);
for (int i=0; i < jArray.length(); i++){
JSONObject obj = jArray.getJSONObject(i);
String lat = obj.optString("lat", "NA"));
String lon = obj.optString("lon", "NA"));
Log.i("details","key = " + key + " coor count = " + i + " lat = " + lat + ", " + "lon = " + lon);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Since I have not tested this, please let me know if you have any issues.

Related

how to merge 2 data records to one in a recyclerView ? (mysql & volley)

I want to merge two data records to become one based on the same DAY, but different "Sesi" such as Sesi 1, and Sesi 2 being 1 in a recyclerVCiew
please see my application Image
here I use mySql with volley JSON + Inner Join MYSQL
Main Activity:
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ALL_JADWAL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject jadwal = array.getJSONObject(i);
String kelas = jadwal.getString("Kelas");
if (kelas.equals(Kelas)) {
jadwalHarianList.add(new JadwalHarian(
jadwal.getString("Nama_Pengajar"),
jadwal.getString("Mata_Kuliah"),
jadwal.getString("Ruang"),
jadwal.getInt("Sesi"),
jadwal.getString("Hari"),
jadwal.getString("Jam")
));
}
JadwalRV jadwalRV = new JadwalRV(getApplicationContext(), jadwalHarianList);
recyclerView.setAdapter(jadwalRV);
jadwalRV.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
JadwalRV Adapter:
public void onBindViewHolder(JadwalRV.MyViewHolder myViewHolder, int i) {
JadwalHarian jadwalHarian = mJadwalHarian.get(i);
myViewHolder.tHari.setText(jadwalHarian.getHari());
myViewHolder.tIsi.setText("Waktu\n" +
"Ruang\n" +
"Mata Kuliah\n" +
"Dosen Pengajar");
myViewHolder.thjam.setText(
"= " + jadwalHarian.getJam()+
"\n= " + jadwalHarian.getRuang() +
"\n= " + jadwalHarian.getMata_Kuliah() +
"\n= " + jadwalHarian.getNama_Pengajar() );
// SESI 2
myViewHolder.tIsi2.setText("Waktu\n" +
"Ruang\n" +
"Mata Kuliah\n" +
"Dosen Pengajar");
myViewHolder.thjam2.setText(
"= " + jadwalHarian.getJam()+
"\n= " + jadwalHarian.getRuang() +
"\n= " + jadwalHarian.getMata_Kuliah() +
"\n= " + jadwalHarian.getNama_Pengajar() );
}
Here is Structure Table which I used inner join in my PHP json
You can try like this following not obvious, but It can help you:
try
{
JSONArray array = new JSONArray();
ArrayList<HashMap<String,Object>> jadwalHarianList = new ArrayList<>();
JSONObject jsonObject=new JSONObject();
try
{
jsonObject.put("Kelas", "R28");
jsonObject.put("Sesi", "1");
jsonObject.put("Mata_Kuliah", "Pemprograman #1");
array.put(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("Kelas", "R28");
jsonObject.put("Sesi", "2");
jsonObject.put("Mata_Kuliah", "Algoritma #2");
array.put(jsonObject);
}
catch (Exception e)
{
Log.e("ldfjdlfj","data----111_jsonOb_ex>>>"+e);
}
Log.e("ldfjdlfj","data----2222>>>"+array);
String previous = "";
for (int i = 0; i < array.length(); i++) {
JSONObject jadwal = array.getJSONObject(i);
String kelas = jadwal.getString("Kelas");
String Sesi = jadwal.getString("Sesi");
String Mata_Kuliah = jadwal.getString("Mata_Kuliah");
if(kelas.equalsIgnoreCase(previous))
{
HashMap<String,Object> map = new HashMap<>();
map.put("kelas",array.getJSONObject(i-1).getString("Kelas"));
map.put("Sesi",array.getJSONObject(i-1).getString("Sesi"));
map.put("Sesi2",Sesi);
map.put("Mata_Kuliah",Mata_Kuliah);
jadwalHarianList.add(map);
}
else
{
previous = kelas;
HashMap<String,Object> map = new HashMap<>();
map.put("kelas",array.getJSONObject(i).getString("Kelas"));
map.put("Sesi",array.getJSONObject(i).getString("Sesi"));
map.put("Sesi2","");
map.put("Mata_Kuliah",Mata_Kuliah);
jadwalHarianList.add(map);
}
}
Log.e("ldfjdlfj","data----333_>>>"+jadwalHarianList);
} catch (JSONException e) {
e.printStackTrace();
}

How to retrieve genre from JSON result

I can not retrieve all key values from JSON object retrieved from HTTP request.
This is the returned JSON object from http request:
{"data":[{"movie_id":3,"movie_name":"Promithius","genre":"a dude","year":"2016","rating":45}]}
my Android Code:
try {
//HttpJsonParser httpJsonParser = new HttpJsonParser();
JSONObject JSonObj = (JSONObject) new
JSONTokener(result).nextValue();
String mymovie = JSonObj.getString("movie_name" );
String movieGenre = JSonObj.getString("genre" );
etResponse.setText("movie=" + mymovie + " genre=" +
movieGenre);
} catch (JSONException e) {
etResponse.setText("ERROR=" + e.getMessage());
e.printStackTrace();
}
When I run it in emulator with only:
String mymovie = JSonObj.getString("movie_name" );
etResponse.setText("movie=" + mymovie;
I get back the Movie name with no error. So the issue is I can retrieve movie_name but no Genre.
Error returned says "No value for genre"
Thanks in advance.
I think the data is JSONArray.
String result = "{\"data\":[{\"movie_id\":3,\"movie_name\":\"Promithius\",\"genre\":\"a dude\",\"year\":\"2016\",\"rating\":45}]}";
try {
JSONObject JSonObj = (JSONObject) new JSONTokener(result).nextValue();
JSONArray data = JSonObj.getJSONArray("data");
for (int i=0; i<data.length(); i++){
JSONObject jsonObject = data.getJSONObject(i);
String mymovie = jsonObject.getString("movie_name" );
String movieGenre = jsonObject.getString("genre" );
String dest = "movie=" + mymovie + " genre=" + movieGenre;
Log.d(TAG, dest);
}
} catch (JSONException e) {
e.printStackTrace();
}
Below is the code that finally worked for me. I hope it can help someone else.
try{
JSONObject object = new JSONObject(result);
JSONArray Jarray = object.getJSONArray("data");
object = Jarray.getJSONObject(0);
String MovieName = object.getString("movie_name");
String Genre = object.getString("genre");
String Rating = object.getString("rating");
String Year = object.getString("year");
etResponse.setText("Movie Name = " + MovieName + " \n Genre = " +
Genre + "\n Rating = " + Rating + " \n Year = " + Year );
} catch (JSONException e) {
etResponse.setText("JSONException: " + e.getMessage());
}

How to get String Array from JSON Object

I am trying to get a list of available numbers from the following json object
void doJSONParser(String str)
{
try {
JSONObject order = new JSONObject(str);
JSONArray index = order.getJSONArray("webnautes");
for(int i = 0; i < index.length(); i++)
{
JSONObject tt = index.getJSONObject(i);
name += "name: " + tt.getString("name")+"\n";
phone = new String[tt.getString("phone").length()];
//phone += "phone: " + tt.getString("phone")+"\n";
}
Log.d("JSON DATA:", name);
Log.d("JSON DATA:", phone.toString());
}
catch (JSONException e)
{
e.printStackTrace();
Log.d("JSON ERROR", e.getLocalizedMessage());
}
}
Try this
JSONArray phoneJson = tt.getJSONArray("phone");
String[] arr = new String[phoneJson.length()];
for(int i = 0; i < phoneJson.length(); i++)
arr[i] = phoneJson.getString(i);

How i can retrieve this array of images from json?

I have his json and i need to retrieve array of images from images Variable..
this my json :
{
id: 215,
title: " this is title",
image: "1464958558.jpg",
description: "description",
images: "["1464958558.jpg","1464958559.jpg","1464958561.jpg","1464958563.jpg","1464958564.jpg","1464958568.jpg","1464958569.jpg","1464958570.jpg","1464958573.jpg","1464958574.jpg"]",
user_name: "user name",
telephone: "0123456789"
}
i want to retrieve this images array and display it in grid view... and i can't find any response in logcat
my doInBackGround()
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
ID = mCursor.getString(ArticleLoader.Query._ID);
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + String.valueOf(Config.BASE_URL));
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
GridItem item;
item = new GridItem();
Log.i(TAG, "parseResult: " + jsonObj);
for (int i = 0; i < jsonObj.length(); i++) {
// if (response != null) {
String images = jsonObj.getString("images");
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
dose i retrieve data correctly ?
Is images json object string or json array? In your code is string.
If WebService changes are possible, request to given you a json array of images, this is best practice.
If not possible you must parse json image object with regex.
No your doing wrong just try below code
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
for(int i=0;i<arrayObj.length();i++)
{
String item = arrayObj.getString(i);
// now you use item string where you want
}
} catch (JSONException e) {
e.printStackTrace();
}
images should be a JSONArray, and hence you can do that to parse it (inside your for loop!):
JSONArray imagesJSON = jsonObj.getJSONArray("images");
for(int k = 0 ; k<imagesJSON.length() ; k++){
String image = imagesJSON.getString(k);
item.setImage(IMAGE_LINK + image);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + image);
mGridData.add(item);
}

How do you pass results from a JSON array into into a multidimensional array?

I am a little new to android/java. I am trying to pass JSON values into a list and then into a multidimensional array. I am not having much success.
2 questions,
1) How would I load all of the variables in a json array into children[][]?
2) How do you view children[][] in Log.i
Herei s my code:
List<String> cList = new ArrayList<String>();
String customer_name, customer_title, customer_postal_code, customer_city, customer_state, customer_street_address;
ArrayList<String> cTitle, cClubName, cPostalCode, cCity, cState, cStreet = new ArrayList<String>();
public String[][] children = null;
//... onCreate method, HTTP Connection, StringBuilder, etc. These work fine...
// Pass data into array
try{
JSONArray jArray = new JSONArray(result);
JSONObject jData=null;
String[][] children = new String[jArray.length()][6];
for(int i=0;i<jArray.length();i++){
jData = jArray.getJSONObject(i);
customer_name=jData.getString("customer_name");
Log.i("JSON ", "customer_name LOG " + customer_name);
cList.add(customer_name);
customer_title=jData.getString("event_title");
Log.i("JSON ", "customer_title LOG " + customer_title);
cList.add(customer_title);
customer_street_address=jData.getString("customer_street_address");
Log.i("JSON ", "customer_Id LOG " + customer_street_address);
cList.add(customer_street_address);
customer_city=jData.getString("customer_city");
Log.i("JSON ", "customer_city LOG " + customer_city);
cList.add(customer_city);
customer_state=jData.getString("customer_state");
Log.i("JSON ", "customer_state LOG " + customer_state);
cList.add(customer_state);
customer_postal_code=jData.getString("customer_postal_code");
Log.i("JSON ", "customer_postal_code LOG " + customer_postal_code);
cList.add(customer_postal_code);
for(int ic = 0; ic < cList.size(); ic++) {
Log.i("jData ", "length " + jData.length());
children[i][ic] = (String) cList.get(ic);
}
Log.i("Child Array", "Children array LOG " + children);
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No customers Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
If I understood your code correctly you don't need cList.
Something like that should do the work
String[][] children = new String[jArray.length()][6];
for(int i=0;i<jArray.length();i++){
jData = jArray.getJSONObject(i);
customer_name=jData.getString("customer_name");
Log.i("JSON ", "customer_name LOG " + customer_name);
children[i][0] = customer_name;
customer_title=jData.getString("event_title");
Log.i("JSON ", "customer_title LOG " + customer_title);
children[i][1] = event_title;
customer_street_address=jData.getString("customer_street_address");
Log.i("JSON ", "customer_Id LOG " + customer_street_address);
children[i][2] = customer_street_address;
customer_city=jData.getString("customer_city");
Log.i("JSON ", "customer_city LOG " + customer_city);
children[i][3] = customer_city;
customer_state=jData.getString("customer_state");
Log.i("JSON ", "customer_state LOG " + customer_state);
children[i][4] = customer_state;
customer_postal_code=jData.getString("customer_postal_code");
Log.i("JSON ", "customer_postal_code LOG " + customer_postal_code);
children[i][5] = customer_postal_code;
}
Make sure your JSON data is well-formed to avoid exceptions.
To view children[][] you can just iterate twice on your multidimentional array and do Log.i("MyTag", "Value: " + children[i][j]);
String[][] data = new String[jsonArray.length][];
for(int i = 0; i<jsonArray.length; i++){
data[i] = ((ArrayList)jsonArray).get(i).toArray(new String[((ArrayList)jsonArray).get(i).size])
}
for printing in log
Log.d("array", data);

Categories

Resources