I understand that we cannot set ImageView in AsyncTask. But I need to add the ImageView into HashMap and the HashMap need to add into an ArrayList inside the for loop. I cannot do that in onPostExecute(). Does anyone know how to do?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
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://192.168.1.132/retEqp.php";
ImageView iv;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "equipments";
private static final String TAG_PID = "item_ID";
private static final String TAG_NAME = "item_Name";
private static final String TAG_DESC = "item_Desc";
private static final String TAG_LOC = "item_Location";
private static final String TAG_STATUS = "item_Status";
private static final String TAG_IMAGE = "item_Image";
// products JSONArray
JSONArray equipments = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
iv = (ImageView)findViewById(R.id.img2);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().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 position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent previousScreen = new Intent(getApplicationContext(), NewProductActivity.class);
//Sending the data to NewProductActivity
previousScreen.putExtra("id",pid);
setResult(1000, previousScreen);
finish();
// starting new activity and expecting some response back
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* 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 {
equipments = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < equipments.length(); i++) {
JSONObject c = equipments.getJSONObject(i);
// Storing each json item in variable
String id = "ID: "+c.getString(TAG_PID);
String name = "Name: "+c.getString(TAG_NAME);
String desc = "Description: "+c.getString(TAG_DESC);
String loc = "Location: "+c.getString(TAG_LOC);
String status = "Status: "+c.getString(TAG_STATUS);
String image = c.getString(TAG_IMAGE);
byte[] rawImage = Base64.decode(image, Base64.DEFAULT);
Bitmap bmp12 = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
iv.setImageBitmap(bmp12);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_IMAGE, rawImage.length);
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESC, desc);
map.put(TAG_LOC, loc);
map.put(TAG_STATUS, status);
map.put(TAG_IMAGE, iv.toString());
// 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_IMAGE,TAG_PID,
TAG_NAME,TAG_DESC,TAG_LOC,TAG_STATUS},
new int[] {R.id.img,R.id.pid, R.id.name,R.id.desc,R.id.loc,R.id.status});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can't access the UI in a background thread.
The idea behind AsyncTask is that doInBackground does the background work, then you can return something that will be passed as a parameter to onPostExecute which is executed in the main thread.
In this case you have to return the parsed model objects from doInBackground (I would create a custom class), receive in onPostExecute. Also, create a custom adapter, which will take care of creating views. You should generate bitmaps there (probably you have to put the parsing to bitmap in another async task).
Related
Ok i've written this android program that has 3 tabs(MEALS,DRINKS AND DESSERT) each in its own activity with a fragment.The problem i'm having now is with retrieving the list from a mysql database and displaying this list in each tab.I'de already ran and executed a custom code which displays a list of items retrieved from a mysql database in a single list,which worked fine.Now bringing this code to my program gives me 3 errors
1)
pDialog = new ProgressDialog(MealsFragment.this); which says
ProgressDialog(android.context,Context) in progressDialog cannot be applied to
com.example.tab.tablayout.MealsFragment
2)
runOnUiThread(new Runnable() which says "cannot resolve method runonuithread "
3)is all about the list adapter.
The initial code used OnCreate,but my fragment uses oncreateView.I dont know if thats the issue.
Here is the code for the MealsFragment.java
package com.example.tabs.tablayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
/**
* Created by GIGABYTE on 5/21/2014.
*/
public class MealsFragment extends ListFragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> mealsList;
// url to get all products list
private static String url_all_meals = "http://10.180.79.73/dbase_connect/get_all_meals.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MEALS = "meals";
private static final String TAG_MID = "mid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray meals = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_meals, container, false);
// Hashmap for ListView
mealsList = new ArrayList<HashMap<String, String>>();
// Loading meals in Background Thread
new LoadAllMeals().execute();
// Get listview
ListView lv = getListView();
return rootView;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllMeals extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MealsFragment.this);
pDialog.setMessage("Loading Meals. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All Meals 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_meals, "GET", params);
// Check your log cat for JSON response
Log.d("All Meals: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Meals found
// Getting Array of Meals
meals = json.getJSONArray(TAG_MEALS);
// looping through All meals
for (int i = 0; i < meals.length(); i++) {
JSONObject c = meals.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_MID);
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_MID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
mealsList.add(map);
}
} /*else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.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 meals
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MealsFragment.this, mealsList,
R.layout.meals_list_item, new String[] {TAG_MID,
TAG_NAME},
new int[] { R.id.mid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
1) The first parameter of the ProgressDialog constructor must be a context. Use
new ProgressDialog(getActivity());
2) You could use getActivity().runOnUiThread(...). However, that's not necessary in this context. The AsyncTask.onPostExecute() method is already running in the UI thread. Just move the Runnable code into the body of the onPostExecute() method.
3) Same as 1, first parameter must be a context. Use new SimpleAdapter(getActivity(), ...).
i'm trying to build android app which has tab layout which also has listfragment. i want total of three tabs, first home, second listview and third when clicked on listview it switches to third tabs and show some information all using json parsing.
i'm using this tutorials as a reference http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
and for listview i'm using following - http://www.androidhive.info/2012/10/android-multilevel-listview-tutorial/
Now the question is that how can i change listActivity to listFragment?
How can i turn this code from Listactivity to Listfragment?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.androidhive.helper.AlertDialogManager;
import com.example.androidhive.helper.ConnectionDetector;
import com.example.androidhive.helper.JSONParser;
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 = "http://api.androidhive.info/songs/albums.php";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
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 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_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_SONGS_COUNT }, new int[] {
R.id.album_id, R.id.album_name, R.id.songs_count });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
please could you help me to found what is the problem with the following code !
when the item from spinner selected nothing occurs
i.e : the body of spinner.setOnItemSelectedListener is not seen !
code :
package com.example.spinner;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import java.util.HashMap;
import org.apache.http.NameValuePair;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
public class MainActivity extends Activity {
// 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/RPM-connect/get_all_patients.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DOCTOR = "products";
private static final String TAG_ID = "id";
private static final String TAG_F_NAME = "F_name";
private static final String TAG_S_NAME = "S_name";
private static final String TAG_L_NAME = "L_name";
// products JSONArray
JSONArray doctor = null;
ArrayList<String> spinnerArray ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
spinnerArray = new ArrayList<String>();
// Loading products in Background Thread
new LoadAllProducts().execute();
Spinner spinner = new Spinner(this);
//ArrayAdapter <HashMap<String, String>> spinnerArrayAdapter = new ArrayAdapter<HashMap<String, String>>(
ArrayAdapter <String> spinnerArrayAdapter = new ArrayAdapter <String >(
this, android.R.layout.simple_spinner_item, spinnerArray );
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
spinner = (Spinner) findViewById( R.id.spinner1 );
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "You have selected : " ,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} );
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
#SuppressLint("NewApi")
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 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
doctor = json.getJSONArray(TAG_DOCTOR);
// looping through All Products
for (int i = 0; i < doctor.length(); i++) {
JSONObject c = doctor.getJSONObject(i);
// Storing each json item in variable
String ID = c.getString(TAG_ID);
String F_name = c.getString(TAG_F_NAME);
String S_name = c.getString(TAG_S_NAME);
String L_name = c.getString(TAG_L_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_F_NAME, F_name);
map.put(TAG_S_NAME, S_name);
map.put(TAG_L_NAME, L_name);
// adding HashList to ArrayList
productsList.add(map);
Log.d("Before temp", productsList.toString());
spinnerArray.add(F_name + " " + L_name);
// temp[i]= F_name+" "+L_name ;
Log.d("TT",spinnerArray.get(i) );
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
Your ArrayList may not be populated from the AsyncTask before you set the adapter. Implement onPostExecute() in your AsyncTask and call notifyDataSetChanged() on your adapter there. Also, you create a new Spinner then use one that exists in your xml
Spinner spinner = new Spinner(this);
this is not needed. Just declare your Spinner like this
public class MainActivity extends Activity {
Spinner spinner;
then initialize it from xml as you are doing later
spinner = (Spinner) findViewById( R.id.spinner1 );
notifyDataSetChanged() Docs
After your done with loading the items into the SpinnerAdapter inside your AsyncTask you need to tell the Adapter to refresh itself to load the new values.
This can be done by calling: spinnerArrayAdapter.notifyDataSetChanged().
Because the AsyncTask is running on another thread, you will need to implement
#Override
public void onPostExecute(String result) {
spinnerArrayAdapter.notifyDataSetChanged()
}
and call the spinnerArrayAdapter.notifyDataSetChanged() inside it, as seen above.
onPostExecute and onPreExecute is run on the main thread, so they can change Views on the UI thread.
As if combining checkbox and listview wasn't difficult enough. I've faced this stupid problem: " my list items are suppose to be downloaded from an HTTP request (done) but I don't know now where I should put the checkbox on the code so each list item has its own checkbox and how can I memorize each item was cheacked ". The following are the used code for the HTTP request:
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
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://10.0.2.2:8080/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PID= "name";
private static final String TAG_CATEGORY = "category";
/*private static final String TAG_UNIT = "unit";
private static final String TAG_CALORY = "calory";
private static final String TAG_CARBOHYDRATE = "carbohydrate";
private static final String TAG_CATEGORY = "category";*/
// the array was defined in PHP file
private static final String TAG_PRODUCT = "product";
// 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();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
Log.d("NUN complete","tyt");
}
}
/**
* 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 items. 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 {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
Log.d("All Products: ", json.toString());
products = json.getJSONArray(TAG_PRODUCT);
// 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); // also name
String category = c.getString(TAG_CATEGORY );
// NO NEED FOR THEM !!
/*
String unit = c.getString(TAG_UNIT );
String category = c.getString(TAG_CATEGORY );
String calory = c.getString(TAG_CALORY );
String carbohydrate = c.getString(TAG_CARBOHYDRATE ); */
// 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_CATEGORY, category);
//map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
Log.d("All Products: ", json.toString());
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.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_CATEGORY},
new int[] { R.id.pid, R.id.category});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can create a custom adapter, where you put all items you got from your HTTP request. and a checkbox per each item, you can use BaseAdapter instead of SimpleAdapter.
Create an xml with the TextView that you are using to display the products and a CheckBox then it will be generated for every item in your list. Just be sure to use a ListView with theandroid:id`
<ListView
android:id=#android:id/list
.../>
or you will get an error.
Also, you shouldn't need runOnUiThread() in onPostExecute() as it already runs on the UI thread
my asynctask is not working. The dialog wont dismiss and the list is not being updated (i think because onPostExecute is not being called).I googled it, but without result.
package com.example.whs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class Albums extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// Array for the list
ArrayList<HashMap<String, String>> itemList;
// url to get the items
private static String url_all_products = "<my url here>";
// JSON variables
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ITEMS = "items";
private static final String TAG_NAME = "name";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
//JSON array
JSONArray items = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
// HashMap for the items
itemList = new ArrayList<HashMap<String, String>>();
// Loading the items on the background
new LoadAllItems().execute();
// Get list-view
ListView lv = getListView();
// On item click
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//do
}
});
}
// class for loading all items
class LoadAllItems extends AsyncTask<String, String, String> {
// Before
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(Albums.this);
pDialog.setMessage("Albums laden...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Get the products
#Override
protected String doInBackground(String... params) {
// Build Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
//Get the JSON string
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params1);
// Check for response
Log.d("All Items: ", json.toString());
try {
// check for success tag
int success = json.getInt(TAG_SUCCESS);
if(success == 1) {
// found the items
items = json.getJSONArray(TAG_ITEMS);
// loop through the items
for (int i = 0; items.length() > i; i++){
// Get the item in variable c
JSONObject c = items.getJSONObject(i);
// Store in a variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String username = c.getString(TAG_USERNAME);
if(username == ""){
username = "onbekend";
}
// Create the HashMap
HashMap<String, String> map = new HashMap<String, String>();
// add it
map.put(TAG_ID, id);
map.put(TAG_USERNAME, username);
map.put(TAG_NAME, name);
// to arraylist
itemList.add(map);
}
}else{
// nothing found
Intent i = new Intent(getApplicationContext(), Index.class);
// close the previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result){
// dismiss dialog
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
// Add adapter to the list
MenuAdapter adapter = new MenuAdapter(Albums.this, itemList);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.albums, menu);
return true;
}
}
the loop is working correctly.
How to fix this?
1) you are trying to start an activity within the background thread, don't do this.
2) you are probably getting a json exception, just log more things so you can see what is happening
these may be why it never reaches onPostExecute
you can not perform UI related action in doInBackGround(), like you are strating a new activity in doInBaclground,
Intent i = new Intent(getApplicationContext(), Index.class);
// close the previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);