Using ASync Task to display data in LIstView on postExecute - android

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

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.

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.

Get image url from json array from wordpress json api

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.

ListView doesn't refresh after adding/deleting something from a MySQL database

I wrote an Android app to manage a MySQL database, and I connect/add/delete rows with some PHP classes that are called by a HttpRequest in an AsyncTask in the background. There is just one simple thing I want, like:
Home screen -> Add screen -- Press add button --> Home screen
But when I add a row into the database, the listview won't refresh. But if I restart the app everything is getting recreated, and my listview displays the added row.
To get the information from the database, I use this code:
class LoadAllBooks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoadAllActivity.this);
pDialog.setMessage("Loading authors. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Getting all books from a 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_books, "GET",
params);
// Check your log cat for JSON reponse
Log.d("All Authors: ", 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_BOOKS);
// Looping through all products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each JSON item in variable
String author = c.getString(TAG_AUTHOR);
// Creating a 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_AUTHOR, author);
// Adding HashList to ArrayList
booksList.add(map);
}
} else {
// No products found
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing a background task, dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// Dismiss the dialog after getting all products
pDialog.dismiss();
// Updating UI from the background thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
SimpleAdapter adapter = new SimpleAdapter(
LoadAllActivity.this, booksList, R.layout.menu_row,
new String[] { TAG_ID, TAG_AUTHOR }, new int[] {
R.id.id, R.id.book });
// Updating listview
setListAdapter(adapter);
}
});
}
I know there is a way to update it when updating the booksList, but I tried that in many different ways, and it's quite not the simpliest way I think.
The way I'd like to solve it is just to restart the main activity, to recall this onCreate(Bundle ...) method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
booksList = new ArrayList<HashMap<String, String>>();
// Loading products in the background thread
new LoadAllBooks().execute();
// Get listview
ListView lv = getListView();
// On seleting single product
// Launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id) {
String author = ((TextView) view.findViewById(R.id.book))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
AuthorTitlesActivity.class);
// Sending pid to next activity
in.putExtra(TAG_AUTHOR, author);
// Starting a new activity and expecting some response back.
startActivityForResult(in, 100);
}
});
}
Is there a way to realize this solution?

implementing the Endless Adapter

I get the entire data from the Server by using doInBackground() method as shown below.
class DataLoader extends Activity{
public void onCreate()
{
...............................
new AsyncTask1().execute();
}
class AsyncTask1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(DataLoader.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
protected String doInBackground(String... args) {
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1",datafield1));
params.add(new BasicNameValuePair("param2",datafield2));
json = jsonParser.makeHttpRequest(url, "POST", params);
try {
int success = json.getInt(SUCCESS);
if (success == 1) {
products = json.getJSONArray(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(ID);
String price = c.getString(PRICE);
String name = c.getString(NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(PID, id);
map.put(PRICE, price);
map.put(NAME, name);
..................
// adding HashList to ArrayList
productsList.add(map);
}
return "success";
}
else {
// no materials found for this section
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String msg) {
if( msg != null && msg.equals("success"))
{
progressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
customadapter=new CustomAdapterList(DataLoader.this, productsList);
listView.setAdapter(adapter);
}
});
}
}
}
As per the above code, I am setting the data to the listview in the onPostExecute() method only after the entire data is loaded. But now I want to implement the CW Endless Adapter with the present code, but as I am new to this, I am unable to get how to move on from here. I included the CWAdapter jar file in the libs folder. Have referred this and searched a lot , but no use. Can some one please help me implementing the endless feature for the data I get?
Basic Idea is to run an AsyncTask when more data is required, that is when uses scrolls to bottom of the list. Here's a quick demo project.

Categories

Resources