running asyntask concurrently (android) - android

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;

Related

How do I successfully refresh Recyclerview in fragment using SwipeRefreshLayout

I am fetching data from a website using jsoup into recyclerview but I can't quite figure out exactly what I should do to refresh and update the recyclerview using the swiperefreshlayout. Can someone please help explain what code do I put in onRefresh in the code below to be able to refresh on pull down?
Content content = new Content();
content.execute();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
//What do I put in here??
}
});
return root;
}
private class Content extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
//progressBar.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressBar.setVisibility(View.GONE);
//progressBar.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
adapter.notifyDataSetChanged();
}
#Override
protected Void doInBackground(Void... voids) {
try {
String url = "https://www.mywebsite.com";
Document doc = Jsoup.connect(url).get();
Elements data = doc.select(".thisurl");
int size = data.size();
Log.d("doc", "doc: " + doc);
Log.d("data", "data: " + data);
Log.d("size", "" + size);
for (int i = 0; i < size; i++) {
String date = doc.select(".b-time").eq(i).text();
String league = doc.select(".card-competition-title").eq(i).text();
String homeLogo = data.select(".card-vs-left")
.select("img")
.eq(i)
.attr("src");
String homeTeam = doc.select(".card-vs-left").eq(i).text();
String awayLogo = data.select(".card-vs-right")
.select("img")
.eq(i)
.attr("src");
String awayTeam = doc.select(".card-vs-right").eq(i).text();
String pick = doc.select("span.card-our-prono").eq(i).text();
sportyParseItems.add(new SportyParseItem(date, league, homeLogo, homeTeam, awayLogo, awayTeam, pick));
Log.d("items", "img: " + homeLogo + "img:" + awayLogo + " . title: " + league);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
content.execute();
}
});

How to fix AsyncTask params error?

I am working on a registration based project that uses asyncTask. But I am getting errors on its params and the background usage tasks.
Snippet -
public class signupActivity extends AppCompatActivity {
EditText edit_name;
EditText edit_usn;
EditText edit_addnum;
EditText edit_pass;
EditText edit_repass;
Button btn_sign;
private static final String REGISTER_URL="http://abcd.000webhostapp.com/signup.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
edit_name=(EditText)findViewById(R.id.id_name);
edit_usn=(EditText)findViewById(R.id.id_usn);
edit_addnum=(EditText)findViewById(R.id.id_add);
edit_pass=(EditText)findViewById(R.id.id_pass);
edit_repass=(EditText)findViewById(R.id.id_repass);
btn_sign=(Button)findViewById(R.id.btn_signup);
btn_sign.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
registerUser();
}
});
}
private void registerUser() {
String name=edit_name.getText().toString().trim().toLowerCase();
String usn=edit_usn.getText().toString().trim().toLowerCase();
String addnum=edit_addnum.getText().toString();
String pass=edit_pass.getText().toString().trim().toLowerCase();
String repass=edit_repass.getText().toString().trim().toLowerCase();
register(name, usn, addnum, pass, repass);
}
private void register(String name,String usn,String addnum,String pass,String repass) {
String urlsuffix = "?name=" + name + "&usn=" + usn + "&ddnum=" + addnum + "&pass=" + pass + "&repass=" + repass;
//Getting **illegal start of type** for void keyword here
class RegisterUser extends AsyncTask <String, void, String> implements abcd.project2.RegisterUser {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(signupActivity.this, "please wait", null, true, true);
}
//Getting **method does not override or implement a method from a supertype** for override here
#Override
protected void onPostExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "Internet not found", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
}
RegisterUser ur = new RegisterUser();
ur.execute(urlsuffix);
}
public void openCreateList(View view) {
Intent i = new Intent(this, createActivity.class);
startActivity(i);
}}
Error messages -
Error:(56, 50) error: illegal start of type Error:(65, 9) error:
method does not override or implement a method from a supertype
How do I solve these?
I tried changing the return type in params but still I am unable to solve the error.
Try this
Its Void not void in parameter of AsyncTask
You need to change your onPostExecute() method just pass String parameter in onPostExecute() method
Change your code like below code
SAMPLE CODE
private void register(String name,String usn,String addnum,String pass,String repass) {
String urlsuffix = "?name=" + name + "&usn=" + usn + "&ddnum=" + addnum + "&pass=" + pass + "&repass=" + repass;
//Getting **illegal start of type** for void keyword here
class RegisterUser extends AsyncTask<String, Void, String> implements abcd.project2.RegisterUser {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(signupActivity.this, "please wait", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
}
RegisterUser ur = new RegisterUser();
ur.execute(urlsuffix);
}
You can read more about AsyncTask
change word "void" to Void in the line of class RegisterUser extends AsyncTask <String, void, String> implements abcd.project2.RegisterUser
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask { ... }
refer this Official document site :
1.Change void to Void
2.change your onPostExecute()
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), "Internet not found", Toast.LENGTH_SHORT).show();
}

sqlite database inserts the same value everytime error

Am displaying random checkboxes from remote server and if a user checks a checkbox then am storing that value in sqlite database and on the next loading am checking whether that value is present in database or not and if its present then bydefault it will check the checkbox. my problem is everytime i try to insert a value to sqlite it always takes the first checked checkbox value. But if I use a toast to check my code am getting the respective checkbox value. but that doesn't work with sqlite
Here is how am displaying a checkbox and setting on clicklistener
rl = (LinearLayout) getView().findViewById(R.id.linearmain);
HashMap<String, String> resultp = new HashMap<String, String>();
sqlcon = new SQLController(context);
sqlcon.open();
CheckBox[] cb = new CheckBox[arraylist.size()];
Cursor c = sqlcon.readEntry();
int rows = c.getCount();
int cols = c.getColumnCount();
for(int i = 0; i < arraylist.size(); i++) {
resultp = arraylist.get(i);
cb[i] = new CheckBox(getActivity());
cb[i].setText(resultp.get(Fltrsubfragment.SUB));
cb[i].setId(i);
cb[i].setOnClickListener(handleOnClick(cb[i]));
rl.addView(cb[i]);
for ( int ikv = 0; ikv < rows; ikv++) {
// inner for loop
for (int j = 0; j < cols; j++) {
String iv;
iv=c.getString(j);
if(iv==null){
Toast.makeText(context, " Empty " + rows, Toast.LENGTH_LONG).show();
}
else if(iv.equals(cb[i].getText().toString())){
cb[i].setChecked(true);
Toast.makeText(context, " Checked " + rows, Toast.LENGTH_LONG).show();
}
else{
cb[i].setChecked(false);
}
}
}
View.OnClickListener handleOnClick(final CheckBox button) {
return new View.OnClickListener() {
public void onClick(View v) {
if(button.isChecked()){
if(barraylist.contains(button.getText().toString())){
Toast.makeText(context, " Already added " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
else {
brandarraylist.add(button.getText().toString());
name=button.getText().toString();
new MyAsync().execute();
Toast.makeText(context, " Stored " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
}
else{
if(barraylist.contains(button.getText().toString()))
{
barraylist.remove(button.getText().toString());
name=button.getText().toString();
new MyAsyncS().execute();
sqlcon.deleteTData(button.getText().toString());
Toast.makeText(context, "Removed this " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Unchecked this " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
}
}
};
AsyncTask code to insert value
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
PD = new ProgressDialog(context);
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
if(name==null){
return null;
}
// inserting data
else{
sqlcon = new SQLController(context);
sqlcon.open();
sqlcon.insertData(name);
sqlcon.close();
// BuildTable();
return null;
}
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
here is the insertData code
public void insertData(String name) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(MyDbHelper.LT_VAL, name);
database.insert(MyDbHelper.LTE, null, cv);
}
Please suggest where am making the mistake.
Inside new MyAsync().execute(); put name:
I recommend using .trim() on all user input. You could easily chain this to:
name=button.getText().toString().trim();
new MyAsync().execute(name);
Then get it by using:
#Override
protected String doInBackground(String... params) {
String name = params[0];
We ruled out context by changing the code to:
#Override
protected String doInBackground(String ... params) {
String name = params[0];
if(name==null){
return null;
}else{
return name;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
sqlcon = new SQLController(context);
sqlcon.open();
sqlcon.insertData(result);
sqlcon.close();
// BuildTable();
PD.dismiss();
}

I need to run several AsyncTask in Android but only when before task has been terminated

I need to run several times the same AsyncTask in Android (passing a different file parameter to download from FTP server), but I need one after other, not in parallel, I want just do this one at time, Doing one when the other one has been terminated/finished.
So far I have this code, but it's no working properly, last task never ends:
private class FtpTask extends AsyncTask<String, Void, Integer> {
private String msg = "";
private String bean = "";
public FtpTask(String msg, String bean) {
this.msg = msg;
this.bean = bean;
}
protected void onPreExecute() {
showProgress(true, "Syncronizing", "Processing " + msg + ", wait...");
}
#Override
protected Integer doInBackground(String... params) {
if (bean.trim().equals("")) {
bean = params[0];
}
String file = Util.getMapFiles().get(bean);
int total = 0;
try {
FtpServerUtil ftp = new FtpServerUtil();
ArrayList<String> fileRows = ftp.lerArquivo(file);
total = insertRecords(bean, fileRows);
} catch (IOException e) {
Log.e(Const.TAG, "Lendo arquivo no FTP", e);
}
if (total > 0) {
Util.setSharedPrefValue("data_sinc_" + bean.toLowerCase(), Util.dateTimeToStringBR(null), context);
}
return total;
}
protected void onPostExecute(Integer total) {
showProgress(false, null, null);
String msg = "";
if (total > 0) {
msg = total + " records [" + bean + "] sincronized";
} else {
msg = "No records...";
}
Util.showToast(msg, activity);
}
}
...
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void StartAsyncTaskInParallel(FtpTask task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
task.execute();
}
}
..
FtpTask ftpTask1 = new FtpTask("Clientes","Cliente");
FtpTask ftpTask2 = new FtpTask("Médicos","Medico");
StartAsyncTaskInParallel(ftpTask1);
StartAsyncTaskInParallel(ftpTask2);
How could I achieve that?
You need to start next AsyncTask in Previous AsyncTask's onPostExecute:
Call ftpTask2 in onPostExecute of ftpTask1
Call ftpTask3 in onPostExecute of ftpTask2
Call ftpTask4 in onPostExecute of ftpTask3
...
To implement this, you can use Java Queue to maintain the list of AsyncTask remaining.
Sample code:
private class FtpTask extends AsyncTask<String, Void, Integer> {
// ...
private Queue<FtpTask> queue;
public FtpTask(String msg, String bean, Queue<FtpTask> queue) {
// ...
this.queue = queue;
}
protected void onPreExecute() {
}
#Override
protected Integer doInBackground(String... params) {
// ...
}
protected void onPostExecute(Integer total) {
// ...
FtpTask nextTask = this.queue.poll();
if (nextTask != null) {
nextTask.execute();
}
}
}
To use:
Queue<FtpTask> queue = new LinkedList<>();
queue.add ( asyncTask1);
queue.add ( asyncTask2);
queue.add ( asyncTask3);
queue.add ( asyncTask4);
FtpTask firstAsync = queue.poll();
firstAsync.execute();

ProgressDialog remains open in android activity

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) {
}

Categories

Resources