How to parse nested json obiect - android

I've this json:
{"data": [{"name" "category" "id" "picture":{"data":{"url":}}}]
My difficulty is how to parse the picture field. I tried with this code:
public class JSONParser {
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jGames = null;
try {
jGames = jObject.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
return getGames(jGames);
}
private List<HashMap<String, Object>> getGames(JSONArray jGames){
int gameCount = jGames.length();
List<HashMap<String, Object>> gameList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> game = null;
for(int i=0; i<gameCount;i++){
try {
game = getGame((JSONObject)jGames.get(i));
gameList.add(game);
} catch (JSONException e) {
e.printStackTrace();
}
}
return gameList;
}
private HashMap<String, Object> getGame(JSONObject jGame){
HashMap<String, Object> game = new HashMap<String, Object>();
String gameName = "";
String logo="";
String user = "";
try {
gameName = jGame.getString("name");
logo = jGame.getString("logo_url");
user = jGame.getString("daily_active_users");
String details ="Utenti attivi : " + user + "\n";
game.put("name", gameName);
game.put("logo_url", R.drawable.icon);
game.put("logo_path", logo);
game.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
return game;
}
}

this tutorial will help you Android JSON Parsing Tutorial

Related

Converting ArrayList to JSONArray

I am using ArrayList<HashMap<String,String>> to store my cart items. But I need to convert it to JSONArray to send it to the database. But when I convert it to JSONArray the JSONArray looks like this:
03-13 11:09:28.842: D/cart before(1339): [{image=2130837526,
category=Chairs, Quantity=1, price=400, name=chair, prodId=34},
{image=2130837566, category=Mirrors, Quantity=1, price=3000, name=La
Fonda, prodId=35}]
03-13 11:09:28.842: D/cart after converting into JSONArray(1339):
["{image=2130837526, category=Chairs, Quantity=1, price=400,
name=chair, prodId=34}","{image=2130837566, category=Mirrors,
Quantity=1, price=3000, name=La Fonda, prodId=35}"]
Which I believe is wrong. Instead it should be converted to something like this:
cartitems=[{"name":"Chair","price":"1001","prodId":"2","category":"Chairs","image":"2130837519","Quantity":"1"},{"name":"Baxton Studio Club Chair","price":"4545","prodId":"5","category":"Chairs","image":"2130837521","Quantity":"1"}]
Code to convert to JSONArray:
protected String doInBackground(String... args) {
AddtoCart obj = (AddtoCart) getApplicationContext();
JSONArray cart = new JSONArray(obj.getCart());
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("email", email);
params.put("payment", payment);
params.put("address", useraddress);
params.put("contact", contact);
params.put("city", usercity);
params.put("cartitems", cart.toString());
Log.d("params", params.toString());
JSONObject json = jParser.makeHttpRequest(url_all_products, "POST", params);
try {
success = json.getInt("success");
message = json.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Class holding ArrayList:
public class AddtoCart extends Application {
private static final String TAG_QUANTITY = "Quantity";
private static final String TAG_PRICE = "price";
ArrayList<HashMap<String, String>> cart = new ArrayList<HashMap<String, String>>();
public void setCart(ArrayList<HashMap<String, String>> data) {
//cart = data;
cart.addAll(data);
Log.d("Items in the cart", String.valueOf(cart));
}
public ArrayList<HashMap<String, String>> getCart() {
return cart;
}
public int getSize() {
return cart.size();
}
public void updateCart(ArrayList<HashMap<String, String>> data) {
cart = data;
Log.d("UPDATED CART", String.valueOf(cart));
}
public void updateQuantity(int index, String quantity) {
cart.get(index).put(TAG_QUANTITY,quantity);
}
}
I found this to be helpful in my project:
Object in my ArrayList<>
public class ListItem {
private long _masterId;
private String _name;
private long _category;
public ListItem(long masterId, String name, long category) {
_masterId = masterId;
_name = name;
_category = category;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Id", _masterId);
obj.put("Name", _name);
obj.put("Category", _category);
} catch (JSONException e) {
trace("DefaultListItem.toString JSONException: "+e.getMessage());
}
return obj;
}
}
The actual conversion:
ArrayList<ListItem> myCustomList = ArrayList<ListItem>();
JSONArray jsonArray = new JSONArray();
for (int i=0; i < myCustomList.size(); i++) {
jsonArray.put(myCustomList.get(i).getJSONObject());
}

I can't get this template code working with my case (HTML to List)

so I found this code on YouTube (Credit goes to "Indragni Soft Solutions") and I wanted to change it so it works with another webpage.
So it is pretty straight forward, there is a listview and I want the listview to display all of the people working here (http://www.muckendorf-wipfing.at/12-0-Amts-+und+Sprechstunden.html), but not the other things left of the office workers. To be as clear as possible: I want everything in the tag. So everything that is in div#content-r should get into my list, with the picture next to it, and when the user taps on one of them, the full text should be displayed. But that doesn't really have to be necessary, as it would also work if there is just the name ontop, the picture left and the email under the name. So as I said, here is the code I tried:
package com.mrousavy.gemeindemuckendorfwipfing;
public class EcoActivity extends AppCompatActivity {
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lv);
String strUrl = "http://wptrafficanalyzer.in/p/demo1/first.php/countries"; //This String should be http://www.muckendorf-wipfing.at/12-0-Amts-+und+Sprechstunden.html but I let it like this so you can see how the template-result looks
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
mListView = (ListView) findViewById(R.id.lv_countries);
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute(result);
}
}
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter> {
JSONObject jObject;
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
CountryJSONParser countryJsonParser = new CountryJSONParser();
List<HashMap<String, Object>> countries = null;
try {
countries = countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
String[] from = {"country", "flag", "details"};
int[] to = {R.id.tv_country, R.id.iv_flag, R.id.tv_country_details};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
#Override
protected void onPostExecute(SimpleAdapter adapter) {
mListView.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path", imgUrl);
hm.put("position", i);
imageLoaderTask.execute(hm);
}
}
}
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
File cacheDirectory = getBaseContext().getCacheDir();
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_" + position + ".png");
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
Bitmap b = BitmapFactory.decodeStream(iStream);
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
fOutStream.flush();
fOutStream.close();
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
hmBitmap.put("flag", tmpFile.getPath());
hmBitmap.put("position", position);
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
String path = (String) result.get("flag");
int position = (Integer) result.get("position");
SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter();
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
hm.put("flag", path);
adapter.notifyDataSetChanged();
}
}
}
And here is the CountryJSONParser (Created by Aylar-HP):
package com.mrousavy.gemeindemuckendorfwipfing;
public class CountryJSONParser {
public List<HashMap<String, Object>> parse(JSONObject jObject) {
JSONArray jCountries = null;
try {
jCountries = jObject.getJSONArray("countries");
} catch (JSONException e) {
e.printStackTrace();
}
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries) {
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> country = null;
for (int i = 0; i < countryCount; i++) {
try {
country = getCountry((JSONObject) jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
private HashMap<String, Object> getCountry(JSONObject jCountry) {
HashMap<String, Object> country = new HashMap<String, Object>();
String countryName = "";
String flag = "";
String language = "";
String capital = "";
String currencyCode = "";
String currencyName = "";
try {
countryName = jCountry.getString("countryname");
flag = jCountry.getString("flag");
language = jCountry.getString("language");
capital = jCountry.getString("capital");
currencyCode = jCountry.getJSONObject("currency").getString("code");
currencyName = jCountry.getJSONObject("currency").getString("currencyname");
String details = "Language : " + language + "\n" +
"Capital : " + capital + "\n" +
"Currency : " + currencyName + "(" + currencyCode + ")";
country.put("country", countryName);
country.put("flag", R.mipmap.ic_launcher);
country.put("flag_path", flag);
country.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
}
So my question is; How can I change that code to work with my case? I have no clue how I just get the div#content-r out of the website, and then get it into my list.. :/ Thanks!

JSON is returning strange characters in Android

I implemented an app that gets data from a JSON. JSON is returning me characters:
Âé...
How I can get that return JSON:
áéíóú
instead of
Âé
private void parseJson(JSONObject json) {
nombresLista = new ArrayList<HashMap<String, String>>();
if (json != null){
try {
JSONArray sitios = json.getJSONArray("sites");
for (int i = 0; i < sitios.length(); i++) {
JSONObject jsonObj = sitios.getJSONObject(i);
String nombre = jsonObj.getString("name");
HashMap<String, String> lista = new HashMap<String, String>();
lista.put("name", nombre);
nombresLista.add(lista);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < nombresLista.size(); i++) {
String nombre = nombresLista.get(i).get("name");
Log.e("", "nombre = " + nombre);
}
}

Get Specific data from json services while populating List

i need to populate a list view from data coming under the tag "group" from a JSON array "video". the coding under it is working fine if i remove if condition. Please help me guys. My boss is kicking my ass for this and my job is on the line. thanks in advance
public class CountryJSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jCountries = null;
try {
// Retrieves all the elements in the 'countries' array
jCountries = jObject.getJSONArray("video");
}
catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;
// Taking each country, parses and adds to list object
for(int i=0; i<countryCount;i++){
try {
// Call getCountry with country JSON object to parse the country
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
// Parsing the Country JSON object
private HashMap<String, Object> getCountry(JSONObject jCountry){
HashMap<String, Object> country = new HashMap<String, Object>();
String countryName = "";
String flag="";
String language = "";
String capital = "";
String currencyCode = "";
String currencyName = "";
try {
countryName = jCountry.getString("Description");
flag = jCountry.getString("thumbnailUrl");
capital = jCountry.getString("title");
language=jCountry.getString("group");
Log.v("---","Country name: "+countryName+"Flag Url:"+flag+"Title"+capital);
if(language.equals("RokuTest-VideoGroup")){
country.put("country", countryName);
country.put("group", language);
country.put("flag", R.drawable.ic_launcher);
country.put("flag_path", flag);
country.put("details", capital);
Log.v("---","Country name: "+countryName+"Flag Url:"+flag+"Title"+capital);
}
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
}
Rohit.. Just manage the code in if and else block. It should work as you are saying removing if is working fine.
if(language.equals("RokuTest-VideoGroup")) {
// do somthing
}
else {
// do something
}

Loading image to ListView

I used this code to retrieve data from PHP and display into a listview.
I put HashMap collections to ArrayList, then insert ArrayList to SimpleAdapter to display on screen.
The problem is If i put into HashMap an element named "image" and value is image URL, SimpleAdapter do not show the image, it understand it as an String ( Not convert string to image ).
How to solve this problem ?
JSONObject jsonObject =
JSONParser.getJSONObject("xxxxxxx/android_get_places.php");
JSONArray jsonArray = null;
try {
jsonArray = jsonObject.getJSONArray("place");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = null;
try {
object = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String name = object.getString("name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", name);
arrayList.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
setListAdapter(new SimpleAdapter(getApplicationContext(), arrayList, R.layout.place_item,
new String[]{"name"}, new int[]{R.id.title}));

Categories

Resources