Android Call more than one Web services in AsyncTask - android

I am working on AsynTask, single url call from AsynTask fine but i want to call two web services one after other in AsyncTask, can you please send some code or idea.
My code:
public class GetInstructionItems extends AsyncTask<String, Void, Boolean> {
public ProgressDialog myProgressDialog = null;
private Boolean authenticationResult = false;
private String LOG = SurgicalHistoryAsynTask.class.getName();
private String responseString = "getInstructionItemsResult";
JSONObject totalResult;
protected Boolean doInBackground(String... params)
{
return getRespose(params[0]);
}
protected void onPostExecute(Boolean result) {
myProgressDialog.dismiss();
if (result)
{
Log.d(LOG, "Response ::result "+result);
}else{
showAlertMsg(getString(R.string.response_fail));
}
}
protected void onPreExecute() {
if (!authenticationResult) {
myProgressDialog = new ProgressDialog(getActivity());
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
myProgressDialog.setMessage("loading...");
myProgressDialog.setCancelable(false);
myProgressDialog.setProgress(100);
myProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myProgressDialog.show();
}
}
private boolean getRespose(String inputUrl){
return true;
}
}

protected Boolean doInBackground(String... params)
{
getRespose(params[0]);
getRespose(params[1]);
getRespose(params[2]);
return true;
}
OR
class Responces
{
boolean r1, r2, r3;
}
protected Responces doInBackground(String... params)
{
Responces r = new Responces();
r.r1 = getRespose(params[0]);
r.r2 = getRespose(params[1]);
r.r3 = getRespose(params[2]);
return r;
}

Related

Android - AsyncTask inside Fragment doesn't work in Marshmallow

I created an AsyncTask to fetch scores. It shows the progressdialog for a split-sec and then disappears. The doInBackground method never gets executes. This task is called inside a fragment.
private class GetScore extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute() {
final ProgressDialog show = progressDialog.show(getActivity(), "", yourName);
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
scoreMap = ScoreCalc.getEngScore(yourName);
// Toast.makeText(LoveActivity.this, engageMap.toString(), Toast.LENGTH_SHORT).show();
return null;
}
#Override
protected void onPostExecute(String img) {
}
}
.
.
.
.
.
.
.
private void confirmYes() {
String s =mEditText.getText().toString();
if(s.equals(""))
return;
new GetScore().execute();
}
Help?
use this asynctask class instead of your class.
public class GetScore extends AsyncTask<String, Void, String>
{
String method;
#Override
protected String doInBackground(String... arg0)
{
method = arg0[0];
return getData.callWebService(arg0[0], arg0[1]);
}
protected void onPostExecute(String xmlResponse)
{
if(xmlResponse.equals("") )
{
try{
if(progDialog!=null && progDialog.isShowing()){
progDialog.dismiss();
}
}catch(Exception ex){}
Toast.
}
else
{
if (method.equals("methodname"))
{
MethodName(xmlResponse, "ResponseTag");
try{
if(progDialog!=null && progDialog.isShowing()){
progDialog.dismiss();
}
}catch(Exception ex){}
//What Ever Want to Do
}
}
}
}
}

get value from asynctask

I found many subject about but I can't get a solution, I'm doing a soap request in doInBackground method of asyncTask, and I want to get an Integer to know if the process is done, here I call my asyncTask:
Simulation.AsyncSoapCall task = new Simulation.AsyncSoapCall();
try {
Integer taskResult = task.execute().get();
} catch (Exception e) {
e.printStackTrace();
}
My AsyncTask class:
private class AsyncSoapCall extends AsyncTask<Void, Void, Integer> {
Integer result;
Boolean isInternetPresent = false;
Boolean isUrlAvailable = false;
ConnectionDetector cd;
AsyncSoapCall(){
}
#Override
protected Integer doInBackground(Void... params) {
cd = new ConnectionDetector(getActivity().getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
String namespace = getResources().getString(R.string.NAMESPACE);
String url = getResources().getString(R.string.URL);
String soapaction = getResources().getString(R.string.SOAP_ACTION);
String login = getResources().getString(R.string.login);
String mdp = getResources().getString(R.string.mdp);
isUrlAvailable = cd.isUrlAvailable();
// check for Internet status
if (isUrlAvailable) {
String idApplication = Installation.id(getActivity());
SOAPContact soapContact = new SOAPContact(namespace, url, soapaction, login, mdp);
soapContact.saveParams(getResources().getString(R.string.origine), db);
result = 1;
} else {
result = 2;
}
} else {
result = 3;
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
I don't get error my app crasha at this line:
Integer taskResult = task.execute().get();
try to get the value from onPostExecute like
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
int yourNum = result;
}
that's it
Did you read the doc?
https://developer.android.com/reference/android/os/AsyncTask.html
AsyncTask has no "get" method.
You need to define a OnPostExecute method which will be called when your task is over with your Integer as a parameter.
public class MyActivity extends Activity
{
private Integer myInteger;
private void blabla(){
Simulation.AsyncSoapCall task = new Simulation.AsyncSoapCall() {
#Override
protected void onPostExecute(Integer result) {
//... Your code here ...
MyActivity.this.myInteger = result;
MyActivity.this.myMethod(result);
}
}
try {
task.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void myMethod(Integer integer){
}
}
Here is one method with the help of interfaces,
MainActivity.java
public class MainActivity extends AppCompatActivity {
static String TAG=MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncSoapCall request = new AsyncSoapCall(new AsyncSoapCall.AsyncSoapInterface() {
#Override
public void callBack(String callBackValue) {
Log.d(TAG,callBackValue);
}
});
request.execute();
}
}
AsyncSoapCall.java
public class AsyncSoapCall extends AsyncTask<Void,Void,Void> {
interface AsyncSoapInterface{
void callBack(String callBackValue);
}
AsyncSoapInterface callbackObj;
AsyncSoapCall(AsyncSoapInterface callbackObj)
{
callbackObj = callbackObj;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
callbackObj.callBack("Your value");
}
}

Android Asyntask, second parameter is sending information before of first

I need to get the information of the Async methods using SOAP request, from "layer_1" before receiving the information from "layer_2", but sometimes it happens the other way round, is there any way to make "layer_2" wait for the end of "layer_1"?
Its my AsyncTask:
protected Void doInBackground(String... params) {
String ope = params[0];
switch (ope)
{
case "layer_1":
if(Util.isNetworkAvailable(mContext.getApplicationContext()))
{
getWebservice = WebService.getLayer(COD_MATRICULA);
changeAsync = true;
}
break;
case "layer_2":
if (Util.isNetworkAvailable(mContext.getApplicationContext())) {
if(canMade)
message = addUserWeb(User);
changeAsync = true;
callMessage = true;
}
else
{
message = null;
changeAsync = false;
}
break;
}
publishProgress();
return null;
}
and in my progressupdate:
protected void onProgressUpdate(Void... values) {
if (changeAsync)
verifyUser();
if(callMessage)
{
.......
callMessage = false;
}
}
You can used two asyncTask in your project like below
//layer_1
private class AsyncTaskRunner1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
if(Util.isNetworkAvailable(mContext.getApplicationContext()))
{
getWebservice = WebService.getLayer(COD_MATRICULA);
changeAsync = true;
}
}
#Override
protected void onPostExecute(String result) {
AsyncTaskRunner2 myTask = new AsyncTaskRunner2();
myTask.execute();
}
}
//layer_2
private class AsyncTaskRunner2 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
if (Util.isNetworkAvailable(mContext.getApplicationContext())) {
if(canMade)
message = addUserWeb(User);
changeAsync = true;
callMessage = true;
}
}
#Override
protected void onPostExecute(String result) {
}
}

prograss bar not displaying using AsyncTask in android

I just wrote a code that need to show progress bar when ever interacting with server.but it is not working if i call dismiss method in below code.
public class AsyncClass extends AsyncTask<String, String, String> {
String result;
public ProgressDialog progressbar;
static Context context;
public AsyncClass(Context context,String result) {
this.context = context;
this.result = result;
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
URI u = new URI(params[0]);
// url = Urls.SENDMOVIE_REQUEST_URL;
HttpGet HG = new HttpGet(u);
HttpResponse response = httpclient.execute(HG);
//httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(response.getEntity());
Log.d("result", result);
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPreExecute() {
progressbar = new ProgressDialog(context);
progressbar.setCancelable(true);
progressbar.setMessage("loading....");
progressbar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressbar.setProgress(0);
progressbar.show();
}
#Override
protected void onPostExecute(String result) {
progressbar.dismiss();
}
}
I think its not showing because of progressbar.setProgress(0);
just remove it & try.
And If you want progressUpdates you need to do like this:
private class DownloadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Edited Iqbal's answer
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(){
dialog = new ProgressDialog(HomeActivity.this);
dialog.setCancelable(false);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
/** * Write your code */
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
// display UI
}
}
}
Use this below code it shall do the job for you
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
/** * Write your code */
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
// display UI
}
}
}
Edit:
Add the initialization of progress bar in the constructor as
public AsyncClass(Context context,String result) {
this.context = context;
this.result = result;
progressbar = new ProgressDialog(context);
}
And remove it from internecine().

Android add a loading view to an AysncTask

Hi there i have an Asynctask that wroks only problem is the screen is blank until everything has loaded so i have created a loadingcell view but i'm wanting to know how to have it show the loading view until everything is loaded.
here what i have tried but it doesn't work
public class PostTask extends AsyncTask<Void, String, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
boolean result = false;
loadFixtures();
publishProgress("progress");
loadResultsFeed();
publishProgress("progress");
loadNewsFeed();
publishProgress("progress");
return result;
}
protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
loadingView = LayoutInflater.from(getBaseContext()).inflate(R.layout.loadingcell,
null);
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.v("BGThread", "begin fillin data");
FillData();
}
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.v("BGThread", "begin fillin data");
FillData();
// hide your view here <---------
// for ex:
progressbar.setVisibility(View.GONE); <---------
}
I have done this way. You can refer
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
downloadFile(b.getString("URL"));
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(ShowDescription.this,
"File successfully downloaded", Toast.LENGTH_LONG)
.show();
imgDownload.setVisibility(8);
} else {
Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
.show();
}
}
}
Try this.
private class BackgroundTask1 extends
AsyncTask<String, Void, String> {
private ProgressDialog dialog;
protected void onPreExecute() {
/** Initialise progress dialog and show*/
dialog = new ProgressDialog(currentActivity.this);
dialog.setMessage("Loading.....");
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(final String... args) {
// do your stuff
return anyString // as an example
}
protected void onPostExecute(String temp) {
Log.v("String:::::",temp);
dialog.dismiss(); // dismiss progress dialog
}
}

Categories

Resources