I have made a program in which I am using PHP to encode data as JSON. My program is working fine, and is not showing any errors or problems; I am getting what I want but I am facing very small issue.
Here, I am not able to show an item's image in ListView but whenever I click on one of the item rows to view full item detail, I get the image of selected item. It means I should be getting the image in ListView, but I'm unable to show that, so could someone please help to sort out this mistake?
public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
// albums JSONArray
JSONArray albums = null;
String imagepath;
// albums JSON url
private static final String URL_ALBUMS = "MY URL";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_IMAGEPATH = "imagepath";
private static final String TAG_SONGS_COUNT = "songs_count";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
// send album id to tracklist activity to get list of songs under that album
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
String imageurl = c.getString(TAG_IMAGEPATH);
String songs_count = c.getString(TAG_SONGS_COUNT);
// 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_DESCRIPTION, description);
map.put(TAG_IMAGEPATH,imageurl);
map.put(TAG_SONGS_COUNT, songs_count);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} 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 albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[]
{
TAG_ID, TAG_NAME, TAG_DESCRIPTION, TAG_IMAGEPATH, TAG_SONGS_COUNT
},
new int[]
{
R.id.album_id, R.id.album_name, R.id.album_description, R.id.list_image, R.id.songs_count
}
);
// updating listview
setListAdapter(adapter);
}
});
}
}
You have to first download the image and then show it in list view. You can not directly pass the image URL, it will not work.
Change your current code as and also remove runOnUiThread() from onPostExecute method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String,
ArrayList<HashMap<String, String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected ArrayList<HashMap<String, String>>
doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
String imageurl = c.getString(TAG_IMAGEPATH);
String songs_count = c.getString(TAG_SONGS_COUNT);
// 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_DESCRIPTION, description);
map.put(TAG_IMAGEPATH,imageurl);
map.put(TAG_SONGS_COUNT, songs_count);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return albumsList;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(ArrayList<HashMap<String,
String>> file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// get listview
ListView lv = getListView();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, file_url,
R.layout.list_item_albums, new String[]
{
TAG_ID, TAG_NAME, TAG_DESCRIPTION,
TAG_IMAGEPATH, TAG_SONGS_COUNT
},
new int[]
{
R.id.album_id,
R.id.album_name, R.id.album_description, R.id.list_image, R.id.songs_count
}
);
// updating listview
lv.setListAdapter(adapter);
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
Intent i = new Intent(getApplicationContext(),
TrackListActivity.class);
// send album id to tracklist activity to get list of songs
//under that album
String album_id = ((TextView) view.
findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
}
NOTE : if you are given direct web URL in ImageView then this will never work because you will need first download image from Web then set it to ImageView src.
see this post how we take image from web server
How to load an ImageView by URL in Android?
It means that you want to customize your list view with image and text. For that (what i did in my case), get the image url and text in two arrays. then set the adapter of the list view by passing context, both arrays.
For setting up images, you need to import the library (Either image url helper or Universe image loader). Both can help you well but i will recommend you for the image url helper library because it is easy to use.
Try this in your Adapter, It might help you:
String imageURL = "htp://domain/some-path/kdhfbdskf.jpg";
Bitmap bmp = null;
try {
InputStream in = new java.net.URL(imageURL).openStream();
bmp = BitmapFactory.decodeStream(in);
}
catch (IOException e) {
e.printStackTrace();
}
if (bmp != null) {
holder.UserImageView.setImageBitmap(bmp);
} else {
holder.UserImageView.setImageResource(R.drawable.ic_launcher);
}
remov the runOnUiThread() from the post Execute and you do not run UI component into thread.. simply set images...
Related
I am new to android development. I managed to populate a listview with a string and a number coming from a JSON array.
I want to add a string (Available Quantity: ) before I display the number.
Can anyone help me with this?
It's being currently displayed as..
French Fries
1
Coke
4
I want to display it as:
Product: Coke
Quantity Available: 4
AllProductsActivity.java
public class AllProductsActivity extends ListActivity {
// 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://api.nal.usda.gov/ndb/search/?format=json&q=french%20fries&sort=n&max=250&offset=0&api_key=DEMO_KEY";
// JSON Node names
private static final String TAG_PID = "offset";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
/**
* 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(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* 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 reponse
Log.d("All Products: ", json.toString());
try {
// products found
// Getting Array of Products
products = json.getJSONObject("list").getJSONArray("item");
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.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();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
you can simple add up string when getting it from json like..
String id = "Quantity Available: "+c.getString(TAG_PID);
String name = "Product: "+c.getString(TAG_NAME);
I make list that show text from database but the image near items. I need images that get from drawable folder in Android. It means in listview text from database and image from Android.
Code is:
public class Category extends Activity {
// progress dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> categoryList;
private static String url_books = "http://10.0.2.2/project/category.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CATEGORY = "category";
private static final String TAG_CATEGORY_ID = "category_id";
private static final String TAG_CATEGORY_NAME = "category_name";
private static final String TAG_MESSAGE = "massage";
// category JSONArray
JSONArray category = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"font/bnazanin.TTF");
// Hashmap for ListView
categoryList = new ArrayList<HashMap<String, String>>();
new LoadCategory().execute();
ListView imagelist=(ListView) findViewById(R.id.list_image);
imagelist.setAdapter(new imageview(this));
}
/**
* Background Async Task to Load category by making HTTP Request
* */
class LoadCategory extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Category.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_books, "GET", params);
// Check your log cat for JSON reponse
Log.d("category: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Getting Array of category
category = json.getJSONArray(TAG_CATEGORY);
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
// Storing each json item in variable
String category_id = c.getString(TAG_CATEGORY_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CATEGORY_ID,category_id);
map.put(TAG_CATEGORY_NAME, category_name);
// adding HashList to ArrayList
categoryList.add(map);
}
return json.getString(TAG_MESSAGE);
} else {
System.out.println("no category found");
}
} 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();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListView lv=(ListView)findViewById(R.id.list_view);
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Category.this,categoryList,
R.layout.category_item, new String[] { TAG_CATEGORY_NAME},
new int[] { R.id.category_name });
// updating listview
// setListAdapter(adapter);
lv.setAdapter(adapter);
}
});
}
}
In my code, i have text but no image. Any help?
Create a pojo for your needs in list items,You can set pojos values from web or local, then use custom listadapter override getView method according to ur needs. A good explanation here!
I am trying to implement a simple listview based on strings. I followed this tutorial
http://www.androidhive.info/2012/10/android-multilevel-listview-tutorial/
Now, I want to add a filter function but I did not find a simple way to do that.
The class ListViewAdapter gives the method getfilter() but not ListAdapter.
Can you help me out with that?
Regards.
public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
// albums JSONArray
JSONArray hotels = null;
// albums JSON url
private static final String URL_HOTELS = "http://10.0.2.2:8888/slim/hotels";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "hotel";
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i = new Intent(getApplicationContext(), SingleTrackActivity.class);
// send album id to tracklist activity to get list of songs under that album
String hotel_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("hotel_id", hotel_id);
startActivity(i);
}
});
TextView inputSearch = (TextView) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
//AlbumsActivity.this.adapter.getFilter().filter(cs);
Log.d("filter :", cs.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Loading hotels ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json;
json = jsonParser.makeHttpRequest(URL_HOTELS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Hotels JSON: ", "> " + json);
try {
hotels = new JSONArray(json);
if (hotels != null) {
// looping through All albums
for (int i = 0; i < hotels.length(); i++) {
JSONObject c = hotels.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// 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);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} 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 albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[] { TAG_ID,
TAG_NAME }, new int[] {
R.id.album_id, R.id.album_name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
just change ListAdapter to SimpleAdapter everything is still be the same but filter function :)
these work for me
I am writing an app in which i am fetching data from JSON, and i am able to fetch list of Categories but whenever i do click on any of the Category not getting List of Products under that particular Category always getting Blank activity.
JSON:
[
{
"categoryId": "1",
"categoryTitle": "SmartPhones", "SmartPhones": [
{
"itemId": "1",
"itemTitle": "Galaxy Mega 5.8"
},
{
"itemId": "2",
"itemTitle": "Galaxy Mega 6.3"
}
]
},
{
"categoryId": "2",
"categoryTitle": "Tablets", "Tablets": [
{
"itemId": "1",
"itemTitle": "Galaxy Note 510"
},
{
"itemId": "2",
"itemTitle": "Galaxy Note 800"
}
]
}
]
AlbumsActivity.java [using for Categories]:
public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
// albums JSONArray
JSONArray albums = null;
// albums JSON url
private static final String URL_ALBUMS = "my.json"; //providing proper URL
// ALL JSON node names
private static final String TAG_ID = "categoryId";
private static final String TAG_NAME = "categoryTitle";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
// send album id to tracklist activity to get list of songs under that album
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// 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);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} 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 albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[] { TAG_ID,
TAG_NAME }, new int[] {
R.id.album_id, R.id.album_name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
TrackListActivity.java [using for Products]:
public class TrackListActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> tracksList;
// tracks JSONArray
JSONArray albums = null;
// Album id
String album_id, album_name;
// tracks JSON url
// id - should be posted as GET params to get track list (ex: id = 5)
private static final String URL_ALBUMS = "my.json"; //providing proper url
// ALL JSON node names
private static final String TAG_ID = "itemId";
private static final String TAG_NAME = "itemTitle";
private static final String TAG_ALBUM = "categoryId";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracks);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(TrackListActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Get album id
Intent i = getIntent();
album_id = i.getStringExtra("album_id");
// Hashmap for ListView
tracksList = new ArrayList<HashMap<String, String>>();
// Loading tracks in Background Thread
new LoadTracks().execute();
// get listview
ListView lv = getListView();
/**
* Listview on item click listener
* SingleTrackActivity will be lauched by passing album id, song id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// On selecting single track get song information
Intent i = new Intent(getApplicationContext(), SingleTrackActivity.class);
// to get song information
// both album id and song is needed
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
String song_id = ((TextView) view.findViewById(R.id.song_id)).getText().toString();
Toast.makeText(getApplicationContext(), "Album Id: " + album_id + ", Song Id: " + song_id, Toast.LENGTH_SHORT).show();
i.putExtra("album_id", album_id);
i.putExtra("song_id", song_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all tracks under one album
* */
class LoadTracks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TrackListActivity.this);
pDialog.setMessage("Loading songs ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting tracks json and parsing
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// post album id as GET parameter
params.add(new BasicNameValuePair(TAG_ID, album_id));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Track List JSON: ", json);
try {
JSONObject jObj = new JSONObject(json);
if (jObj != null) {
String album_id = jObj.getString(TAG_ID);
album_name = jObj.getString(TAG_ALBUM);
if (albums != null) {
// looping through All songs
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item in variable
String song_id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("album_id", album_id);
map.put(TAG_ID, song_id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
tracksList.add(map);
}
} else {
Log.d("Albums: ", "null");
}
}
} 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 tracks
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
TrackListActivity.this, tracksList,
R.layout.list_item_tracks, new String[] { "album_id", TAG_ID,
TAG_NAME }, new int[] {
R.id.album_id, R.id.song_id, R.id.album_name });
// updating listview
setListAdapter(adapter);
// Change Activity Title with Album name
setTitle(album_name);
}
});
}
}
}
You read the JSON from the webservice into a JSONObject however the JSON you have posted is a JSONArray. Try something like this to parse your JSON...
JSONArray jObj = new JSONArray(json);
if (jObj != null) {
for(int i = 0; i < jObj.length(); i++) {
JSONObject cat = jObj.getJSONObject(i);
String id = cat.getString("categoryId");
String title = cat.getString("categoryTitle");
JSONArray devices = cat.optJSONArray(title, null);
for(int j=0; i<devices.length(); j++) {
//get itemId and itemTitle
}
}
}
I have a JSON string which is generated by a php file. The problem is that the JSON string is not appearing on the textview of android. can anyone explain why?
public class AllUsersActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
// url to get all users list
private static String url_all_users = "http://10.0.2.2/android_connect/get_all_users.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UID = "UserID";
private static final String TAG_FIRSTNAME = "FirstName";
// users JSONArray
JSONArray users = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_users);
// Hashmap for ListView
usersList = new ArrayList<HashMap<String, String>>();
// Loading users in Background Thread
new LoadAllusers().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String uid = ((TextView) view.findViewById(R.id.uid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
UserDetailsActivity.class);
// sending uid to next activity
in.putExtra(TAG_UID, uid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllusers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUsersActivity.this);
pDialog.setMessage("Loading users. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All users 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_users, "GET", params);
// Check your log cat for JSON reponse
Log.d("All users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// users found
// Getting Array of users
users = json.getJSONArray(TAG_USERS);
// looping through All users
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_FIRSTNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_UID, id);
map.put(TAG_FIRSTNAME, name);
// adding HashList to ArrayList
usersList.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 users
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllUsersActivity.this, usersList,
R.layout.list_item, new String[] { TAG_UID,
TAG_FIRSTNAME},
new int[] { R.id.uid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
this is the JSON string from the PHP file
{"Users":[{"0":[],"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"0":[],"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null,"1":[]},{"0":[],"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null,"1":[],"2":[]},{"0":[],"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null,"1":[],"2":[],"3":[]}],"success":1}
I've found the error.
It is caused by case sensitiveness.
users --> Users
Mistake on my part. Sorry.
Thanks for trying to help me!