I have made an activity in that I am making an api call by using AsyncTak,I have shown a progressDialog In DoBackground method ,and want to dismiss that progressDialog in postExecute i have done this way but its not working,My progressDialog remains, open after the operations too..My code is as below,can anybuddy help me to dissmiss it.
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint.Join;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.backend.FavoriteAPI;
import com.epe.yehki.backend.ResponseListener;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Const.API_RESULT;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class WholesaleProductDetailActivity extends Activity {
public ImageView productImage;
private ImageLoader imageLoader;
private DisplayImageOptions options;
private ProgressDialog pDialog;
JSONArray proDetails = null;
private Menu menu;
Intent i1;
private FavoriteAPI favApi;
private int isFavourite;
private ProgressDialog progressDialog;
// CONTROLLS FOR WHOLESALE RETAILS.........!!!
TextView retailPrice;
TextView tv_moqW;
TextView tv_moqR;
TextView tv_shipping_cost;
TextView EscrowPayment;
TextView ProcessigPeriod;
LinearLayout llQuantity;
EditText quantity;
LinearLayout llbotm;
TextView tv_escrow_payment;
TextView tv_procesiing_period;
Button contactSuplier, addToCart, buyNOw;
LinearLayout ll_botom1;
// ************************
// strings.......!!!
String pro_id;
String name;
String retail_price;
String price_wholesale;
String keywords;
String supplier_id;
String supplier_name;
String listing_description;
String image;
String Specifications;
String date_added;
String status;
int flag = 0;
String port;
String customer_name;
String customer_id;
String cId;
String min_order_qty_retail;
String min_order_qty_wholesale;
String countyId;
String supply_amount;
String msg;
String supply_unit_id;
String supply_unit_name;
String supply_time;
String payment_terms;
String min_order_qty;
String min_order_qty_unit;
String min_order_qty_unit_name;
String delivery_time;
String company_name;
String country_id;
String state_id;
String procesPeriod;
// COMPANY DETAILS....
String companyDetail;
String companyDetailName;
String companyDetailAddress;
String companyDetailPhoto;
String companyDetailMainProduct;
String companyDetailotherProduct;
String cartNo;
// PRODUCT QUICK DETAILS...
// TextViews.............!!!
public TextView productName;
public TextView wholeSalePrice;
public TextView minOrder;
public TextView shippingCost;
public TextView escrowPayment;
public TextView processingPeriod;
public TextView compnyName;
public TextView countryName;
public TextView bussinessType;
public TextView mainProduct;
public TextView productDetails;
public String pid;
// Buttons of placeOrder and contact supplier..
private Button contactSupplier;
private ImageView iv_back;
private TextView cart;
private ImageView iv_fav;
public Intent i;
//
// Hashmap for ListView
ArrayList<HashMap<String, String>> ProductDetailList;
// URL to get contacts JSON
// API_PRODUCT?product_id=29
private static String productUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
initializeViews();
cId = Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "");
ll_botom1 = (LinearLayout) findViewById(R.id.ll_botom1);
ll_botom1.setVisibility(View.VISIBLE);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(WholesaleProductDetailActivity.this));
options = new DisplayImageOptions.Builder().cacheOnDisc(true).showImageOnFail(R.drawable.logo).build();
new AddToCart().execute();
// get extras..............!!!!
i = getIntent();
i.getStringExtra(Const.TAG_PRODUCT_NAME);
i.getStringExtra(Const.TAG_PRODUCT_IMG);
pid = i.getStringExtra(Const.TAG_PRODUCT_ID);
favApi = new FavoriteAPI(WholesaleProductDetailActivity.this, responseListener, pid, Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, ""));
favApi.callApi();
// bACK BUTTON.......!
iv_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
// DO FAVOURITE YOUR PRODUCT..........!!!
iv_fav.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// CHECKING IS USER lOGIN...!
if (Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "") != null
&& !Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "").equals("")) {
// FAVOURITE API CALL..........!!!
if (iv_fav.isSelected()) {
isFavourite = 0;
iv_fav.setImageResource(R.drawable.star);
iv_fav.setSelected(false);
} else {
isFavourite = 1;
iv_fav.setImageResource(R.drawable.star_filled);
iv_fav.setSelected(true);
}
if (Utils.isOnline(WholesaleProductDetailActivity.this)) {
progressDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
progressDialog.setMessage(getString(R.string.process_progress_msg));
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
favApi = new FavoriteAPI(WholesaleProductDetailActivity.this, responseListener, pid, Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, ""));
favApi.callApi();
} else {
Toast.makeText(WholesaleProductDetailActivity.this, "Please check your interenet connection", Toast.LENGTH_SHORT).show();
}
} else {
i = new Intent(WholesaleProductDetailActivity.this, LoginActivity.class);
startActivity(i);
}
}
});
productUrl = Const.API_WHOLESALE_PRODUCT_DETAIL + "?" + Const.TAG_PRODUCT_ID + "=" + pid;
System.out.println(":::::::::::PRODUCT URL:::::::::::::::" + productUrl);
productName.setText(i.getStringExtra(Const.TAG_PRODUCT_NAME));
try {
imageLoader.displayImage(i.getStringExtra(Const.TAG_PRODUCT_IMG), productImage, options);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
productImage.setBackgroundResource(R.drawable.logo);
}
new GetProductDetails().execute();
buyNOw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (quantity.getText().toString() != null && !quantity.getText().toString().equals("")) {
if (Double.parseDouble(quantity.getText().toString()) < (Double.parseDouble(min_order_qty_retail))) {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please Enter Quantity greater than min. retail quamtity", "Yehki", "Ok");
} else {
i1 = new Intent(WholesaleProductDetailActivity.this, WholesalePlaceOrderActivity.class);
i1.putExtra(Const.TAG_PRODUCT_NAME, name);
i1.putExtra(Const.TAG_PRODUCT_ID, pid);
i1.putExtra("QTY_RETAIL", min_order_qty_retail);
i1.putExtra("QTY_WHOLESALE", min_order_qty_wholesale);
i1.putExtra(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID, supply_unit_id);
i1.putExtra(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME, supply_unit_name);
i1.putExtra(Const.TAG_PRODUCT_MAX_PRICE, price_wholesale);
i1.putExtra(Const.TAG_PRODUCT_MIN_PRICE, retail_price);
i1.putExtra("takenQTY", quantity.getText().toString());
if (Double.parseDouble(quantity.getText().toString()) > (Double.parseDouble(min_order_qty_retail))
&& Double.parseDouble(quantity.getText().toString()) < (Double.parseDouble(min_order_qty_wholesale))) {
i1.putExtra("price", retail_price);
startActivity(i1);
} else if (Double.parseDouble(quantity.getText().toString()) > (Double.parseDouble(min_order_qty_wholesale))) {
i1.putExtra("price", price_wholesale);
startActivity(i1);
}
}
} else {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please Enter Quantity", "Yehki", "Ok");
}
}
});
contactSuplier.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(WholesaleProductDetailActivity.this, ContactSupplierActivity.class);
i.putExtra(Const.TAG_SUPPLIER_ID, supplier_id);
System.out.println("::::::::::::::::;my supplier id>>>>>>>>>>>>>>+++++++++++++++++" + supplier_id);
i.putExtra(Const.TAG_PRODUCT_ID, pid);
startActivity(i);
}
});
addToCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!quantity.getText().toString().equals("") && quantity.getText().toString() != null) {
new AddToCart().execute();
} else {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please enter quanitity", "Yehki", "Ok");
}
}
});
}
// ****INITIALIZING THE VIEWS.....!!!!!!!!!!!!!!!
private void initializeViews() {
productImage = (ImageView) findViewById(R.id.iv_product);
productName = (TextView) findViewById(R.id.tv_product_name);
buyNOw = (Button) findViewById(R.id.tv_place_order);
contactSupplier = (Button) findViewById(R.id.tv_contact_suplier);
wholeSalePrice = (TextView) findViewById(R.id.tv_price_range);
minOrder = (TextView) findViewById(R.id.tv_min_order);
shippingCost = (TextView) findViewById(R.id.tv_sply);
escrowPayment = (TextView) findViewById(R.id.tv_payment_terms);
processingPeriod = (TextView) findViewById(R.id.tv_port);
compnyName = (TextView) findViewById(R.id.tv_company_name);
countryName = (TextView) findViewById(R.id.tv_contry);
bussinessType = (TextView) findViewById(R.id.tv_bussiness_type);
mainProduct = (TextView) findViewById(R.id.tv_main_products);
productDetails = (TextView) findViewById(R.id.tv_pro_detail);
menu = (Menu) findViewById(R.id.menuProduct);
iv_back = (ImageView) findViewById(R.id.iv_back);
iv_fav = (ImageView) findViewById(R.id.iv_fvrt);
cart = (TextView) findViewById(R.id.tv_cart);
retailPrice = (TextView) findViewById(R.id.tv_retail_price);
tv_moqW = (TextView) findViewById(R.id.tv_moqw);
tv_moqR = (TextView) findViewById(R.id.tv_min_order);
tv_shipping_cost = (TextView) findViewById(R.id.tv_shipping_cost);
tv_escrow_payment = (TextView) findViewById(R.id.tv_escrow_payment);
tv_procesiing_period = (TextView) findViewById(R.id.tv_procesiing_period);
quantity = (EditText) findViewById(R.id.et_qty);
llQuantity = (LinearLayout) findViewById(R.id.ll_btm);
llQuantity.setVisibility(View.VISIBLE);
llbotm = (LinearLayout) findViewById(R.id.ll_botom1);
llbotm.setVisibility(View.VISIBLE);
tv_shipping_cost.setText("Shipping Cost:");
tv_escrow_payment.setText("Escrow Payment:");
tv_procesiing_period.setText("Processing Period:");
contactSuplier = (Button) findViewById(R.id.tv_contc_sup);
addToCart = (Button) findViewById(R.id.btn_add_cart);
buyNOw = (Button) findViewById(R.id.btn_buy);
retailPrice.setVisibility(View.VISIBLE);
menu.setSelectedTab(1);
}
private class GetProductDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
System.out.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(productUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
// yes
proDetails = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
System.out.println("==========inside doIn background===================");
// looping through All Contacts
for (int i = 0; i < proDetails.length(); i++) {
JSONObject c = proDetails.getJSONObject(i);
name = c.getString(Const.TAG_PRODUCT_NAME);
keywords = c.getString(Const.TAG_PRODUCT_KEYWORDS);
supplier_id = c.getString(Const.TAG_PRODUCT_SUPPLIER_ID);
supplier_name = c.getString(Const.TAG_PRODUCT_SUPPLIER_NAME);
listing_description = c.getString(Const.TAG_PRODUCT_LISTING_DESCRIPTION);
image = c.getString(Const.TAG_PRODUCT_IMG);
Specifications = c.getString(Const.TAG_PRODUCT_SPECIFICATION);
date_added = c.getString(Const.TAG_PRODUCT_DATE_ADDED);
customer_name = c.getString(Const.TAG_PRODUCT_CUSTMER_NAME);
customer_id = c.getString(Const.TAG_PRODUCT_CUSTOMER_ID);
retail_price = c.getString(Const.TAG_PRICE_RETAIL);
price_wholesale = c.getString(Const.TAG_PRICE_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + price_wholesale);
min_order_qty_retail = c.getString(Const.TAG_MIN_ORDER_QTY_RETAIL);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_retail);
min_order_qty_wholesale = c.getString(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_wholesale);
countyId = c.getString(Const.TAG_COUNTRY_ID);
state_id = c.getString(Const.TAG_STATE_WHOLESALE_ID);
supply_unit_id = c.getString(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID);
supply_unit_name = c.getString(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME);
System.out.println("::::::::::::::::mY supply unit name::::::::::::::");
supply_time = c.getString(Const.TAG_PRODUCT_SUPPLY_TIME);
delivery_time = c.getString(Const.TAG_DELIVERY_TIME_WHOLESALE);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + delivery_time);
company_name = c.getString(Const.TAG_PRODUCT_COMPANY_NAME);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + company_name);
// GETTING COMPANY DETAILS..........!!!
JSONObject companyDetails = c.getJSONObject(Const.TAG_PRODUCT_COMPANY_DETAILS);
companyDetailName = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_NAME);
companyDetailAddress = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_ADDRESS);
companyDetailMainProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_MAIN_PRODUCT);
companyDetailotherProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_OTHER_PRODUCT);
companyDetailPhoto = companyDetails.getString(Const.TAG_PRODUCTDETAIL_PHOTO);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null) {
pDialog.dismiss();
}
productName.setText(name);
wholeSalePrice.setText("WholeSale Price:" + " " + price_wholesale);
retailPrice.setText("Retail Price:" + " " + retail_price);
tv_moqW.setText("MoqW:" + min_order_qty_wholesale);
minOrder.setText("MoqR:" + min_order_qty_retail);
shippingCost.setText("");
escrowPayment.setText(payment_terms);
compnyName.setText(company_name);
countryName.setText(country_id);
mainProduct.setText(companyDetailMainProduct);
processingPeriod.setText(delivery_time);
}
}
// RESPONSE lISTENER FOR THE FAVOURITE......!!
ResponseListener responseListener = new ResponseListener() {
#Override
public void onResponce(String api, API_RESULT result, Object obj) {
if (progressDialog != null) {
progressDialog.dismiss();
}
if (api.equals(Const.API_DO_FAVOURITE)) {
if (result == Const.API_RESULT.SUCCESS) {
System.out.println("::::::::::::::::;INSIDE SUCCESS ACTIVITY OF FAVORITE:::::::::;");
}
}
}
};
// *********************ADD TO CART CALL...
// *******************
private class AddToCart extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
System.out.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
String addToCArt = Const.API_ADD_TO_CART + "?customer_id=" + cId + "&product_id=" + pid + "&quantity=" + quantity.getText().toString() + "&unit_id=" + supply_unit_id; // Creating
// service
// handler
// class
// instance
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::MY add to cart url:::::::::::;" + addToCArt);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(addToCArt, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_STATUS)) {
status = jsonObj.getString(Const.TAG_STATUS);
if (status.equalsIgnoreCase("success")) {
flag = 1;
msg = jsonObj.getString(Const.TAG_MESSAGE);
cartNo = jsonObj.getString(Const.TAG_TOTAL_CART_PRODUCTS);
} else {
flag = 2;
msg = jsonObj.getString(Const.TAG_MESSAGE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null) {
pDialog.dismiss();
}
if (flag == 1) {
Toast.makeText(WholesaleProductDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
quantity.setText("");
cart.setText(cartNo);
Pref.setValue(WholesaleProductDetailActivity.this, Const.PREF_CART_NO, cartNo);
} else {
Toast.makeText(WholesaleProductDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
}
}
replace your GetProductDetails AsyncTask code with this. and do same for other
// My AsyncTask start...
class GetProductDetails extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(productUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
// yes
proDetails = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
System.out.println("==========inside doIn background===================");
// looping through All Contacts
for (int i = 0; i < proDetails.length(); i++) {
JSONObject c = proDetails.getJSONObject(i);
name = c.getString(Const.TAG_PRODUCT_NAME);
keywords = c.getString(Const.TAG_PRODUCT_KEYWORDS);
supplier_id = c.getString(Const.TAG_PRODUCT_SUPPLIER_ID);
supplier_name = c.getString(Const.TAG_PRODUCT_SUPPLIER_NAME);
listing_description = c.getString(Const.TAG_PRODUCT_LISTING_DESCRIPTION);
image = c.getString(Const.TAG_PRODUCT_IMG);
Specifications = c.getString(Const.TAG_PRODUCT_SPECIFICATION);
date_added = c.getString(Const.TAG_PRODUCT_DATE_ADDED);
customer_name = c.getString(Const.TAG_PRODUCT_CUSTMER_NAME);
customer_id = c.getString(Const.TAG_PRODUCT_CUSTOMER_ID);
retail_price = c.getString(Const.TAG_PRICE_RETAIL);
price_wholesale = c.getString(Const.TAG_PRICE_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + price_wholesale);
min_order_qty_retail = c.getString(Const.TAG_MIN_ORDER_QTY_RETAIL);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_retail);
min_order_qty_wholesale = c.getString(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_wholesale);
countyId = c.getString(Const.TAG_COUNTRY_ID);
state_id = c.getString(Const.TAG_STATE_WHOLESALE_ID);
supply_unit_id = c.getString(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID);
supply_unit_name = c.getString(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME);
System.out.println("::::::::::::::::mY supply unit name::::::::::::::");
supply_time = c.getString(Const.TAG_PRODUCT_SUPPLY_TIME);
delivery_time = c.getString(Const.TAG_DELIVERY_TIME_WHOLESALE);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + delivery_time);
company_name = c.getString(Const.TAG_PRODUCT_COMPANY_NAME);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + company_name);
// GETTING COMPANY DETAILS..........!!!
JSONObject companyDetails = c.getJSONObject(Const.TAG_PRODUCT_COMPANY_DETAILS);
companyDetailName = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_NAME);
companyDetailAddress = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_ADDRESS);
companyDetailMainProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_MAIN_PRODUCT);
companyDetailotherProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_OTHER_PRODUCT);
companyDetailPhoto = companyDetails.getString(Const.TAG_PRODUCTDETAIL_PHOTO);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
productName.setText(name);
wholeSalePrice.setText("WholeSale Price:" + " " + price_wholesale);
retailPrice.setText("Retail Price:" + " " + retail_price);
tv_moqW.setText("MoqW:" + min_order_qty_wholesale);
minOrder.setText("MoqR:" + min_order_qty_retail);
shippingCost.setText("");
escrowPayment.setText(payment_terms);
compnyName.setText(company_name);
countryName.setText(country_id);
mainProduct.setText(companyDetailMainProduct);
processingPeriod.setText(delivery_time);
// Dismiss the progress dialog
pDialog.dismiss();
}
}
}
Remove
if (pDialog.isShowing())
and
use if (pDialog != null)
may this help you
You should remove super.onPostExecute(result); as you have your implementation of onPostExecute(), so you may not want framework to handle it.
Since you have definitely showed the Progress Dialog in onPreExecute(), then you can also omit check for isShowing(), but i will recommend you to keep this check as it causes no harm and adds little more security.
In your onPostExecute() block you are calling super.onPostExecute(result);
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Your code
}
However as you are overriding the onPostExecute() there is no need to call super.onPostExecute(result);
If you take a look at the AsyncTask source, you will see that the super class does nothing:
#SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}
Related
I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}
I am trying to have a asynctask to run in the background and the other one to load something from the webservice to have a new listview.
Here is my code.
AsyncCallForwardListWS
private class AsyncCallForwardListWS extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
//List<Request_model> thisList = newList;
//List<Tn_Parent> thisList = listDataParent;
List<Request_model> thisList = lvList;
System.out.println("there2: " + thisList.size());
for (int y = 0; y< thisList.size(); y++){
//Request_model model = thisList.get(y);
//Tn_Parent model = thisList.get(y);
Request_model model = thisList.get(y);
if(model.isSelected()){
if(action.equals("deny")){
//getComment = model.getApproverComment();
getComment = model.getApprComments();
}else
getComment = "This request is " + ACTION_MSG + " by " + model.getUser_fullName() + " via mobile app";
//getComment = "This request is " + ACTION_MSG + " by " + model.getApproverName() + " via mobile app";
taskActivity_forward = model.getTaskActivity();
getRequestID = model.getRequestId();
System.out.println("testing");
db.addInfo(new Request_model(model.getRequestId()));
System.out.println("requestid: " + getRequestID);
ForwardWebService();
}
}
return null;
}
AsyncCallListWS
private class AsyncCallListWS extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.show();
progressDialog.setContentView(R.layout.custom_progressbar);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
TextView textView1 = (TextView) progressDialog.findViewById(R.id.textView1);
Typeface dsr = Typeface.createFromAsset(getActivity().getAssets(), getResources().getString(R.string.droid_sans));
textView1.setTypeface(dsr);
System.out.println("here1");
isThereAnyRequest = false;
if(lvAdapter!=null) {
lvAdapter.clear();
lvAdapter.notifyDataSetChanged();
}
}
#Override
protected Void doInBackground(Void... params) {
//listDataParent = new ArrayList<Tn_Parent>();
listPending();
System.out.println("here2");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dismissLoadingDialog();
System.out.println("here3");
selectAll.setChecked(false);
if(getContext()!=null) {
lvAdapter = new Tn_ListViewAdapter(getActivity(), lvList, selectAll);
listView.setAdapter(lvAdapter);
progressDialog.dismiss();
}
if (isThereAnyRequest){
buttonLayout.setVisibility(View.VISIBLE);
//selectAll.setVisibility(View.VISIBLE);
checkBox_layout.setVisibility(View.VISIBLE);
//textView.setVisibility(View.GONE);
no_request_noti.setVisibility(View.GONE);
}
else{
buttonLayout.setVisibility(View.INVISIBLE);
//selectAll.setVisibility(View.INVISIBLE);
checkBox_layout.setVisibility(View.GONE);
//textView.setVisibility(View.VISIBLE);
no_request_noti.setVisibility(View.VISIBLE);
}
}
}
}
I have this somewhere else to trigger the asynctask.
new AsyncCallForwardListWS().execute();
new AsyncCallListWS().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Both asynctasks really run together at the same time but it is so weird that the for loop in AsyncCallForwardListWS will not loop according to the number of checkbox that I have selected. Please help.
did System.out.println("there2: " + thisList.size()); show the exact number of the list?
if not try
List<Request_model> thisList=new List<Request_model>();
thisList.addAll(lvList);
//at post of
List<Request_model> thisList = lvList;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having a problem with a task that shows live content from a site.
I have been playing around with this code for a while and playing around with the status but I can't seem to get it to work correctly.
The only solution I have been able to come up with so far is completely disable orientation changes, but I would prefer not to do that if possible.
Here is the Stack Trace:
STACK_TRACE = java.lang.IllegalArgumentException: View not attached to window manager
at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:653)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:349)
at android.view.WindowManagerImpl$CompatModeWrapper.removeView(WindowManagerImpl.java:160)
at android.app.Dialog.dismissDialog(Dialog.java:319)
at android.app.Dialog.dismiss(Dialog.java:302)
at cl.cromer.tronwell.concepcion.Progress.dismiss(Progress.java:72)
at cl.cromer.tronwell.concepcion.AdditionalMaterial.databaseLoaded(AdditionalMaterial.java:149)
at cl.cromer.tronwell.concepcion.AdditionalMaterial.access$13(AdditionalMaterial.java:122)
at cl.cromer.tronwell.concepcion.AdditionalMaterial$1$1.run(AdditionalMaterial.java:73)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5031)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Here is my code for the class that is crashing:
package cl.cromer.tronwell.concepcion;
import java.util.Calendar;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cl.cromer.tronwell.concepcion.DBSchema.DBAdditionalMaterial;
import cl.cromer.tronwell.concepcion.DBSchema.DBAdditionalMaterialGroups;
import cl.cromer.tronwell.concepcion.Files.Download;
public class AdditionalMaterial extends ActionBarActivity implements ListenerXML, ListenerDownload, ListenerAsync {
private final static String URL = "action=downloads";
private XMLParser xmlParser;
private Progress progress = null;
// Parsers
private SQLParser sqlParser;
private Handler threadHandler = new Handler();
// The database
private SQLiteDatabase tronDB;
private int downloadId = 0;
private boolean downloadAll = false;
private int downloadCount = 1;
private int firstDownloadAvailable = 0;
private String fileName;
private Files files = new Files();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("debug", "onCreate");
setContentView(R.layout.activity_additional_material);
//progress = new Progress();
//progress.show(this, this, false);
sqlParser = new SQLParser(this);
new Thread(new Runnable() {
public void run() {
tronDB = sqlParser.getWritableDatabase();
threadHandler.post(new Runnable() {
public void run() {
databaseLoaded();
}
});
}
}).start();
}
#Override
protected void onStart() {
super.onStart();
Log.d("debug", "onStart");
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("debug", "onRestart");
}
#Override
protected void onResume() {
super.onResume();
progress = new Progress();
progress.show(this, this, false);
Log.d("debug", "onResume");
}
#Override
protected void onStop() {
super.onStop();
Log.d("debug", "onStop");
}
#Override
protected void onDestroy() {
super.onDestroy();
progress = null;
Log.d("debug", "onDestroy");
}
#Override
public void onPause() {
super.onPause();
Log.d("debug", "onDestroy");
}
private void databaseLoaded() {
SharedPreferences settings = getSharedPreferences(Settings.PREFERENCES, MODE_PRIVATE);
long materialDate = settings.getLong(Settings.MATERIAL_DATE, Settings.MATERIAL_DATE_DEFAULT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long currentDate = calendar.getTimeInMillis();
if (currentDate > materialDate ) {
// Update the database
String rut = settings.getString(Settings.RUT, Settings.RUT_DEFAULT);
String password = settings.getString(Settings.PASSWORD, Settings.PASSWORD_DEFAULT);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("rut", rut);
postData.put("pass", password);
xmlParser = new XMLParser(this, postData);
xmlParser.fetchListener = this; // Tell the XMLParser that this activity has the listener
xmlParser.execute(MainActivity.URL + URL);
}
else {
// Material does not need to be updated, just show what is in the database
if (progress != null && progress.isShowing()) {
progress.dismiss();
}
ShowContent showContent = new ShowContent(this);
showContent.asyncListener = this; // Tell the task that this class is listening
showContent.execute();
}
}
private void fetchFinished(HashMap<String, HashMap<String, String>> xmlData) {
// Let's put the groups in the database
HashMap<String, String> xmlHash = xmlData.get("1");
String groups = xmlHash.get("groups");
for (int i = 1; i <= Integer.valueOf(groups); i++) {
ContentValues values = new ContentValues();
values.put(DBAdditionalMaterialGroups.COLUMN_ID, String.valueOf(i));
values.put(DBAdditionalMaterialGroups.COLUMN_NAME, xmlHash.get("group" + String.valueOf(i)));
tronDB.replace(
DBAdditionalMaterialGroups.TABLE_NAME,
null,
values);
}
// Now the material
for (int i = 2; i <= xmlData.size() - 1; i++) {
xmlHash = xmlData.get(String.valueOf(i));
ContentValues values = new ContentValues();
values.put(DBAdditionalMaterial.COLUMN_ID, xmlHash.get("id"));
values.put(DBAdditionalMaterial.COLUMN_NAME, xmlHash.get("title"));
values.put(DBAdditionalMaterial.COLUMN_GROUP, xmlHash.get("group"));
values.put(DBAdditionalMaterial.COLUMN_TYPE, xmlHash.get("type"));
values.put(DBAdditionalMaterial.COLUMN_URL1, xmlHash.get("url1"));
values.put(DBAdditionalMaterial.COLUMN_URL2, xmlHash.get("url2"));
tronDB.replace(
DBAdditionalMaterial.TABLE_NAME,
null,
values);
}
SharedPreferences settings = getSharedPreferences(Settings.PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor settingsEditor = settings.edit();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long currentDate = calendar.getTimeInMillis();
settingsEditor.putLong(Settings.MATERIAL_DATE, currentDate);
settingsEditor.commit();
progress.dismiss();
ShowContent showContent = new ShowContent(this);
showContent.asyncListener = this; // Tell the task that this class is listening
showContent.execute();
}
#TargetApi(Build.VERSION_CODES.FROYO)
protected class ShowContent extends AsyncTask<String, View, Void> {
private Context context;
private PowerManager.WakeLock wakeLock;
protected ListenerAsync asyncListener = null; // This needs to be set from the parent activity
private LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
protected ShowContent(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Let's make sure the CPU doesn't go to sleep
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
wakeLock.acquire();
}
#SuppressLint("InflateParams")
#Override
protected Void doInBackground(String... passedInfo) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View categoryView;
View downloadView;
View seperatorView;
TextView textView = new TextView(context);
ImageButton imageButton = new ImageButton(context);
Cursor cursorMaterialGroups = tronDB.query(
DBAdditionalMaterialGroups.TABLE_NAME,
DBAdditionalMaterialGroups.ALL_COLUMNS,
null,
null,
null,
null,
DBAdditionalMaterialGroups.COLUMN_ID + " ASC",
null);
while (cursorMaterialGroups.moveToNext()) {
// Create a group TextView by inflating a layout
categoryView = inflater.inflate(R.layout.additional_material_category, null);
textView = (TextView) categoryView;
textView.setText(cursorMaterialGroups.getString(cursorMaterialGroups.getColumnIndex(DBAdditionalMaterialGroups.COLUMN_NAME)));
publishProgress(textView);
// Now to get the downloads from the group
Cursor cursorMaterial = tronDB.query(DBAdditionalMaterial.TABLE_NAME,
DBAdditionalMaterial.ALL_COLUMNS,
DBAdditionalMaterial.COLUMN_GROUP + "=" + cursorMaterialGroups.getString(cursorMaterialGroups.getColumnIndex(DBAdditionalMaterialGroups.COLUMN_ID)),
null,
null,
null,
DBAdditionalMaterial.COLUMN_ID + " ASC",
null);
downloadCount += cursorMaterial.getCount();
while (cursorMaterial.moveToNext()) {
downloadView = inflater.inflate(R.layout.additional_material_download, null);
// Download title
textView = (TextView) downloadView.findViewById(R.id.download_title);
textView.setText(cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_NAME)));
// Download/play button
imageButton = (ImageButton) downloadView.findViewById(R.id.download_button);
imageButton.setId(Integer.valueOf(cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_ID))));
String fileName = null;
if (cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_TYPE)).equals("pdf")) {
fileName = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_ID)) + ".pdf";
}
else {
fileName = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_ID)) + ".mp3";
}
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_play);
if (!files.fileExists(context, fileName)) {
if (firstDownloadAvailable == 0) {
firstDownloadAvailable = imageButton.getId();
}
drawable = getResources().getDrawable(R.drawable.ic_action_save);
imageButton.setImageDrawable(drawable);
imageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
downloadId = view.getId();
download();
}
});
}
else {
imageButton.setImageDrawable(drawable);
imageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String contentId = String.valueOf(view.getId());
openContent(contentId);
}
});
}
publishProgress(downloadView);
if (!cursorMaterial.isLast()) {
seperatorView = inflater.inflate(R.layout.additional_material_seperator, null);
publishProgress(seperatorView);
}
}
cursorMaterial.close();
}
// Other
categoryView = inflater.inflate(R.layout.additional_material_category, null);
textView = (TextView) categoryView;
textView.setText("OTHER");
publishProgress(textView);
// Download all
downloadView = inflater.inflate(R.layout.additional_material_download, null);
// Download title
textView = (TextView) downloadView.findViewById(R.id.download_title);
textView.setText("Download all material");
// Download/play button
imageButton = (ImageButton) downloadView.findViewById(R.id.download_button);
imageButton.setId(1);
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_play);
drawable = getResources().getDrawable(R.drawable.ic_action_save);
imageButton.setImageDrawable(drawable);
imageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
downloadId = firstDownloadAvailable;
downloadAll = true;
download();
}
});
publishProgress(downloadView);
cursorMaterialGroups.close();
return null;
}
#Override
protected void onProgressUpdate(View... view) {
linearLayout.addView(view[0]);
}
#Override
protected void onPostExecute(Void result) {
wakeLock.release();
if (asyncListener != null) {
// Call the listener if one is set
asyncListener.onAsyncComplete();
}
}
}
private void download() {
progress.show(this, this, true);
Files files = new Files();
// Check if the memory card can be written to
if (files.isWriteable()) {
Cursor cursorMaterial = tronDB.query(DBAdditionalMaterial.TABLE_NAME,
DBAdditionalMaterial.ALL_COLUMNS,
DBAdditionalMaterial.COLUMN_ID + "=" + String.valueOf(downloadId),
null,
null,
null,
null,
"1");
cursorMaterial.moveToFirst();
String title = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_NAME));
String type = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_TYPE));
String url1 = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_URL1));
String url2 = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_URL2));
cursorMaterial.close();
if (type.equals("pdf")) {
fileName = String.valueOf(downloadId) + ".pdf";
}
else {
fileName = String.valueOf(downloadId) + ".mp3";
}
// Change the message in the downloading prompt
progress.setMessage(getString(R.string.general_downloading) + " " + title);
SharedPreferences settings = getSharedPreferences(Settings.PREFERENCES, MODE_PRIVATE);
String rut = settings.getString(Settings.RUT, Settings.RUT_DEFAULT);
String url = url1 + rut + url2;
url = url.replace(" ", "%20");
final Download download = files.new Download(this, fileName, progress);
download.downloadListener = this;
download.execute(url);
progress.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadAll = false;
download.cancel(true);
}
});
}
else {
progress.dismiss();
Toast.makeText(this, getString(R.string.general_no_memory), Toast.LENGTH_SHORT).show();
}
}
private void openContent(String contentId) {
Cursor cursorMaterial = tronDB.query(DBAdditionalMaterial.TABLE_NAME,
DBAdditionalMaterial.ALL_COLUMNS,
DBAdditionalMaterial.COLUMN_ID + "=" + contentId,
null,
null,
null,
null,
"1");
cursorMaterial.moveToFirst();
String type = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_TYPE));
cursorMaterial.close();
String fileName = "";
String mimeType = "";
if (type.equals("pdf")) {
fileName = contentId + ".pdf";
mimeType = "application/pdf";
}
else {
fileName = contentId + ".mp3";
mimeType = "audio/mp3";
}
files.openFile(this, fileName, mimeType);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (intent.getBooleanExtra(ConnectionFailed.RETRY, false)) {
// Failed, let's try the connection again
SharedPreferences settings = getSharedPreferences(Settings.PREFERENCES, MODE_PRIVATE);
String rut = settings.getString(Settings.RUT, Settings.RUT_DEFAULT);
String password = settings.getString(Settings.PASSWORD, Settings.PASSWORD_DEFAULT);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("rut", rut);
postData.put("pass", password);
xmlParser = new XMLParser(this, postData);
xmlParser.fetchListener = this; // Tell the XMLParser that this activity has the listener
xmlParser.execute(MainActivity.URL + URL);
}
}
// This is the listener for the xml
public void onFetchComplete(String xml) {
if (xml == null) {
progress.dismiss();
// Failed to fetch xml, either a server error or an internet connection problem
Intent intent = new Intent(this, ConnectionFailed.class);
startActivityForResult(intent, 1);
}
else {
HashMap<String, HashMap<String, String>> xmlHash = xmlParser.parseXML(xml);
new User().checkUserValidation(xmlHash.get("0"));
fetchFinished(xmlHash);
}
}
// This is the listener for the download
public void onDownloadComplete(boolean result) {
progress.dismiss();
if (!result) {
Toast.makeText(this, getString(R.string.general_failed_download), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, getString(R.string.general_download_complete), Toast.LENGTH_SHORT).show();
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_play);
ImageButton buttonView = (ImageButton) findViewById(downloadId);
buttonView.setImageDrawable(drawable);
buttonView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String contentId = String.valueOf(view.getId());
openContent(contentId);
}
});
if (downloadAll) {
while (downloadCount >= downloadId) {
downloadId++;
Cursor cursorMaterial = tronDB.query(DBAdditionalMaterial.TABLE_NAME,
DBAdditionalMaterial.ALL_COLUMNS,
DBAdditionalMaterial.COLUMN_ID + "=" + String.valueOf(downloadId),
null,
null,
null,
null,
"1");
cursorMaterial.moveToFirst();
String type = cursorMaterial.getString(cursorMaterial.getColumnIndex(DBAdditionalMaterial.COLUMN_TYPE));
cursorMaterial.close();
if (type.equals("pdf")) {
fileName = String.valueOf(downloadId) + ".pdf";
}
else {
fileName = String.valueOf(downloadId) + ".mp3";
}
if (!files.fileExists(this, fileName)) {
download();
break;
}
}
if (downloadCount == downloadId) {
// The last one downloaded we can now stop the process
downloadAll = false;
}
}
}
}
// This is the listener for the Async
public void onAsyncComplete() {
progress.dismiss();
}
}
Here is the code for my progress bar:
package cl.cromer.tronwell.concepcion;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
public final class Progress {
protected ProgressDialog progressBar = null;
private int oldOrientation = -1; // Orientation not set
private Activity activity;
protected void show(Context context, Activity activity, boolean cancelable) {
this.activity = activity;
// Disable rotation while we are loading something
oldOrientation = activity.getRequestedOrientation();
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
if (progressBar != null && progressBar.isShowing()) {
activity.setRequestedOrientation(oldOrientation);
progressBar.dismiss();
}
progressBar = new ProgressDialog(context);
progressBar.setCancelable(cancelable);
if (!cancelable) {
progressBar.setMessage(context.getString(R.string.general_loading));
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
else {
progressBar.setIndeterminate(true);
progressBar.setCanceledOnTouchOutside(false);
progressBar.setMessage(context.getString(R.string.general_downloading));
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
}
protected void setMessage(String message) {
progressBar.setMessage(message);
}
protected void setIndeterminate(boolean indeterminate) {
progressBar.setIndeterminate(indeterminate);
}
protected void setProgress(int progress) {
progressBar.setProgress(progress);
}
protected void setOnCancelListener(DialogInterface.OnCancelListener listener) {
progressBar.setOnCancelListener(listener);
}
protected boolean isShowing() {
if (progressBar.isShowing()) {
return true;
}
return false;
}
protected void dismiss() {
// Turn rotation back to it's previous state
activity.setRequestedOrientation(oldOrientation);
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
}
}
}
Check answer of this question Answer
I think you facing same issue
Check this one as well Answer 2
Im having a problem on my application, when my application refreshes or loading in slow internet connection.. the activity always destroys, or "Unfortunately (Name) is Stopped" how can i prevent the Force Close on my activity. I'm using Asynctask and JSON file to get my data out of PHP. and this is my code:
package com.example.this;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Frontpane extends Activity {
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
return;
}
Button Loginbutton;
Button exitButton;
EditText username=null;
EditText password=null;
EditText checker;
String Username1;
String Password1;
/** For database connection**/
private static String url = "http://1.1.1.1/radarMonitoring/api/retrieveacc.php";
private static final String TAG_REGISTEREDACCOUNTS = "RegisteredAccounts";
private static final String TAG_ACCNUM = "Acc_Num";
private static final String TAG_USEREG = "User_NameReg";
private static final String TAG_PASSREG = "Pass_WordReg";
JSONArray accnt = null;
String cntb;
String cnta;
String can;
String cbn;
int usncnt;
int pswcnt;
ArrayList<HashMap<String, String>> accntList;
/** For database connection**/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.front);
Toast.makeText(Frontpane.this, "Please Login to Continue.", Toast.LENGTH_SHORT).show();
exitButton = (Button) findViewById(R.id.button);
username=(EditText)findViewById(R.id.username);
password=(EditText)findViewById(R.id.password);
// checker=(EditText)findViewById(R.id.editText1);
exitButton.setOnClickListener(button);
addButtonListener();
/**array of usernames and pw **/
accntList = new ArrayList<HashMap<String, String>>();
/**array of usernames and pw **/
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);
// looping through All Contacts
for (int i = 0; i < accnt.length(); i++) {
int l;
JSONObject c = accnt.getJSONObject(i);
// String an = c.getString(TAG_ACCNUM);
String unr = c.getString(TAG_USEREG);
// String pwr = c.getString(TAG_PASSREG);
// tmp hashmap for single contac
HashMap<String, String> acc = new HashMap<String, String>();
// adding each child node to HashMap key => value
// acc.put(TAG_ACCNUM, an);
acc.put(TAG_USEREG, unr);
// acc.put(TAG_PASSREG, pwr);
if(unr.equals(Username1)){
usncnt = i;
can = unr;
}
// adding contact to contact list
accntList.add(acc);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
cnta = can;
if(Username1.isEmpty()==false){
if(Password1.isEmpty()){
Toast.makeText(Frontpane.this, "Please Enter Password!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
else{
if(cnta!=null){
new GetPAss().execute();
}
else{
Toast.makeText(Frontpane.this, "Not Registered or Check your Internet Connection..", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
else{
Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
private class GetPAss extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);
// looping through All Contacts
for (int i = 0; i < accnt.length(); i++) {
int l;
JSONObject c = accnt.getJSONObject(i);
// String an = c.getString(TAG_ACCNUM);
//String unr = c.getString(TAG_USEREG);
String pwr = c.getString(TAG_PASSREG);
// tmp hashmap for single contac
HashMap<String, String> acc = new HashMap<String, String>();
// adding each child node to HashMap key => value
// acc.put(TAG_ACCNUM, an);
// acc.put(TAG_USEREG, unr);
acc.put(TAG_PASSREG, pwr);
if(pwr.equals(Password1)){
pswcnt = i;
cbn = pwr;
}
// adding contact to contact list
accntList.add(acc);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
cntb = cbn;
if(Username1.isEmpty()){
Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
else{
/* Toast.makeText(Frontpane.this, "meron", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null); */
if(cntb!=null){
if((pswcnt>=0)&&(usncnt>=0)){
if(pswcnt==usncnt){
Intent intent = new Intent(Frontpane.this,MyActivity.class);
startActivity(intent);
Toast.makeText(Frontpane.this, "Login Successful!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
else{
Toast.makeText(Frontpane.this, "Username and Password does not match, Please Try Again! ", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
else{
Toast.makeText(Frontpane.this, "Wrong Password, Please Try Again! ", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses("com.example.RadarOperationMonitoringSystem");
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
// Method 2
System.exit(0);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
public void addButtonListener() {
Loginbutton = (Button) findViewById(R.id.buttonLogin);
Loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Username1 = username.getText().toString();
Password1 = password.getText().toString();
new GetContacts().execute();
Toast.makeText(Frontpane.this, "Please Wait.. Verifying User Log-in. ", Toast.LENGTH_SHORT).show();
}
});
}
OnClickListener button = new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Frontpane.this);
builder.setMessage("Are you sure want to exit?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
};
}
do this in post execute, by returning proper value from doInBackground method. All UI related code should run in ui thread.
Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
Update
you have to do some thing like this
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);
// looping through All Contacts
for (int i = 0; i < accnt.length(); i++) {
int l;
JSONObject c = accnt.getJSONObject(i);
// String an = c.getString(TAG_ACCNUM);
String unr = c.getString(TAG_USEREG);
// String pwr = c.getString(TAG_PASSREG);
// tmp hashmap for single contac
HashMap<String, String> acc = new HashMap<String, String>();
// adding each child node to HashMap key => value
// acc.put(TAG_ACCNUM, an);
acc.put(TAG_USEREG, unr);
// acc.put(TAG_PASSREG, pwr);
if(unr.equals(Username1)){
usncnt = i;
can = unr;
}
// adding contact to contact list
accntList.add(acc);
}
} catch (JSONException e) {
e.printStackTrace();
return false;
}
return true;
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
///Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
if(!result)
{
// add here your message
Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
return;
}
cnta = can;
if(Username1.isEmpty()==false){
if(Password1.isEmpty()){
Toast.makeText(Frontpane.this, "Please Enter Password!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
else{
if(cnta!=null){
new GetPAss().execute();
}
else{
Toast.makeText(Frontpane.this, "Not Registered or Check your Internet Connection..", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
else{
Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
The workflow for executing asynctask is as follows
onPreExecute()
doInBackground(Params...)
onProgressUpdate(Progress...)
onPostExecute(Result)
It is possible to invoke UI code on these methods except doInBackground(Params...). The UI work should be deferred to onPostExecute(Result).
It seems that the toast message in doInbackground is triggered following an exception in the code.
package com.example.tabactivity;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class circularlistparsing extends ActivityGroup {
public int currentPage = 1;
public ListView lisView1;
static final String KEY_ITEM = "docdetails";
static final String KEY_ITEM2 = "info";
static final String KEY_NAME1 = "";
static final String KEY_NAME = "heading";
static final String KEY_DATE = "date";
public Button btnNext;
public Button btnPre;
public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetCircularList";
TextView txtreord;
TextView totalpage;
TextView pagenumber;
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtreord = (TextView) findViewById(R.id.recored);
totalpage = (TextView) findViewById(R.id.totalpage);
pagenumber = (TextView) findViewById(R.id.pagenumber);
// listView1
lisView1 = (ListView) findViewById(R.id.listView1);
// new YourTask().execute();
// Next
btnNext = (Button) findViewById(R.id.btnNext);
// Perform action on click
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage + 1;
// new YourTask().execute();
ShowData();
pagenumber.setText("Of" + currentPage+"]");
}
});
// Previous
btnPre = (Button) findViewById(R.id.btnPre);
// Perform action on click
btnPre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage - 1;
// new YourTask().execute();
ShowData();
pagenumber.setText("Of" + currentPage+"]");
}
});
// new YourTask().execute();
ShowData();
}
public void ShowData() {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
NodeList n2 = doc.getElementsByTagName(KEY_ITEM2);
int displayPerPage = 10; // Per Page
int TotalRows = nl.getLength();
txtreord.setText( TotalRows+"Records|"); // number of records
int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);
int TotalPage = 0;
if (TotalRows <= displayPerPage) {
TotalPage = 1;
} else if ((TotalRows % displayPerPage) == 0) {
TotalPage = (TotalRows / displayPerPage);
} else {
TotalPage = (TotalRows / displayPerPage) + 1; // 7
TotalPage = (int) TotalPage; // 7
}
totalpage.setText("Page[" + TotalPage);
int indexRowEnd = displayPerPage * currentPage; // 5
if (indexRowEnd > TotalRows) {
indexRowEnd = TotalRows;
}
// Disabled Button Next
if (currentPage >= TotalPage) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
// Disabled Button Previos
if (currentPage <= 1) {
btnPre.setEnabled(false);
} else {
btnPre.setEnabled(true);
}
// Load Data from Index
int RowID = 1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
// RowID
if (currentPage > 1) {
RowID = (displayPerPage * (currentPage - 1)) + 1;
}
for (int i = indexRowStart; i < indexRowEnd; i++) {
Element e = (Element) nl.item(i);
Element e2 = (Element) n2.item(i);
String date = e2.getAttribute(KEY_DATE);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put("RowID", String.valueOf(RowID));
map.put(KEY_DATE, date);
// String Heading = parser.getValue(e, KEY_NAME).replace("|", "|\n")
// .replace("|", "");
//
String mytime = date;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
Date myDate = null;
try {
myDate = dateFormat.parse(mytime);
} catch (ParseException t) {
t.printStackTrace();
} catch (java.text.ParseException t) {
// TODO Auto-generated catch block
t.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = timeFormat.format(myDate);
// System.out.println("rrrrrrrrrrrrr"+finalDate);
String Heading = parser.getValue(e, KEY_NAME);
int a = Heading.indexOf("|");
String beforeSubString = Heading.substring(0, a);
String afterSubString = Heading.substring(a, Heading.length())
.replace("|", "") + "[" + finalDate + "]";
// String
// final1="<b>"+beforeSubString+"<b>"+"|"+afterSubString.replace("|",
// "|\n")
// .replace("|", "");
// String k=Html.fromHtml(final1).toString();
//
// Html.fromHtml(final1);
map.put(KEY_NAME, beforeSubString);
map.put(KEY_NAME1, afterSubString);
// adding HashList to ArrayList
menuItems.add(map);
RowID = RowID + 1;
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(circularlistparsing.this, menuItems,
R.layout.list_item,
new String[] { "RowID", KEY_NAME1, KEY_NAME }, new int[] {
R.id.ColRowID, R.id.ColName, R.id.textView1 });
lisView1.setAdapter(sAdap);
lisView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(circularlistparsing.this, detail.class);
// sending data to new activity
// i.putExtra("product", product);
startActivity(i);
}
});
}
class YourTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
dialog = ProgressDialog.show(circularlistparsing.this, "", "Please wait..");
}
protected Void doInBackground(Void... unused) {
try {
// doSomethingHeavy();
// publishProgress(...);
ShowData();
} catch(Exception e) {
//...
}
return null;
}
protected void onProgressUpdate(Void... unused) {
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
}
Hii please this code show data function is for displaying data when i m using new YourTask().execute(); in place of show data then its showing Progress bar but not displaying data but able to read data while when we user showdata() function den it display data please tell me how to implement progress bar .
private class YourTask extends AsyncTask<Object, Integer, Object> {
ProgressDialog dialog = new ProgressDialog(Currentactivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
this.dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
//do hard work here
return params;
}
#Override
protected void onProgressUpdate(Integer... values) {
progress.getProgress();
}
#Override
protected void onPostExecute(Object result) {
progressBar.dismiss();
super.onPostExecute(result);
}
}
implement this code
private class YourTask extends AsyncTask<Object, Integer, Object> {
#Override
protected void onPreExecute() {
ProgressDialog dialog = ProgressDialog.show(Activity.this, "",
"Loading...");
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
try {
// doSomethingHeavy();
// publishProgress(...);
ShowData();
} catch(Exception e) {
//...
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog .getProgress();
}
#Override
protected void onPostExecute(Object result) {
dialog .dismiss();
super.onPostExecute(result);
}
}