Get image url from json array from wordpress json api - android

am working on new reader that is to get news post froma wordpress site to android fone app.
i can get the test(title,date,content) from the json array but i cannot get the image url from the array any ideas
class LoadBrkNews extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Breaking.this);
pDialog.setMessage("Loading News Feeds...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting breaking JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(BREAK_URL, "GET",
params);
// Check your log cat for JSON reponse
Log.d("BREAKING NEWS JSON: ", json.toString());
try {
if (json.getString("status").equalsIgnoreCase("ok")) {
breakFeeds = json.getJSONArray("posts");
//breakImg = json.getJSONArray(TAG_IMAGE_URL);
// looping through All messages
for (int i = 0; i < breakFeeds.length(); i++) {
JSONObject c = (JSONObject) breakFeeds.getJSONObject(i);
// JSONObject forImg = (JSONObject) breakImg.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String date = c.getString(TAG_DATE);
// remember to remove this line fro production
String urlForImage = c.getString(TAG_IMAGE_URL);
Log.d("attachemtent url",urlForImage);
// Strip off tags
String fcontent = content.replaceAll("<(.*?)\\>"," ");
// 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_TITLE, title);
map.put(TAG_CONTENT, fcontent);
map.put(TAG_DATE, date);
map.put(TAG_IMAGE_URL, urlForImage);
// adding HashList to ArrayList
breakingNewsList.add(map);
ObjectOutput out = new ObjectOutputStream(
new FileOutputStream(tempFile));
String toCache = breakFeeds.toString();
out.writeObject(toCache);
out.close();
Log.d("Write to Cache", "Success");
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
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(Breaking.this,
breakingNewsList, R.layout.imagelayout,
new String[] { TAG_TITLE, TAG_CONTENT, TAG_DATE,
TAG_IMAGE_URL }, new int[] {
R.id.title, R.id.content, R.id.date,R.id.imglink });
// updating listview
setListAdapter(adapter);
}
});
}
}
`

Since your having trouble only with the image url, I guess it can be either
1. Your data is missing the image url
2. TAG_IMAGE_URL is not matching the key in the data.
Try using some json parsing libary to make things easier.

Related

Android: AsyncTask causes app to crash, no error logs printed

i am currently trying a tutorial to connect an android app with a server (link: https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/).
However, i have difficulties with an AsyncTask which is supposed to load the elements of a database. It causes the app to crash and leaves no error logs in the logcat (also tried "no filter"). I surrounded the execute call with a try catch block as well, but the app still crashes. Any ideas what is causing the error?
here are extracts from the code:
public class AllProductsActivity extends ListActivity {
private static String url_all_products = "https://api.androidhive.info/android_connect/get_all_products.php";
...
#Override
public void onCreate(Bundle savedInstanceState) {
try {
new LoadAllProducts().execute();
}catch (Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
...
/**
* 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
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<Pair> params = new ArrayList<Pair>();
// 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 {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// 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);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
AddNewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} 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);
}
});
}
}
The problem is not with your code implementation. I can see webservice url in your code as
private static String url_all_products = "https://api.androidhive.info/android_connect/get_all_products.php";
The problem is with this web service. That is no longer working. I tested the webservice as you mentioned the link of the tutorial over postman, that is not working any more. Hope you get my point. Feel free to ask me if you have any confusions.

Android Background web service Issue

I really need your help. I am building an Android app that needs a lot of HTTP requests such as logging to the server(check if user is exists or not) and storing the session to the database (user_sessions table), adding, updating and deleting records.
In my Login Activity, I have my AsyncTask (to check if user exits) and other background threads (logs the user session and download user info to database) . This is successful. Next, when I update the user info, it updates successfully. But what if I update using my web app? My should display the newly updated info on my android app. How can I resolve this problem?
This is what I've tried so far:
private void logSessionToServer() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
strUsername = etUsername.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_log_session,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("", "Successfully logged session!");
} else {
// failed
Log.d("", "Not Successful!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
thread.start();
}
/**
* Background Async Task to Create new record
* */
class LoginTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setIcon(R.drawable.upload);
pDialog.setTitle("Connecting to server");
pDialog.setMessage("Validating login details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
*
* */
protected String doInBackground(String... args) {
strUsername = etUsername.getText().toString();
strPassword = etPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
params.add(new BasicNameValuePair( TAG_PASSWORD, strPassword ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
logSessionToServer(); // Save login to server
saveUserInfoToDB(); // Save user info to DB
saveUserloggedIn(); // Save user logged in to preference
savePriestInfoToDB(); // Save priest to DB
Log.d("", "Successful Login!");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
finish();
} else {
// failed
new Thread()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(),
"Not Successful Login", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
Log.d("", "Not Successful Login!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
private void saveUserInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(url_view_loggedUser_profile);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_FIRSTNAME, jb.getString(TAG_FIRSTNAME));
map.put(TAG_MIDDLENAME, jb.getString(TAG_MIDDLENAME));
map.put(TAG_LASTNAME, jb.getString(TAG_LASTNAME));
map.put(TAG_EMAIL, jb.getString(TAG_EMAIL));
map.put(TAG_AGE, jb.getString(TAG_AGE));
map.put(TAG_GENDER, jb.getString(TAG_GENDER));
map.put(TAG_USERNAME, jb.getString(TAG_USERNAME));
map.put(TAG_PASSWORD, jb.getString(TAG_PASSWORD));
map.put(TAG_BARANGAY, jb.getString(TAG_BARANGAY));
map.put(TAG_COMPLETEADDRESS, jb.getString(TAG_COMPLETEADDRESS));
map.put(TAG_CUS_ID, jb.getString(TAG_CUS_ID));
map.put(TAG_REG_DATE, jb.getString(TAG_REG_DATE));
map.put(TAG_BD_MONTH, jb.getString(TAG_BD_MONTH));
map.put(TAG_BD_DATE, jb.getString(TAG_BD_DATE));
map.put(TAG_BD_YEAR, jb.getString(TAG_BD_YEAR));
arraylist.add(map);
String strCusID = jb.getString(TAG_CUS_ID);
String strFname = jb.getString(TAG_FIRSTNAME);
String strMname = jb.getString(TAG_MIDDLENAME);
String strLname = jb.getString(TAG_LASTNAME);
String strEmail = jb.getString(TAG_EMAIL);
String strAge = jb.getString(TAG_AGE);
String strGender = jb.getString(TAG_GENDER);
String strUsername = jb.getString(TAG_USERNAME);
String strPassword = jb.getString(TAG_PASSWORD);
String strBarangay = jb.getString(TAG_BARANGAY);
String strCompleteAddress = jb.getString(TAG_COMPLETEADDRESS);
String strRegDate = jb.getString(TAG_REG_DATE);
String strBDMonth = jb.getString(TAG_BD_MONTH);
String strBDDate = jb.getString(TAG_BD_DATE);
String strBDYear = jb.getString(TAG_BD_YEAR);
try{
dbHelper.insertEntry(strCusID, strFname, strMname, strLname, strEmail,
strAge, strGender, strUsername, strPassword,
strBarangay, strCompleteAddress, strRegDate,
strBDMonth, strBDDate, strBDYear);
Log.d("Response", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
private void savePriestInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(URL_VIEW_PRIESTS);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_P_ID, jb.getString(TAG_P_ID));
map.put(TAG_P_FIRSTNAME, jb.getString(TAG_P_FIRSTNAME));
map.put(TAG_P_MIDDLENAME, jb.getString(TAG_P_MIDDLENAME));
map.put(TAG_P_LASTNAME, jb.getString(TAG_P_LASTNAME));
map.put(TAG_P_EMAIL, jb.getString(TAG_P_EMAIL));
map.put(TAG_P_AGE, jb.getString(TAG_P_AGE));
map.put(TAG_P_ADDRESS, jb.getString(TAG_P_ADDRESS));
map.put(TAG_P_CONTACT, jb.getString(TAG_P_CONTACT));
map.put(TAG_P_STATUS, jb.getString(TAG_P_STATUS));
arraylist.add(map);
String strP_ID = jb.getString(TAG_P_ID);
String strP_Fname = jb.getString(TAG_P_FIRSTNAME);
String strP_Mname = jb.getString(TAG_P_MIDDLENAME);
String strP_Lname = jb.getString(TAG_P_LASTNAME);
String strP_Email = jb.getString(TAG_P_EMAIL);
String strP_Age = jb.getString(TAG_P_AGE);
String strP_Address = jb.getString(TAG_P_ADDRESS);
String strP_Status = jb.getString(TAG_P_STATUS);
String strP_Contact = jb.getString(TAG_P_CONTACT);
try{
dbHelper.insertPriest(strP_ID, strP_Fname, strP_Mname,
strP_Lname, strP_Email, strP_Age,
strP_Address, strP_Status, strP_Contact);
Log.d("Response - Priest", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response - Priest", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
Feel free to check out my codes and give feedback if this is the best practice for HTTP requests. I am new to Web Services so I really need your help. Any help will be greatly appreciated. Thanks
Well what I just said: you write a thread which downloads user-info every 5 seconds. then it compares the user info downloaded with the user info that is already stored on your device. if there is a difference, an update has been made, and your thread invokes a new download of the updated user info.

how to load image and pass to Layout using JSON Data?

This is My code,I'm trying to pass the image to listview but i get error.
how can i pass image ? should i download it into local memory first and then send it listview ??
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all, "GET", params);
if(json == null)
System.out.println("NULL");
else{
// Check your log cat for JSON reponse
Log.d("All Developers: ", json.toString());
try {
// Checking for SUCCESS TAG
int status = json.getInt(TAG_STATUS);
if (status == 1) {
// products found
// Getting Array of Products
developers = json.getJSONArray(TAG_all);
// looping through All Products
for (int i = 0; i < developers.length(); i++) {
JSONObject c = developers.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
String image = c.getString(TAG_IMAGE_PATH);
// 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_NAME, name);
//map.put(TAG_IMAGE_PATH, image);
// adding HashList to ArrayList
developersList.add(map);
//Iamge Download
}
} else {
System.out.println("No Data");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(),
developersList,R.layout.list_data, new String[] { TAG_UID,
TAG_NAME,TAG_IMAGE_PATH},
new int[] { R.id.uid, R.id.name,R.id.image });
// updating listview
lv.setAdapter(adapter);
}
});
}
}
}
Errors
03-30 13:34:03.475: E/BitmapFactory(22326): Unable to decode stream: java.io.FileNotFoundException
You don't have to re-invent the wheel - assuming you have the url to the image you can use nostra13 library for image loading it'll do all the nasty staff for you (cache handling downloading\ saving thumbnail etc..) it also have an exmaple project you can look at to better unnderstand of how to use it.

Not able to show item image in listview

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...

Using ASync Task to display data in LIstView on postExecute

the problem that im having is kind of weird the printstack of the JSON is correct displaying all the element in the table the way that it should the same as for the method String doInBackground(String... args) the problem is in the postExecute method that is displaying the same element in all the element of the listview "the last element in the row of the table to be exact can someone tell me what i did wrong " thank you for your time bellow you will find the class that im talking about thank you
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProDentActivity.this);
pDialog.setMessage("Loading Balance. 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.getJSONFromUrl(balanceURL, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
amount = json.getJSONArray(TAG_BALANCE);
// looping through All Products
for (int i = 0; i < amount.length(); i++) {
JSONObject c = amount.getJSONObject(i);
// Storing each json item in variable
String amount = c.getString(TAG_AMOUNT);
String createdat = c.getString(TAG_CREATEDAT);
//String userid = c.getString(TAG_USERID);
// adding each child node to HashMap key => value
map.put(TAG_AMOUNT, amount);
map.put(TAG_CREATEDAT, createdat);
//map.put(TAG_USERID , userid);
// adding HashList to ArrayList
amountlist.add(map);
}
} else {
// no balance found
// Launch Add New balance Activity
Intent i = new Intent(getApplicationContext(),
ProDentActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
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() {
ListAdapter adapter = new SimpleAdapter(
ProDentActivity.this, amountlist,
R.layout.list_item, new String[] { TAG_AMOUNT,TAG_CREATEDAT},
new int[] { R.id.amount, R.id.createdat });
// updating listview
setListAdapter(adapter);
}
});
}
}
JSON:
{"balance":[{"amount":"50000","created_at":"2012-12-15 02:39:13"},{"amount":"50000","created_at":"2012-12-16 15:29:03"},{"amount":"30000","created_at":"2012-12-17 19:38:07"}],"success":1}
...and the method returns
12-18 02:29:05.797: D/All Products:(885): {"success":1,"balance":[{"amount":"50000","created_at":"2012-12-15 02:39:13"},{"amount":"50000","created_at":"2012-12-16 15:29:03"},{"amount":"30000","created_at":"2012-12-17 19:38:07"}]}
problem fixed i found what i have been doing wrong. the problem was that i didn't define my hash map in the method protected String doInBackground(String... args)
i was defining it in the listactivity anw thank you for your time and help
bellow code to be replaced with the old one
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
amount = json.getJSONArray(TAG_BALANCE);
// looping through All Products
for (int i = 0; i < amount.length(); i++) {
JSONObject c = amount.getJSONObject(i);
// Storing each json item in variable
String amount = c.getString(TAG_AMOUNT);
String createdat = c.getString(TAG_CREATEDAT);
//String userid = c.getString(TAG_USERID);
// adding each child node to HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_AMOUNT, amount);
map.put(TAG_CREATEDAT, createdat);
//map.put(TAG_USERID , userid);
// adding HashList to ArrayList
amountlist.add(map);
}
} else {
// no balance found
// Launch Add New balance Activity
Intent i = new Intent(getApplicationContext(),
ProDentActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

Categories

Resources