Loading image to ListView - android

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}));

Related

Json array parsing always has null result in Android

How I can parse this json array?
{"1":
{"0":"3","id_disc":"3","1":"Дослідження і проектування компютерних систем","name":"Дослідження і проектування компютерних систем","2":"ДПКМС ","s_name":"ДПКМС "}
,"2":
{"0":"5","id_disc":"5","1":"Цивільний захист і охорона праці в галузі","name":"Цивільний захист і охорона праці в галузі","2":"ЦЗ і ОП","s_name":"ЦЗ і ОП"}
,"3":
{"0":"1","id_disc":"1","1":"Дослідження і проектування інтелектуальних систем (Лекція)","name":"Дослідження і проектування інтелектуальних систем (Лекція)","2":"ДіПІС","s_name":"ДіПІС"}
}
I was trying this method, but I always have null result.
String[] sA = new String[100];
try {
JSONArray cast = getDisc(paraaams).getJSONArray(" ");
for (int i=0; i<cast.length(); i++) {
JSONObject disc = cast.getJSONObject(i);
sA[i-1] = disc.getString("name");
}
}catch (JSONException e){}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
public JSONArray getDisc(Object params[]){
HTTPWorker httpWorker=new HTTPWorker();
JSONArray mjson =new JSONArray();
String s = httpWorker.doInBackground(params);
try {
mjson = new JSONArray(s);
Log.e("JSONinClass ",mjson.toString());
}catch (JSONException e){}
return mjson;
I think i try to parse it like json object, but i don't know how correct work with json arrays.
Thanks for help:)
my ListFragment:
public class MyFilesActivity extends android.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_myfiles, null);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
String[] sA = new String[100];
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getDisc(paraaams).toString());
} catch (JSONException e) {
e.printStackTrace();
}
int i =0;
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
if (jsonObject.has(key)) {
JSONObject value = jsonObject.getJSONObject(key);
// value is another JSONObject where you can get the "name" from
String name = value.getString("name");
sA[i]=name;
Log.e("value= ", name);
i+=1;
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
return rootView;
}
I cut it a bit, removed it is not important for the question :)
Try this for your Response to Parse
May Help you
try{
JSONObject jsonObject = new JSONObject(response);
List<String> keyList = getAllKeys(jsonObject);
for(String key : keyList){
JSONObject innerObject = jsonObject.getJSONObject(key);
List<String> innerKeyList = getAllKeys(innerObject);
for(String innerKey: innerKeyList){
System.out.println(innerObject.getString(innerKey));
}
}
}catch(Exception e){
e.printStackTrace();
}
This method will return keys
private List<String> getAllKeys(JSONObject jsonObject) throws JSONException{
List<String> keys = new ArrayList<String>();
Iterator<?> iterator = jsonObject.keys();
while( iterator.hasNext() ) {
String key = (String)iterator.next();
keys.add(key);
}
return keys;
}
try this:
please check below changes replace array to arraylist
public class MyFilesActivity extends android.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_myfiles, null);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
ArrayList<String> sA = new ArrayList<>();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getDisc(paraaams).toString());
} catch (JSONException e) {
e.printStackTrace();
}
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
if (jsonObject.has(key)) {
JSONObject value = jsonObject.getJSONObject(key);
// value is another JSONObject where you can get the "name" from
String name = value.getString("name");
sA.add(name);
Log.e("value= ", name);
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
return rootView;
}
Here is a tested code to parse json.
try {
JSONObject json = new JSONObject(json);
int jsonLength = json.length();
for(int i=1; i<=jsonLength; i++){
JSONObject jObject = json.getJSONObject(""+i);
String data = jObject.getString("0");
}
} catch (JSONException e) {
e.printStackTrace();
}
It is just a plain JSONObject not an JSONArray, so you have to cast it to a JSONObject first
JSONObject json = new JSONObject(jsonString);
To loop through it
for (Iterator<String> iter = json.keys(); iter.hasNext();) {
String key = iter.next();
JSONObject value = (JSONObject) json.getJSONObject(key);
String name = value.getString("name");
}

Android parse json array between json object

I tried to parse this json array and json objects but give me error and not recieve any data, can you help me to parse this;
Here my json link:
http://almahdishop.com/api/posts.json?fields=id,title,thumb&limit=10
Here My Code:
JSONArray jsonarray = new JSONArray(jsStr);
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jso = jsonarray.getJSONObject(i);
map.put("id_product", jso.getString("id"));
map.put("name", jso.getString("title"));
map.put("model","");
map.put("price", "14000");
map.put("oldprice", "14000");
map.put("logo", jso.getString("thumb"));
arraylist.add(map);
}
Some like this
try {
JSONObject data = new JSONObject(jsonString);
JSONArray itemsArray = data.getJSONArray("items");
for (int i = 0; i <itemsArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jso = itemsArray .getJSONObject(i);
map.put("id_product", jso.getString("id"));
map.put("name", jso.getString("title"));
map.put("model","");
map.put("price", "14000");
map.put("oldprice", "14000");
map.put("logo", jso.getString("thumb"));
arraylist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
Parse this json as follows :
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray array = jsonObject.getJSONArray("items");
for(int i=0;i<array.length();i++){
JSONObject obj = (JSONObject) array.get(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
I think problem comes from parsing.
Please use org.JSON.simple.-111.jar.

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
}

How to parse nested json obiect

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

How to display the parsed JSON data in android

I have parsed the JSON data and storing the parsed JSON data into ArrayList HashMap with the key value ,when I want to display the parsed data I am getting only the last value of the parsed Data rest all data are not displayed for reference
public HashMap<String,String> map = new HashMap<String, String>();
create HASHmap then arraylist
public static ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
void parsing(JSONObject json)
{
String id="";
String countryn="";
try
{
countryobj = json.getJSONArray("country_details");
for(int i = 0;i<countryobj.length(); i++)
{
JSONObject items = countryobj.getJSONObject(i);
Log.e("i","value==="+i);
if(items.has("countryid"))
{
id = items.getString("countryid");
map.put("countryid",id);
Log.e("id","valueID==="+id);
}
if(items.has("country"))
{
countryn= items.getString("country");
map.put("country",countryn);
Log.e("counyrt","valueName==="+countryn);
}
contactList.add(i,map);
Log.e("lisvaluet","val--"+i +contactList.get(i));
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
in Log I am getting only 08-20 12:13:45.830: E/--ID---(654): value--{countryid=275, country=Palestinian Territory} with 269 times can any help me out where I am doing wrong in storing the parsed data , I am stuck here.
Check this.
private JSONObject[] items;
JSONArray countryobj = json.getJSONArray("country_details");
items = new JSONObject[countryobj.length()];
for(int i=0, i < countryobj.length(); i++)
{
items[i] = countryobj.optJSONObject(i);
id = items[i].getString("countryid");
map.put("countryid",id);
countryn= items[i].getString("country");
map.put("country",countryn);
contactList.add(i,map);
}

Categories

Resources