I am working with the ESPN Sports API. Can any one help me how to parse this?
I am pasting my code, I am able to parse only the name and id–please help how to parse inner objects items.
public class BaseballActivity extends ListActivity{
private static String url = "http://api.espn.com/v1/sports/baseball?apikey=h29yphwtf7893hktfbn7cd5g";
private static final String TAG_SPORTS = "sports";
private static final String TAG_ID = "id";
private static final String TAG_TIMESTAMP = "timestamp";
private static final String TAG_NAME = "name";
private static final String TAG_NEWS = "news";
private static final String TAG_HEADLINES = "headlines";
private static final String TAG_LINKS = "links";
private static final String TAG_API = "api";
private static final String TAG_SPORTS1 = "sports";
private static final String TAG_HREF = "href";
JSONArray sports = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// HashMap for ListView
ArrayList<HashMap<String, String>> sportsList = new ArrayList<HashMap<String, String>>();
// creating Json parser instance
JSONParser jParser = new JSONParser();
// getting Json String from url
JSONObject json = jParser.getJSONFromUrl(url);
try{
// Getting Array of Contacts
sports = json.getJSONArray(TAG_SPORTS);
// looping through All Contacts
for(int i = 0; i < sports.length(); i++){
JSONObject c = sports.getJSONObject(i);
//String news = c.getString(TAG_NEWS);
// String headlines = c.getString(TAG_HEADLINES);
String name = c.getString(TAG_NAME);
// String timestamp = c.getString(TAG_TIMESTAMP);
String id = c.getString(TAG_ID);
// JSONObject links = c.getJSONObject(TAG_LINKS);
// JSONObject api = c.getJSONObject(TAG_API);
// JSONObject sports = c.getJSONObject(TAG_SPORTS1);
// String href = c.getString(TAG_HREF);
HashMap<String, String> map = new HashMap<String, String>();
// map.put(TAG_TIMESTAMP, timestamp);
map.put(TAG_NAME, name);
// map.put(TAG_NEWS, news);
// map.put(TAG_HEADLINES, headlines);
map.put(TAG_ID, id);
// map.put(TAG_HREF, href);
sportsList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, sportsList,
R.layout.list_item,
new String[]{TAG_NAME,TAG_ID} , new int[] {
R.id.id,R.id.name});
setListAdapter(adapter);
}
}
here is my link I am using
Sample Link
I would recomend you to use gson. For me it was much more easier to work with...
EDIT: (some sample code)
Download the gson-2.2.2.jar add it to your dependencies
Create a base class (when you use more than one request)
public abstract class RequestBase {
public String ToJson(){
Gson gson = new Gson();
return gson.toJson(this);
}
public abstract String getUrl();
protected String getBaseUrl(){
return //Your URL;
}
}
Make a class which will execute your request..
Make classes for the requests and responses. Then you can just enter them with getters and setters:
public class SomeRequest extends RequestBase {
#SerializedName("Parameter1")
private int Parameter1;
public void setParameter1(int Parameter1) {
this.Parameter1= Parameter1;
}
public int getParameter1() {
return Parameter1;
}
#Override
public String getUrl() {
return this.getBaseUrl() +"YOUR/OWN/URL" + Parameter1;
}
}
and
public class SomeResponse {
#SerializedName("responseParameter1")
private int responseParameter1;
#SerializedName("responseParameter2")
private String responseParameter2;
public void setResponseParameter1(int responseParameter1) {
this.responseParameter1= responseParameter1;
}
public int getResponseParameter1() {
return responseParameter1;
}
public void setResponseParameter2(String responseParameter2) {
this.responseParameter2= responseParameter2;
}
public String getResponseParameter1() {
return responseParameter2;
}
}
Related
I am trying to parse a single JSON object that looks like this:
{
"message":"Request Successful",
"data":{
"id":"g8nEDt",
"name":"Twins Bazil Twins",
"nameDisplay":"Twins Bazil Twins",
"abv":"6.75",
"isOrganic":"N",
"description":"Beers",
}
},
"status":"success"
}
This is the code that I am using.
public class randomBeer extends Activity {
TextView name1;
TextView description1;
TextView abv1;
TextView ibu1;
Button Btngetdata;
//URL to get JSON Array
private static String urlRandom = "http://api.brewerydb.com/v2/beer/random?key=mykey";
//JSON Node Names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ABV = "abv";
private static final String TAG_IBU = "ibu";
JSONObject data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.randombeer);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView)findViewById(R.id.name);
description1 = (TextView)findViewById(R.id.description);
abv1 = (TextView)findViewById(R.id.abv);
ibu1 = (TextView)findViewById(R.id.ibu);
pDialog = new ProgressDialog(randomBeer.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(urlRandom);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
data= json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String ibu;
if(c.has("ibu")) {
ibu = c.getString(TAG_IBU);
} else {
ibu = "No ibu value";
}
String abv;
if(c.has("abv")) {
abv = c.getString(TAG_ABV);
} else {
abv = "No abv value";
}
String description;
if(c.has("description")) {
description = c.getString(TAG_DESCRIPTION);
} else {
description = "No description available";
}
//Set JSON Data in TextView
name1.setText(name);
description1.setText(description);
abv1.setText(abv);
ibu1.setText(ibu);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
The problem is that it is trying to get an array but I just need and object.
How can I transform this code so it gets the object instead of trying to get an array?
I tried to change
data = json.getJSONArray(TAG_DATA);
to
data = json.getJSONObject(TAG_DATA);
but then on the line
JSONObject c = data.getJSONObject(0);
I get an Error:
(87, 51) error: incompatible types: int cannot be converted to
String.
It should be
data= json.getJSONObject(TAG_DATA);
instead of
data= json.getJSONArray(TAG_DATA);
in onPostExecute. It now has
"data":{
"id":"g8nEDt",
"name":"Twins Bazil Twins",
"nameDisplay":"Twins Bazil Twins",
"abv":"6.75",
"isOrganic":"N",
"description":"Beers",
}
in it. To get i.e. the "name" use
String name = data.getString("name");
IN ADDITION:
Make sure to execute HttpGet instead of HttpPost when using this link
http://api.brewerydb.com/v2/beer/random?key=mykey
Replace this:
// Getting JSON Array
data= json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
with:
// Getting JSON Object
data= json.getJSONObject(TAG_DATA);
Also, replace all "c" variable usages with "data".
I am new to Android. I am using Fedor's Lazy Loading List. Is it possible to get all the values from a HashMap (values were retrieved from mysql) and store it to private String[] drinkImages?
String[] drinkImages' values will be passed to adapter Lazy_Adapter.
Or is there any other way to pass the value to Lazy_Adapter?
Code:
Lazy_ListItem.java
public class Lazy_ListItem extends Activity {
ListView list;
Lazy_Adapter adapter;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all products list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// products JSONArray
JSONArray drinks = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView) findViewById(R.id.list);
adapter = new Lazy_Adapter(this, drinkImages);
list.setAdapter(adapter);
// Button b = (Button) findViewById(R.id.button1);
// b.setOnClickListener(listener);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
/*
* public OnClickListener listener = new OnClickListener() {
*
* #Override public void onClick(View arg0) {
* adapter.imageLoader.clearCache(); adapter.notifyDataSetChanged(); } };
*/
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
/*
* #Override protected void onPreExecute() { super.onPreExecute();
*
* pDialog = new ProgressDialog(Lazy_Adapter.this, Lazy_ListItem.class);
* pDialog.setMessage("Loading drinks. Please wait...");
* pDialog.setIndeterminate(false); pDialog.setCancelable(false);
* pDialog.show();
*
* //final ProgressDialog dialog; // dialog =
* ProgressDialog.show(getActivity, "Title", "Message", true); }
*/
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Products
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
String drk_image = c.getString(TAG_DRK_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_IMAGE, drk_image);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
private String[] drinkImages = {
"http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" }; }
Lazy_Adapter.java
public class Lazy_Adapter extends BaseAdapter {
String drk_name, drk_desc, drk_price, drk_avail;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all products list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// products JSONArray
JSONArray drinks = null;
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public Lazy_ImageLoader imageLoader;
public Lazy_Adapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new Lazy_ImageLoader(activity.getApplicationContext());
// Hashmap for ListView
drinksList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ///
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Products
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_NAME, drk_name);
map.put(TAG_DRK_DESC, drk_desc);
map.put(TAG_DRK_PRICE, drk_price);
map.put(TAG_DRK_AVAIL, drk_avail);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
#SuppressWarnings("unused")
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);
for (Map<String, String> menuItem : drinksList) {
ImageView image = (ImageView) vi.findViewById(R.id.image);
imageLoader.DisplayImage(data[position], image);
TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
tvMenuName.setText(drinksList.get(position).get(TAG_DRK_NAME));
TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
tvMenuDesc.setText(drinksList.get(position).get(TAG_DRK_DESC));
TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
tvMenuPrice.setText("P"
+ drinksList.get(position).get(TAG_DRK_PRICE));
TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
tvMenuAvail.setText(drinksList.get(position).get(TAG_DRK_AVAIL));
}
return vi;
}}
I hope you can help me. Thank you.
You can access perticular string on loacation with this code. Here i is an index number which may be 0,1,2 etc.
String yourstring = drinksList.get(i).get(TAG_DRK_IMAGE)
String[] drinkImages = (String[]) drinkList.get(0).values().toArray();
Yes, something like this will work .
public static void main(String[] args) {
Map<String, String> hm = new HashMap<String, String>(); // and yes. I am still using java 6 :(
hm.put("a", "a.jpg");
hm.put("b", "b.jpg");
String[] arr = new String[hm.size()];
hm.values().toArray(arr);
for (String s : arr) {
System.out.println(s);
}
}
O/P:
b.jpg
a.jpg
Try to iterate HashMap and build Array from HashMap value :
public String[] getStringArrayFromMap(HashMap<String,String> map){
String[] array = new String[map.size()];
int i=0;
for (String key : map.keySet()) {
array[i++] = map.get(key);
}
return array;
}
I am just a newbie with Android programming. I am using Fedor's LazyList for my thesis. I've been trying to configure his code but I am not getting any luck. What I would like to do is retrieve data from mysql and place it into the textviews. However, I am only getting the same last data for all textviews and I am not sure why the 3rd one's empty.
My LogCat shows I am getting all the data from the database, so the problem must be the structure of the code.
Code:
Lazy_ListItem.java
public class Lazy_ListItem extends Activity {
ListView list;
Lazy_Adapter adapter;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
// private static String url_all_products =
// "http://10.0.2.2/android_connect/get_all_products.php";
private static String url_all_products = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// products JSONArray
JSONArray drinks = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView) findViewById(R.id.list);
adapter = new Lazy_Adapter(this, mStrings);
list.setAdapter(adapter);
// Button b = (Button) findViewById(R.id.button1);
// b.setOnClickListener(listener);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
/*public OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};*/
private String[] mStrings = {
"http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" };
}
Lazy_Adapter.java
public class Lazy_Adapter extends BaseAdapter {
TextView tvMenuName, tvMenuDesc, tvMenuPrice;
String drk_name, drk_desc, drk_price, drk_avail;
int length;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
// private static String url_all_products =
// "http://10.0.2.2/android_connect/get_all_products.php";
private static String url_all_products = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// products JSONArray
JSONArray drinks = null;
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public Lazy_ImageLoader imageLoader;
public Lazy_Adapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new Lazy_ImageLoader(activity.getApplicationContext());
// Loading products in Background Thread
new LoadAllProducts().execute();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ///
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
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 response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Products
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
length = drinks.length();
// Storing each json item in variable
String rid = c.getString(TAG_RID);
String drk_id = c.getString(TAG_DRK_ID);
drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_RID, rid);
// map.put(TAG_DRK_ID, drk_id);
// map.put(TAG_DRK_NAME, drk_name);
// map.put(TAG_DRK_DESC, drk_desc);
// map.put(TAG_DRK_PRICE, drk_price);
// adding HashList to ArrayList
// productsList.add(map);
}
}
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}}
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);
// text.setText("Drinks " + position);
//TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
ImageView image = (ImageView) vi.findViewById(R.id.image);
imageLoader.DisplayImage(data[position], image);
TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
tvMenuName.setText(drk_name);
TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
tvMenuDesc.setText(drk_desc);
TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
tvMenuPrice.setText("P" + drk_price);
TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
tvMenuAvail.setText(drk_avail);
return vi;
}
}
I hope you can help me. Thank you.
UPDATE: Changed code to this and it worked!
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
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 response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Products
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_NAME, drk_name);
map.put(TAG_DRK_DESC, drk_desc);
map.put(TAG_DRK_PRICE, drk_price);
map.put(TAG_DRK_AVAIL, drk_avail);
// adding HashList to ArrayList
productsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);
for (Map<String, String> menuItem : productsList) {
ImageView image = (ImageView) vi.findViewById(R.id.image);
imageLoader.DisplayImage(data[position], image);
TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
tvMenuName.setText(productsList.get(position).get(TAG_DRK_NAME));
TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
tvMenuDesc.setText(productsList.get(position).get(TAG_DRK_DESC));
TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
tvMenuPrice.setText(productsList.get(position).get(TAG_DRK_PRICE));
TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
tvMenuAvail.setText(productsList.get(position).get(TAG_DRK_AVAIL));
}
return vi;
}
It looks like in getView() method you're pulling data out of variables that have been set as class fields, when you need to be pulling it out of the productsList instead.
Try replacing
tvMenuName.setText(drk_name);
with
tvMenuName.setText(productsList.get(position).get(TAG_DRK_NAME));
And so on down the line...
You are seeing the last part of the data in all the TextViews because in your loop in the AsyncTask you set the same variables every time as below. You need to sake these on every iteration of the loop. You could use a HashMap in a List for example. The in the getView method do something like productsList.get(position).get(TAG_DRK_NAME) etc. You actually have most of this commented out.
drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);
I am new to Android.
I want to get the values of drk_image or TAG_DRK_IMAGE from the HashMap and store it to private String[ ] drinkImages. Is this possible?
Code:
Lazy_ListItem.java
public class Lazy_ListItem extends Activity {
ListView list;
Lazy_Adapter adapter;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all drinks list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_DRK_IMAGE = "drk_image";
// drinks JSONArray
JSONArray drinks = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView) findViewById(R.id.list);
adapter = new Lazy_Adapter(this, drinkImages);
list.setAdapter(adapter);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
/**
* Background Async Task to Load all drinks by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All drinks from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// drinks found
// Getting Array of Drinks
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Drinks
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
String drk_image = c.getString(TAG_DRK_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_IMAGE, drk_image);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
private String[] drinkImages = {
"http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" }; }
The value of String[ ] drinkImages must be replaced with values from the HashMap (from the database) and so I can pass it to Lazy_Adapter.
I want to get the values from the database instead of just declaring it like this:
private String[] drinkImages = {
"http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" };
Lazy_Adapter.java
public class Lazy_Adapter extends BaseAdapter {
String drk_name, drk_desc, drk_price, drk_avail;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all drinks list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// drinks JSONArray
JSONArray drinks = null;
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public Lazy_ImageLoader imageLoader;
public Lazy_Adapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new Lazy_ImageLoader(activity.getApplicationContext());
// Hashmap for ListView
drinksList = new ArrayList<HashMap<String, String>>();
// Loading drinks in Background Thread
new LoadAllProducts().execute();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ///
/**
* Background Async Task to Load all drinks by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All drinks from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// drinks found
// Getting Array of Drinks
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Drinks
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_NAME, drk_name);
map.put(TAG_DRK_DESC, drk_desc);
map.put(TAG_DRK_PRICE, drk_price);
map.put(TAG_DRK_AVAIL, drk_avail);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
#SuppressWarnings("unused")
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);
for (Map<String, String> menuItem : drinksList) {
ImageView image = (ImageView) vi.findViewById(R.id.image);
imageLoader.DisplayImage(data[position], image);
TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
tvMenuName.setText(drinksList.get(position).get(TAG_DRK_NAME));
TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
tvMenuDesc.setText(drinksList.get(position).get(TAG_DRK_DESC));
TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
tvMenuPrice.setText("P"
+ drinksList.get(position).get(TAG_DRK_PRICE));
TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
tvMenuAvail.setText(drinksList.get(position).get(TAG_DRK_AVAIL));
}
return vi;
}}
EDIT:
Output:
This is the output if I have declared private String[] drinkImages. I am hoping to get the same output when getting it from the database.
Emulator Screenshot
Database Screenshot
I am doing this for my thesis. Really appreciate any help.
Thanks a lot~
Because you are using AsyncTask, maybe your task isn't finished yet.
So, you should add your adapter instance and assign it to your listview in onPostExecute method.
Please change your LazyListItem.java looklike below code:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.widget.ListView;
public class Lazy_ListItem extends Activity {
ListView list;
Lazy_Adapter adapter;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all drinks list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_DRK_IMAGE = "drk_image";
// Your Images Array
private String[] drinkImages;
// drinks JSONArray
JSONArray drinks = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView) findViewById(R.id.list);
new LoadAllProducts().execute();
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
/**
* Background Async Task to Load all drinks by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All drinks from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// drinks found
// Getting Array of Drinks
drinks = json.getJSONArray(TAG_DRINKS);
// Define Lenght for Images Array
drinkImages = new String[drinks.length()];
// looping through All Drinks
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
String drk_image = c.getString(TAG_DRK_IMAGE);
// Add image into Array
drinkImages[i] = drk_image;
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_IMAGE, drk_image);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
adapter = new Lazy_Adapter(this, drinkImages);
list.setAdapter(adapter);
super.onPostExecute(result);
}
}
I'm new to Android coding. I have written a multi-line List using SimpleAdapter, but the text does not display. If I switch to a hardcoded hashlist, the text shows up on screen. To ensure that my varaible actually containes text, I have printed its contents using Log.e.
What could I be doing wrong?
public class AndroidListViewActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
ListParse mytask;
super.onCreate(savedInstanceState);
mytask = new ListParse();
mytask.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.layout.activity_main, menu);
return true;
}
private class ListParse extends AsyncTask<URL, Integer, Long> {
// url to make request
private static final String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
// create the grid item mapping
String[] from = new String[] { "TAG_NAME", "TAG_EMAIL", "TAG_PHONE_MOBILE" };
int[] to = new int[] { R.id.list_name, R.id.list_email, R.id.list_mobile };
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
protected void onPostExecute(Long result) {
Iterator<HashMap<String, String>> entry = contactList.iterator();
while (entry.hasNext()){
Log.e("Debug Info", "We have " + entry.next());
}
SimpleAdapter adapter = new SimpleAdapter(AndroidListViewActivity.this, contactList,
R.layout.list_item, from, to);
setListAdapter(adapter);
}
#Override
protected Long doInBackground(URL... arg0) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// Phone number is again JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}