This is my MainActivity... i put one button, in button onclick i call asyncTask
package com.example.asnytaskpro;
import java.util.concurrent.ExecutionException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AsyncMainActivity extends Activity implements OnClickListener {
Button button ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_async, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.err.println("1");
try {
new AllPrinterClass(AsyncMainActivity.this, "123456789123456789", "123").execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
This is My AsyncTaskClass
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Toast;
public class AllPrinterClass extends AsyncTask<Integer, Integer, Integer>{
public static String ServerData = "";
private ProgressDialog prgDialog;
private Context context;
String TransNo = "" ,IMEINo = "";
int iRetValue = 0;
String CurrentDate = null, CurrentTime= null;
SimpleDateFormat df,tf;
public AllPrinterClass(Context context1, String imeiNo,String transno2)
{
this.context = context1;
this.IMEINo = imeiNo;
this.TransNo = transno2;
Calendar c = Calendar.getInstance();
df = new SimpleDateFormat("dd/M/yyyy");
CurrentDate = df.format(c.getTime());
tf = new SimpleDateFormat("hh:mm:ss");
CurrentTime = tf.format(c.getTime());
System.err.println(CurrentDate);
System.err.println(CurrentTime);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.prgDialog = new ProgressDialog(context);
this.prgDialog.setMessage("Place your finger on FPS ...");
this.prgDialog.setIndeterminate(true);
this.prgDialog.setCancelable(false);
this.prgDialog.show();
}
#Override
protected Integer doInBackground(Integer... params) {
//////////////////Doing my Code///////////////////
for (int i = 0; i < 10; i++) {
System.err.println("i :-" + i);
SystemClock.sleep(500);
}
/////////////////////////////////////////////////////
return iRetValue;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prgDialog.dismiss();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
}
This code working for me but my ProgressDialog not showing(May be run background).
In i remove prgDialog.dismiss(); in onPostExecute() Method then my dialog showing after doInBackground() Method.
I want dialog show in onPreExecute() Method and dismiss in onPostExecute() method.
Here:
...execute().get();
Calling get method will block main ui Thread until doInBackground execution not completed. that's why ProgressDialog is not showing.
Use only execute() method to start AsyncTask which show Progress Dialog during doInBackground method execution:
new AllPrinterClass(AsyncMainActivity.this,
"123456789123456789", "123").execute();
Related
I am developing an Android eCommerce application in which there are two different buttons. The first one is an ADD TO CART button and the other one is a BUY NOW button.
When I click on the ADD TO CART button, it successfully places the item in the cart and after I click on the cart button, the app proceeds to the Cart Activity. I did the same for BUY NOW but the issue is how do I update my cart and move to Cart Activity on a single click?
ProductDescription.java:
package com.www.prashant;
import android.app.ProgressDialog;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.slider.library.SliderLayout;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class ProductDescription extends Fragment {
View V;
int position;
ImageView product_image;
TextView product_desc;
public TextView price;
public TextView specialPrice;
TextView product_name;
ImageLoader image;
SliderLayout product_images;
Button sharbtn;
public TextView txt_qty;
public Button btn_plus;
public Button btn_buy;
ProgressDialog pdialog;
public int sum=0;
public int remove=0;
String cartMessage;
String cartMessage1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
Constants.lastDetails = true;
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_details, container, false);
//Set Navigation mode as Statndard
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);
V=v;
//get Product Position
position = Constants.product_position;
//Initialize ids
product_image=(ImageView) V.findViewById(R.id.product_image);
product_desc=(TextView) V.findViewById(R.id.textProductDescription);
price=(TextView) V.findViewById(R.id.text1);
specialPrice = (TextView) V.findViewById(R.id.textSpecialPrice);
product_name=(TextView) V.findViewById(R.id.textProductName);
//sharbtn=(Button)V.findViewById(R.id.sharbtn);
image=new ImageLoader(getActivity());
image.DisplayImage(Constants.Product_image.get(position), product_image);
product_name.setText(Constants.Product_name.get(position));
product_desc.setText(Constants.Product_desc.get(position));
// product_adesc.setText(Constants.Product_adesc.get(position));
if(Constants.Product_specialPrice.get(position) < Constants.Product_price.get(position)
&& Constants.Product_specialPrice.get(position)!=0){
price.setText(String.format("%.2f",Constants.Product_price.get(position)));
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
specialPrice.setText(String.format("%.2f",Constants.Product_specialPrice.get(position)));
}
else {
price.setText(String.format("%.2f",Constants.Product_price.get(position)));
specialPrice.setText(null);
}
btn_plus = (Button) V.findViewById(R.id.btn_plus);
btn_buy = (Button) V.findViewById(R.id.btn_buy);
// btn_minus = (ImageButton) V.findViewById(R.id.btn_minus);
txt_qty = (TextView) V.findViewById(R.id.txt_qty);
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
**/* Button Click Listener for Add Qty*/**
btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.Product_pos=position;
remove=0;
sum = Integer.parseInt(txt_qty.getText().toString())+1;
Constants.Product_qty.set(position, sum);
cartMessage1="Adding product to cart...";
cartMessage="Product was added successfully";
new updateCart().execute();
}
});
**/* Button Click Listener for Buy Qty*/**
btn_buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.Product_pos=position;
remove=0;
sum = Integer.parseInt(txt_qty.getText().toString())+1;
Constants.Product_qty.set(position, sum);
cartMessage1="Adding product to cart...";
cartMessage="Product was added successfully";
new updateCart().execute();
}
});
product_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageFragment imageFrag=new ImageFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,imageFrag,null).addToBackStack(null).commit();
getActivity().setTitle("Images");
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//((MainActivity)getActivity()).resetActionBar(true, DrawerLayout.LOCK_MODE_LOCKED_OPEN);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
MainActivity.getInstance().CallFragment(Constants.position);
}
return true;
}
//Add product to cart task
public class updateCart extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage(cartMessage1);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataAddProductToCart();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
Toast.makeText(getActivity(), cartMessage, Toast.LENGTH_LONG).show();
//Update Notification Count in action bar icon
//Constants.cart_count += 1;
//txt_qty.setText(String.valueOf(sum));
MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
//Remove product from cart
public class removeCartProduct extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage(cartMessage1);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataAddProductToCart();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
Toast.makeText(getActivity(), cartMessage,Toast.LENGTH_LONG).show();
//Update Notification Count in action bar icon
//Constants.cart_count -= 1;
//txt_qty.setText(String.valueOf(sum));
MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
public void parseJSONDataAddProductToCart(){
try {
SoapObject item = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntity");
SoapObject request;
int qty;
if(remove==0){
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductAdd");
qty=1;
}else{
qty= Constants.Product_qty.get(Constants.Product_pos);
if(qty==0){
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductRemove");
}else{
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductUpdate");
}
}
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
PropertyInfo pinfo = new PropertyInfo();
pinfo.setName("product_id");
pinfo.setValue(Constants.Product_ID.get(Constants.Product_pos));
pinfo.setType(String.class);
item.addProperty(pinfo);
pinfo = new PropertyInfo();
pinfo.setName("qty");
pinfo.setValue(qty);
pinfo.setType(Double.class);
item.addProperty(pinfo);
SoapObject EntityArray = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntityArray");
EntityArray.addProperty("products", item);
request.addProperty("quoteId", Constants.cartId);
request.addProperty("products",EntityArray);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
//Web method call
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.URL);
androidHttpTransport.debug = true;
androidHttpTransport.call("", envelope);
//get the response
Object result = envelope.getResponse();
Constants.CartaddStatus=result.toString();
if(Constants.CartaddStatus == "true"){
if (Constants.ProductCart_Id.isEmpty()){
Constants.cartArrayPos=0;
}
if (!Constants.ProductCart_Id.contains(Constants.Product_ID.get(Constants.Product_pos))) {
Constants.ProductCart_Id.add(Constants.cartArrayPos,Constants.Product_ID.get(Constants.Product_pos));
Constants.ProductCart_Img.add(Constants.cartArrayPos,Constants.Product_image.get(Constants.Product_pos));
Constants.ProductCart_Price.add(Constants.cartArrayPos, Constants.Product_price.get(Constants.Product_pos));
Constants.cartArrayPos+=1;
}
if (qty==0){
Constants.ProductCart_Id.remove(Constants.Product_pos);
Constants.ProductCart_Img.remove(Constants.Product_pos);
Constants.ProductCart_Price.remove(Constants.Product_pos);
Constants.cartArrayPos-=1;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
ActivityCart:
package com.www.prashant;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
/**
* Created by Prashant on 10/16/2016.
*/
public class ActivityCart extends Fragment {
int run;
ProgressDialog pdialog;
View v;
GridView list2;
CartImageLoadAdapter adapter;
public static ActivityCart sActivityCart;
public Double TotalPrice= 0.00;
TextView btn_place_order;
TextView btn_place;
Button btn_place_ord;
static String TotalProductCartPrice;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.cart, container, false);
sActivityCart = this;
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);
list2=(GridView)v.findViewById(R.id.cartlist);
//list2.setBackgroundColor(Color.BLACK);
//list2.setVerticalSpacing(1);
// list2.setHorizontalSpacing(1);
clearData();
btn_place_order = (TextView) v.findViewById(R.id.btn_place_order);
// btn_place = (TextView) v.findViewById(R.id.btn_place);
btn_place_ord = (Button) v.findViewById(R.id.btn_place_ord);
btn_place_ord.setOnClickListener(listener);
return v;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Constants.lastDetails = false;
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
Constants.cartEntry=1;
new getDataTask().execute();
}
void clearData(){
Constants.Product_ID.clear();
Constants.Product_name.clear();
Constants.Product_price.clear();
Constants.Product_image.clear();
Constants.Product_qty.clear();
Constants.Product_specialPrice.clear();
Constants.Product_desc.clear();
//Constants.Product_adesc.clear();
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
if (run==1) {
list2.setAdapter(null);
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
super.onDestroy();
}
//Click Listner for place order button
public View.OnClickListener listener=new View.OnClickListener(){
#Override
public void onClick(View arg0) {
if(run == 1) {
// Call Login Function
if(Constants.Customer_FirstName.equals(""))
{
CartLogin CartLogin=new CartLogin();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CartLogin,null).addToBackStack(null).commit();
getActivity().setTitle("Login");
}
else {
// Call Shipping Information Function
ActivityCustomerAddress CustomerAddress=new ActivityCustomerAddress();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CustomerAddress,null).addToBackStack(null).commit();
getActivity().setTitle("Shipping");
}
}
else
Toast.makeText(getActivity(),"Cart is Empty",Toast.LENGTH_LONG).show();
}
};
// Image urls used in LazyImageLoadAdapter.java file
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage("Loading...");
pdialog.setCanceledOnTouchOutside(getRetainInstance());
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
if (!Constants.ProductCart_Id.isEmpty()){
parseJSONData();
run=1;
}else{
run=0;
}
//Get Product Prices
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Create custom adapter for listview
if (run==1) {
String[] images = new String[Constants.Product_image.size()];
images = Constants.Product_image.toArray(images);
adapter = new CartImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list2.setAdapter(adapter);
if (pdialog.isShowing()) {
pdialog.dismiss();
pdialog = null;
}
}else{
if (pdialog.isShowing()) {
pdialog.dismiss();
pdialog = null;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Cart is Empty").setMessage("Start Shopping now !!").create().show();
run=0;
}
// if internet connection and data available show data on list
// otherwise, show alert text
// btn_place_order.setText(String.format("Total: %.2f Place Order", TotalPrice));
btn_place_order.setText(String.format("%.2f ", TotalPrice));
TotalProductCartPrice= btn_place_order.getText().toString();
}
}
// method to parse json data from server
public void parseJSONData(){
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://prashant.com/customApi/cartDetails.php?cartId="+Constants.cartId;
//Log.i("httpget", URL);
JSONParser parser =new JSONParser();
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
Constants.Login=SetServerString;
JSONArray array=new JSONArray(SetServerString);
for (int i = 0; i < array.length(); i++) {
JSONObject obj=array.getJSONObject(i);
Constants.Product_ID.add(Long.parseLong(obj.getString("productId")));
Constants.Product_name.add(obj.getString("name"));
Double price= Double.valueOf(obj.getString("price"));
int Qty= Integer.parseInt(obj.getString("qty"));
Constants.Product_price.add(price*Qty);
Constants.Product_image.add(obj.getString("imageurl"));
Constants.Product_qty.add(Integer.valueOf(obj.getString("qty")));
Constants.Product_specialPrice.add((Double.valueOf(obj.getString("spprice")))*Qty);
// Total Sum of Cart Item price
TotalPrice += Double.valueOf(Double.valueOf(obj.getString("spprice"))*Qty);
}
// Show response on activity
}
catch(Exception ex)
{
}
}
public static ActivityCart getInstance() {
return sActivityCart;
}
public void SyncCart(){
// Call Shipping Information Function
ActivityCart SyncCart=new ActivityCart();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,SyncCart,null).addToBackStack(null).commit();
getActivity().setTitle("Cart");
}
}
I have followed a number of guides and other questions I think exactly but I have an error that I can't fix.
Against this line
private class loadNotams extends AsyncTask<String, Void, Void> {
I am getting this error
The type MainActivity.loadNotams must implement the inherited abstract method AsyncTask.doInBackground(String...)
and against this line
protected Void doInBackground(String airfield) {
I am getting this error:
The method doInBackground(String) of type MainActivity.loadNotams must override or implement a supertype method
Any ideas here is my whole code:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView testText;
Notam[] notamList = new Notam[100];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Document doc = null;
testText = (TextView) findViewById(R.id.textview);
new loadNotams().execute("ybmk");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class loadNotams extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String airfield) {
Document doc = null;
try {
doc = Jsoup
.connect(
"https://pilotweb.nas.faa.gov/PilotWeb/notamRetrievalByICAOAction.do?method=displayByICAOs")
.data("retrieveLocId", airfield)
.data("formatType", "ICAO")
.data("reportType", "REPORT")
.data("actionType", "notamRetrievalByICAOs")
// .userAgent("Mozilla")
// .cookie("auth", "token")
.timeout(3000).post();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int counter = 0;
Elements pre = doc.select("pre");
for (Element link : pre) {
// get the value from href attribute
System.out.println("text : " + link.text());
notamList[counter++] = new Notam(airfield, link.text()
.substring(0, 8), link.text().substring(11,
link.text().length()));
}
counter--;
while (counter >= 0) {
System.out.println("class : " + notamList[counter].identifier
+ "#" + notamList[counter].notamText);
counter--;
}
testText.setText(notamList[0].notamText);
return null;
}
}
}
change
protected Void doInBackground(String airfield)
to
protected Void doInBackground(String... airfield)
or
protected Void doInBackground(String[] airfield)
as doInBackground() methods requires array of Strings as parameter
and also change to
try {
doc = Jsoup
.connect(
"https://pilotweb.nas.faa.gov/PilotWeb/notamRetrievalByICAOAction.do?method=displayByICAOs")
.data("retrieveLocId", airfield[0])
.data("formatType", "ICAO")
.data("reportType", "REPORT")
.data("actionType", "notamRetrievalByICAOs")
// .userAgent("Mozilla")
// .cookie("auth", "token")
.timeout(3000).post();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Make it a variable argument method
protected Void doInBackground(String... airfield)
I'm simply loading an image on button click via url , i want progress bar to show downloadin done,0-100 now i had changed the code not showing the progress updation but only progress bar
kindly help. XML has a button [downloadbtn], and a progressbar, imageview and a quit button
mainfest.xml has acsess permission internet
code:
*
package com.example.t4;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressBar prgs;
ProgressTask task = new ProgressTask();
Button showProgressBtn;
Button stopProgressBtn;
ImageView img;
Bitmap bmp ;
TextView tv1;
int filesize,filedyn;
public void startdownload(){
try { URL url;
url = new URL("http://whywedoit.files.wordpress.com/2009/04/smile.jpg");
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
filesize = urlConnection.getContentLength();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.tv1);
img = (ImageView) findViewById(R.id.imageView1) ;
stopProgressBtn = (Button) findViewById(R.id.btnCancel);
prgs = (ProgressBar) findViewById(R.id.progress);
showProgressBtn = (Button) findViewById(R.id.btn);
prgs.setVisibility(View.INVISIBLE);
img.setVisibility(View.INVISIBLE);
tv1.setVisibility(View.INVISIBLE);
final ProgressTask pgt = new ProgressTask();
showProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(pgt.getStatus()==Status.RUNNING){Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();}
if(pgt.getStatus()==Status.FINISHED||pgt.getStatus()==Status.PENDING){
Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();
prgs.setVisibility(View.VISIBLE);
task.execute(10);
tv1.setVisibility(View.VISIBLE);
}}
});
stopProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
stopProgress();
}
});
}
private class ProgressTask extends AsyncTask<Integer,Integer,Void>{
protected void onPreExecute() {
super.onPreExecute();
prgs.setMax(100); // set maximum progress to 100.
}
protected void onCancelled() {
prgs.setMax(0); // stop the progress
Log.v("Progress","Cancelled");
finish();
}
protected Void doInBackground(Integer... params) {
startdownload();
//for(int j=0;j<=filesize;j++){
publishProgress((int) ((filedyn / (float) filesize) * 100));
//}
Log.v("Progress","Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(0);
Log.v("Progress","Updating");
}
protected void onPostExecute(Void result) {
img.setVisibility(View.VISIBLE);
tv1.setVisibility(View.INVISIBLE);
img.setImageBitmap(bmp);
prgs.setVisibility(View.INVISIBLE);
Log.v("Progress", "Finished");
}
}
public void stopProgress() {
task.cancel(true);
}
}
*
Sorry, I don't think you only have progress bar update problems. There are too many points needs to be repaired.
1st inside your OnClickListener, you are doing task.execute(10);showProgress(); AsnycTask is asynchronous task, you cannot put your showProgress() there. Do something with your code.
private boolean init = true;
private Void doInBackground(Integer... params) {
init = true;
startdownload();
Log.v("Progress", "Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
if (init){
showProgress();
init = false;
}else{
prgs.setProgress(5);
Log.v("Progress", "Once");
}
}
2nd startdownload method, are you sure your startdownload method doing downloading? or just getting the length of filesize. Make it clear else you will get yourself confuse.
3nd To invoke onProgressUpdate, you need to call publishProgress(progressValue); Here's the sample.
private Void doInBackground(Integer... params) {
init = true;
startdownload();
publishProgress(5); // onProgressUpdate invoked
//
// doing download
//
Log.v("Progress", "Downloading");
return null;
}
use this code and use progressdialog instead of progressbar
#Override
protected void onProgressUpdate(Integer... progress) {
//Set the pertange done in the progress dialog
pd.setProgress((int) (progress[0]));
}
You need set the ProgressBar max value and you need to update the progress in onProgressUpdate
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(values[0]);
Log.v("Progress","Once");
}
and call
publishProgress(progress)
in the doInBackground of ProgressTask to update the progress
Check for more ref
When i am trying to call the method "refresh" of main activity from another Api class,the method was called and also it shows some fatal errors.And it didn't change the adapter values.Can anyone give any idea to clear that.?
package com.example.hotspot;
import com.example.hotspot.HotspotApi;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends Activity {
TextView textview;
ListView listview;
HotspotAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hot_spot);
textview = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
adapter = new HotspotAdapter(this);
listview.setAdapter(adapter);
new HotspotApi(adapter).execute();
}
public void refresh() {
System.out.println("refresh() is called");
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hot_spot, menu);
return true;
}
}
hotspot.java
package com.example.hotspot;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.hotspot.HotspotModel;
import com.example.hotspot.HotspotAdapter;
import android.os.AsyncTask;
public class HotspotApi extends AsyncTask<Void, Integer, Void> implements
Icommon {
public Boolean IsServerErr = false;
private JSONArray response_array;
String url = "some url";
HotspotAdapter adapter;
HotSpot hot;
public HotspotApi(HotspotAdapter adapter) {
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getresult();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
hot=new HotSpot();
hot.refresh();
super.onPostExecute(result);
}
void getresult() {
InternetManager manager = new InternetManager(url);
String category_jsonresponse = manager.URLRequest();
if (!manager.IsServerConn) {
IsServerErr = true;
}
if (category_jsonresponse != null) {
System.out.println("Hotspot_jsonresponse" + category_jsonresponse);
try {
response_array = new JSONArray(category_jsonresponse);
for (int i = 1; i < response_array.length(); i++) {
JSONObject image_object = response_array.getJSONObject(i);
HotspotModel h = new HotspotModel();
h.setId(image_object.getString("id") == null ? ""
: image_object.getString("id"));
h.setContent(image_object.getString("content") == null ? ""
: image_object.getString("content"));
h.setImg(image_object.getString("img") == null ? ""
: image_object.getString("img"));
h.setName(image_object.getString("name") == null ? ""
: image_object.getString("name"));
arraylist.add(h);
}
System.out.println("HotspotModelsize() is " + arraylist.size());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
HotspotAdapter.java
package com.example.hotspot;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class HotspotAdapter extends BaseAdapter implements Icommon{
private TextView textview;
private View view;
ImageView imageview;
private LayoutInflater inflater;
public HotspotAdapter(Context context ){
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arraylist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arraylist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
view = inflater.inflate(R.layout.custom_layout, null);
} else {
view = arg1;
}
textview = (TextView) view.findViewById(R.id.txt_content);
textview.setText(arraylist.get(arg0).getName());
return view;
}
}
In your HotSpotApi class you are creating a new HotSpot activity, this seems wrong. I guess that you are getting json data from internet and load it into a listview.
Solution:
In HotspotApi change following instead of calling activity method:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
adapter.notfiyDatasetChanged();
}
Hope this will help you.
hot=new HotSpot(); ?? you cannot use like that! HotSpot is an activity, should be called by Framework for example, activitymanager. Or use startActivity() to show a activity.
Refresh method (adapter.notifyDataSetChanged();) will result in refresh of UI. However, hot = new HotSpot() will not call onCreated() method,which means the UI is not created. So it definitely results in the fatal error.
I'd never see anyone call an Activity with new operator.
You should reference the common process about how use a activity and adapter.
I am displaying a progress bar using Async task class and simulatneously in parallel operation , i want to retrieve a string array from a function of another class that takes some time to return the string array.
The problem is that when i place the function call in doing backgroung function of AsyncTask class , it gives an error in Doing Background and gives the message as cant change the UI in doing Background ..
Therefore , i placed the function call in post Execute method of Asynctask class . It doesnot give an error but after the progress bar has reached 100% , then the screen goes black and takes some time to start the new activity.
How can i display the progress bar and make the function call simultaneously.??plz help , m in distress
here is the code
package com.integrated.mpr;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Progess extends Activity implements OnClickListener{
static String[] display = new String[Choose.n];
Button bprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
bprogress = (Button) findViewById(R.id.bProgress);
bprogress.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bProgress:
String x ="abc";
new loadSomeStuff().execute(x);
break;
}
}
public class loadSomeStuff extends AsyncTask<String , Integer , String>{
ProgressDialog dialog;
protected void onPreExecute(){
dialog = new ProgressDialog(Progess.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i = 0 ;i<40;i++){
publishProgress(5);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
dialog.dismiss();
String y ="abc";
return y;
}
protected void onProgressUpdate(Integer...progress){
dialog.incrementProgressBy(progress[0]);
}
protected void onPostExecute(String result){
display = new Logic().finaldata();
Intent openList = new Intent("com.integrated.mpr.SENSITIVELIST");
startActivity(openList);
}
}
}
You can't dismiss the dialog in doInBackground() - even dismissing a dialog needs the UI task. Move dialog.dismiss() to onPostExecute() of the AsyncTask.