I am using lazy loading in my app, I want to show the loading animation or progress bar or anything till the content loads from remote server just to tell the user that the page is not blank or under construction. Here is my activity, plz tell me the solution to make user wait till content loads.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotel_listview);
// URL to the XML data
String strUrl = "http://xxx.php";
// Creating a new non-ui thread task to download xml data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
if (!isOnline(this)) {
showDialog(DIALOG_ERROR_CONNECTION); //displaying the created dialog.
} else {
//Internet available. Do what's required when internet is available.
}
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected())
return true;
else
return false;
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_ERROR_CONNECTION:
AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
errorDialog.setTitle("Error");
errorDialog.setMessage("Connection Error....!");
errorDialog.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog errorAlert = errorDialog.create();
return errorAlert;
default:
break;
}
return dialog;
}
/** A method to download xml data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download xml data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
// The parsing of xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}}
}
/** AsyncTask to parse xml data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
StringReader reader;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strXml) {
try{
reader = new StringReader(strXml[0]);
}catch(Exception e){
Log.d("XML Exception1",e.toString());
}
// Instantiating xml parser class
HotelListParser hotelListParser = new HotelListParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> hotelList = null;
try{
// Getting the parsed data as a List construct
hotelList = hotelListParser.parse(reader);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "hotel","photo","rupees","review","distance"};
// Ids of views in listview_layout
int[] to = { R.id.tv_hotelName,R.id.iv_photo,R.id.tv_rupees,R.id.tv_review,R.id.tv_distance};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), hotelList, R.layout.hotel_listview_layout, from, to);
return adapter;
}
/** Invoked by the Android when "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("photo_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("photo_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("photo_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("photo",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
if (result != null) {
// Getting the path to the downloaded image
String path = (String) result.get("photo");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("photo",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
`
Progress Dialog method to show and hide. Or you can write code in onPreExecute() to show and onPostExecute() to hide the progress dialog.
ProgressDialog barProgressDialog;
public void showHideProgressDialog(boolean status){
if(barProgressDialog==null){
barProgressDialog = new ProgressDialog(YourActivity.this);
barProgressDialog.setTitle("Title");
barProgressDialog.setMessage("Your Message");
}
if(status){
barProgressDialog.show();
}else{
barProgressDialog.dismiss();
}
}
AsyncTask methods.
public void onPreExecute(...){
showHideProgressDialog(true)
..
}
public void onPostExecute(...){
showHideProgressDialog(false)
...
}
Suggestion : Do http stuff only when device has a data connection
.....
DownloadTask downloadTask = new DownloadTask();
// dont call http stuff here
//downloadTask.execute(strUrl);
if (!isOnline(this)) {
showDialog(DIALOG_ERROR_CONNECTION); //displaying the created dialog.
} else {
//Internet available. Do what's required when internet is available.
downloadTask.execute(strUrl);
}
....
Related
I am using following code from a tutorial , code works great but the app force closes if there is no connection or incase of slow connection.
public class MainActivity extends Activity {
ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the XML data
String strUrl = "http://wptrafficanalyzer.in/p/demo1/countries_xml.php/countries/";
// Creating a new non-ui thread task to download xml data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
}
/** A method to download xml data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download xml data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse xml data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
StringReader reader;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strXml) {
try{
reader = new StringReader(strXml[0]);
}catch(Exception e){
Log.d("XML Exception1",e.toString());
}
// Instantiating xml parser class
CountryXmlParser countryXmlParser = new CountryXmlParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = countryXmlParser.parse(reader);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "country","flag","details"};
// Ids of views in listview_layout
int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
/** Invoked by the Android when "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
}
You're returning null if an exception is thrown during doInBackground(), but then you're accessing result in onPostExecute() and not handling the null case. You need to verify that result is not null before you try to access it. Like so:
#Override
protected void onPostExecute(HashMap<String, Object> result) {
if (result != null) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
You will have to check if your application has internet access, before making calls that require it.
Following methods check if you have internet access. Use it before you need to do internet calls. If it returns false, show the user a notification saying that internet is required.
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
Also, add these permissions if you haven't already:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Use it like this
if (isInternetAvailable() {
// available network
} else {
// no network
}
I've a custom list in Android that collects data using Json.Sometimes correctly load the app list and the other is closed. The error in logcat is:
https://www.dropbox.com/s/yywp1aa6vlc66y4/error_list.png
And my code is:
public class Lista_productos extends Activity{
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_producto);
// URL to the JSON data
int section = 1;
String strUrl = "http://server/file.php?valor="+section;
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.listaJson);
Button Buttonback = (Button) findViewById(R.id.back);
Buttonback.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
private ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Lista_productos.this, "", "Cargando...", true);
}
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
dialog.dismiss();
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
JSONParser DealJsonParser = new JSONParser();
DealJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
JSONParser DealJsonParser = new JSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> deal = null;
try{
// Getting the parsed data as a List construct
deal = DealJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "flag","details","precionuevo","descripcion","total","codeqr","latitud","longitud","unidades","telefono"};
// Ids of views in listview_layout
int[] to = { R.id.dealimage,R.id.details,R.id.price,R.id.descripcion,R.id.total,R.id.codeqr,R.id.latitud,R.id.longitud,R.id.unidades,R.id.telefono};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), deal, R.layout.list_view, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View view, int position, long id) {
// TODO Auto-generated method stub
String URL = ((TextView) view.findViewById(R.id.descripcion)).getText().toString();//this will take the value of the invincible textView
ImageView imageview = (ImageView) view.findViewById(R.id.dealimage);
imageview.buildDrawingCache();
Bitmap bmap = imageview.getDrawingCache();
Intent i = new Intent(Lista_productos.this, pruebalista.class);
Bundle extras = new Bundle();
// extras.putParcelable("imagebitmap", image);
i.putExtra("BitmapImage", bmap);
i.putExtras(extras);
i.putExtra("URL", URL);
startActivity(i);
}
});
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
}
}
Does anyone have any idea to solve this? Thanks!
Try this..
I Guess You need to initialize the listview before calling the DownloadTask
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.listaJson);
Button Buttonback = (Button) findViewById(R.id.back);
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
Same like that you no need to create OnItemClickListener inside Asynctask
mListView.setOnItemClickListener(new OnItemClickListener() {
You need to do it inside OnCreate
I have a list and I would like to add a 'header'.
I've tried this tutorial and my code final is :
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_producto);
// URL to the JSON data
String strUrl = "http://server/file.php";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.listaJson);
View header = getLayoutInflater().inflate(R.layout.header, null);
mListView.addHeaderView(header);
/*View header = (View)getLayoutInflater().inflate(R.layout.header, null);
mListView.addHeaderView(header);*/
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
JSONParser DealJsonParser = new JSONParser();
DealJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
JSONParser DealJsonParser = new JSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> deal = null;
try{
// Getting the parsed data as a List construct
deal = DealJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "nombre","flag","details","precionuevo","descripcion",};
// Ids of views in listview_layout
int[] to = { R.id.price,R.id.dealimage,R.id.details,R.id.price,R.id.descripcion};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), deal, R.layout.list_view, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
/* AÑADIR HEADER?
View header = getLayoutInflater().inflate(R.layout.header, null);
mListView.addHeaderView(header);
*/
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// TODO Auto-generated method stub
String URL = ((TextView) view.findViewById(R.id.descripcion)).getText().toString();//this will take the value of the invincible textView
Intent i = new Intent(Lista_productos.this, pruebalista.class);
i.putExtra("URL", URL);
startActivity(i);
}
});
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
/*Toast toast = Toast.makeText(Lista_productos.this, path, Toast.LENGTH_LONG);
toast.show();*/
}
}
}
When you run the application prints the list and the header but after 6 seconds, the app quits unexpectedly showing errors in logcat:
https://www.dropbox.com/s/uj1a3zj64wrtzfy/error3.png
public class TopMovie extends Activity
{
GridView lv;
Vibrator vibrator;
private Object params;
public static String movie_Id;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.i("Category", MainActivity.movie_Category);
setContentView(R.layout.new_movie);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
lv = (GridView) findViewById(R.id.grid_view);
// URL to the JSON data
String strUrl = "http://vaibhavtech.com/work/android/movie_list.php?category="
+ MainActivity.movie_Category + "&sub_category=other";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// // TODO Auto-generated method stub
vibrator.vibrate(40);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
MainActivity.movie_Id = ((TextView) arg1
.findViewById(R.id.tv_girdview_content_id)).getText()
.toString();
Log.i("Name is", MainActivity.movie_Id);
startActivity(new Intent(TopMovie.this, MovieDescription.class));
}
});
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends
AsyncTask<String, Void, SimpleAdapter> {
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
MovieParser countryJsonParser = new MovieParser();
countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
// Instantiating json parser class
MovieParser countryJsonParser = new MovieParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try {
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
// Keys used in Hashmap
String[] from = { "image", "id", "year", "duration", "name" };
// Ids of views in listview_layout
// int[] to = {
// R.id.iv_radio_data_image,R.id.tv_radio_data_id,R.id.tv_radio_data_like,R.id.tv_radio_data_rating,R.id.tv_radio_data_listner,R.id.tv_radio_data_radio_url,R.id.tv_radio_data_name};
int[] to = { R.id.iv_girdview_content_image,
R.id.tv_girdview_content_id, R.id.tv_girdview_content_like,
R.id.tv_girdview_content_listner,
R.id.tv_girdview_content_name };
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
countries, R.layout.grid_view_content, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
lv.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path", imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in
// the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends
AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
#Override
protected HashMap<String, Object> doInBackground(
HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position
// in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("image", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path and
// position
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("image");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter) lv.getAdapter();
// Getting the hashmap object at the specified position of the
// listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(position);
// Overwriting the existing path in the adapter
hm.put("image", path);
adapter.notifyDataSetChanged();
}
}
}
My application is debugging but not running.RejectedExecutionException: Task android.os.AsyncTas rejected from java.util.concurrent.
Submitting tasks to a thread-pool gives RejectedExecutionException
how to resolve threadpool exception in gridview android
You can change the executor the asynctask uses if you extend the asynctask class.
Check this example from docs where they download multiple images and use a custom asynctask to control the concurrency.
I had the same problem you are having and used that project to fix it.
public class TopMovie extends Activity
{
GridView lv;
Vibrator vibrator;
Dialog dialog;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Log.i("Category", MainActivity.movie_Category);`enter code here`
setContentView(R.layout.new_movie);
setProgressBarIndeterminateVisibility(true);
setProgressBarIndeterminateVisibility(false);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
lv = (GridView) findViewById(R.id.grid_view);
// URL to the JSON data
String strUrl = "http://vaibhavtech.com/work/android/movie_list.php?category="
+ MainActivity.movie_Category + "&sub_category=other";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// // TODO Auto-generated method stub
vibrator.vibrate(40);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
MainActivity.movie_Id = ((TextView) arg1
.findViewById(R.id.tv_girdview_content_id)).getText()
.toString();
Log.i("Name is", MainActivity.movie_Id);
startActivity(new Intent(TopMovie.this, MovieDescription.class));
}
});
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return data;
}
protected void onPreExecute() {
// SHOW THE SPINNER WHILE LOADING FEEDS
// linlaHeaderProgress.setVisibility(View.VISIBLE);
//super.onPreExecute();
dialog=dialog=ProgressDialog.show(TopMovie.this,"", "Loading...", true);
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends
AsyncTask<String, Void, SimpleAdapter> {
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
MovieParser countryJsonParser = new MovieParser();
countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
// Instantiating json parser class
MovieParser countryJsonParser = new MovieParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try {
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
// Keys used in Hashmap
String[] from = { "image", "id", "year", "duration", "name" };
// Ids of views in listview_layout
// int[] to = {
// R.id.iv_radio_data_image,R.id.tv_radio_data_id,R.id.tv_radio_data_like,R.id.tv_radio_data_rating,R.id.tv_radio_data_listner,R.id.tv_radio_data_radio_url,R.id.tv_radio_data_name};
int[] to = { R.id.iv_girdview_content_image,
R.id.tv_girdview_content_id, R.id.tv_girdview_content_like,
R.id.tv_girdview_content_listner,
R.id.tv_girdview_content_name };
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
countries, R.layout.grid_view_content, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
lv.setAdapter(adapter);
// Setting adapter for the listview
if(dialog!=null)
dialog.dismiss();
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path", imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in
// the listview
imageLoaderTask.execute(hm);
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends
AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
#Override
protected HashMap<String, Object> doInBackground(
HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position
// in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("image", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path and
// position
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("image");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter) lv.getAdapter();
// Getting the hashmap object at the specified position of the
// listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(position);
// Overwriting the existing path in the adapter
hm.put("image", path);
adapter.notifyDataSetChanged();
}
}
}}
i have a gridview in which items coming from json..,sometime my applications runs but sometime gives REJECTED EXECUTION EXECPTION at " imageLoaderTask.execute(hm);",i am unable to understand how to resolve this problem.i have tried all examples and condiotions.i have used asynchtask ,custom adapetr in my code ,but no solution and answer is ocured in my code.,how can i resolve my error.please help me...:(
First you have to understand what RejectedExecutionException means. Then decide how do you want to handle it.
AsyncTask runs its tasks in an Executor. This executor uses a queue where the tasks are stored until the executor is free to pay attention to them. The default executor with a default task can handle 10 tasks at the same time and store 10 additional tasks to perform once the running ones complete. Once the spot for all these 20 tasks (10+10) it can't take any more tasks, and it lets you know by raising a RejectedExecutionException.
How can you deal with this? Depends on what you need. You can catch that exception and try again later to see if the queue has room later, or you could use a differently configured executor that (a) can perform more tasks at the same time or (b) that has a queue with more space for tasks. Some already existing executor classes can be configured with parameters more appropriate for your needs (see the documentation for Executor) or you can write your own. One such executor is ThreadPoolExecutor that you can tell what kind of queue to use (this is the executor that is used in some of the Android versions, you don't specify which version you're working with). In the documentation there's discussion about what kinds of queues there are.
Again, the decision on how to configure the executor and queue is up to you and your needs. Such as if you want to allow for unbounded creation of threads, or have a limit. Want to have a long queue of tasks or short, or even unbound.
Try this..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
imageLoaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, hm);
else
imageLoaderTask.execute(hm);
For all AsyncTask