Calling static Async task from other fragment - android

I am trying to call Async task in some other activity from a fragment. I tried to call various way but none of it worked. I just want to know whats the best way to call static AsyncTask .Here is my Async task:
static class MyAsync extends AsyncTask<Void, Void, Void> {
Context context;
String username, password;
private MyAsync(Context context, String username, String password) {
this.context = context;
this.username = username;
this.password = password;
}
ProgressDialog dialog;
private String response;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "Connecting to Server","Getting Credentials"
, true);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
ContentDownload download = new ContentDownload();
response = download.loginApi(agentId, password);
if(response.contains("Success")){
if(SettingHelper.getFirstCall(context)){
ContentDownload.CallApi(context);
SettingHelper.setFirstCall(context, false);
}
if(SettingHelper.getFirstLaunch(context)){
ContentDownload load = new ContentDownload();
load.callItemApi(context);
load.callActionApi(context);
SettingHelper.setFirstLaunch(context, false);
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(response.contains("Success")){
context.startActivity(new Intent(context, AllActivity.class));
}else{
Toast.makeText(context, "Got back", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}}
I am trying to call it this way:
LoginActivity.new MyAsync(getActivity).execute();
but its giving error

It you want to use this class from your Fragment, give it public visibility, also a public constructor and then you can call it:
new LoginActivity.MyAsync(getActivity())

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

AsyncTask not working inside ViewPager

I am having problem with AsyncTask class inside ViewPager's Fragment.
I have added code like below inside ViewPager's 3rd Fragment:
private View.OnClickListener finishClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
UserIdAsyncTask userIdAsyncTask = new UserIdAsyncTask( getActivity(), "URL", "Test", "Value" );
userIdAsyncTask.execute();
Her is my UserIdAsyncTask class:
private class UserIdAsyncTask extends AsyncTask<Void, Void, String> {
String url = "";
String oldpass = "";
String newpass = "";
private Context mContext = null;
private ProgressDialog dialog;
public UserIdAsyncTask( Context context, String url, String oldPass, String newPass ) {
this.mContext = context;
this.url = url;
this.oldpass = oldPass;
this.newpass = newPass;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(this.mContext, "", "Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String str = "";
try {
return str;
} catch (Exception e) {
Log.e(ThirdFrag.class.toString(), e.getMessage(), e);
}
return str;
}
#Override
protected void onPostExecute(String response) {
dialog.dismiss();
Intent i = new Intent(getActivity(), ABC.class);
startActivity(i);
getActivity().finish();
}
}
In the given code, onPreExecute() called but doInBackground() never called.
Any ideas anyone? I'm really struggling with this one.

Android - Dialog dismiss

I have created a simple login where the user enters his details and using AsyncTask it comapares user input to SQLite database if its correct it will start intent of Main activity.
Problems:
Loading progressDialog doesnt dismiss if the user password/username is incorrect but shows the else statement toast when incorrect password/username
In the Login class on the OnClick i have declared a new LoginTask of the users input here is my AysncTask
private static class LoginTask extends AsyncTask<Void, Void, Boolean> {
ProgressDialog pd;
String username, password;
private final Context context;
Intent log;
// private final WeakReference<Context> reference;
private LoginTask(Context context, String username, String password) {
this.context = context;
this.username = username;
this.password = password;
//final Context context = this.context;
//Controller handler = new Controller(this.context);
pd = new ProgressDialog(this.context);
}
protected void onPreExecute() {
//super.onPreExecute();
pd.show(this.context,"Authenticating account ...", "Please wait ...");
pd.setCanceledOnTouchOutside(false);
}
#Override
protected Boolean doInBackground(Void... p) {
//final Context context = this.context;
Controller handler = new Controller(this.context);
handler.open();
if (!handler.executeLog(username.trim(), password.trim())){
return false;
} else {
return true;
}
}
#Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
// super.onPostExecute(result);
// final Context context = this.context;
Controller handler = new Controller(this.context);
handler.open();
if (result == false) {
Toast.makeText(context, "Failed, Incorrect Username/Password", Toast.LENGTH_SHORT).show();
} else {
handler.close();
Intent log = new Intent(this.context, MainActivity.class);
context.startActivity(log);
((Activity)context).finish();
Toast.makeText(context, "You have successfully logged on, " + username, Toast.LENGTH_LONG).show();
}
}
}
}
Change this :
protected void onPreExecute() {
//super.onPreExecute();
pd.show(this.context,"Authenticating account ...", "Please wait ...");
pd.setCanceledOnTouchOutside(false);
}
By this:
#Override
protected void onPreExecute() {
// super.onPreExecute();
this.pd.setCanceledOnTouchOutside( false );
this.pd.setCancelable( true );
this.pd.setTitle( "Authenticating account ..." );
this.pd.setMessage( "Please wait ..." );
this.pd.show();
}

Start activity is slow

I'm write a music application online.But i'm meet a problem... A new activity starts slowly when I select an item in listview...
I don't know resolve, please help me ! :(
Sorry. I'm speak English very bad :(
This is my code:
public class startNewActivity extends AsyncTask<String, Void, String> {
private Activity activity;
private String selectDoc = "div.gen img";
private String attr = "title";
private String result;
public String Quality;
public startNewActivity(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... arg0) {
nameSong = (String) lvSong.getItemAtPosition(positionId);
link = linkSong.get(Integer.valueOf(obj.toString()));
Quality = Utils.getQuality(link, selectDoc, attr, result);
Log.i("Quality", Quality);
changeLink = link.replace(".html", "_download.html").substring(15)
.replaceFirst("", "http://download")
.replace("nhac-hot", "mp3".concat("/vietnam/v-pop"));
Log.i("Change link", changeLink);
try {
//Connect internet
linkIntent = Utils.getLinkPlay(selectLinkPlay, changeLink,
afterChangeLink);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Server has problem... Please while for minutes",
Toast.LENGTH_SHORT).show();
}
return linkIntent;
}
#Override
protected void onPostExecute(String result) {
//i'm want help here
Intent i = new Intent(SongActivity.this, PlayMusicActivity.class);
i.putExtra("song", linkIntent);
i.putExtra("namesong", nameSong);
i.putExtra("Quality", Quality);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
pDialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(SongActivity.this, "",
"Please wait...");
}
}
You're starting the new activity inside onPostExecute() which executes only after you've completed doInBackground(). Hence, the time delay.
Ideally, you should start the activity just after you execute your AsyncTask. The AsyncTask will continue in the background while your activity changes.

How to use Spinning or Wait icon when AsyncTask is being performed in Android?

I have used AsyncTask to retrieve data from my web services. I want to show some Spinning or Wait Icon masking while webservice is being processed. I have seen some solutions regarding this but they are very lengthy to write, my requirement is not to show how much percentage is left for complete processing, i just want to show an icon on processing the web service and it should dismiss when it is executed. I am calling this code from my activity and i want to show icon on my activity. See my code below. Please suggest some small and easy solution.
public class AsyncLoginWarden extends AsyncTask<String, Integer, String> {
protected String doInBackground(String...str) {
WebserviceCall wb = new WebserviceCall();
wb.param1 = str[0];
wb.param2 = str[1];
String response = wb.LoginWarden("LoginWarden");
return response;
}
protected void onPostExecute(String result) {
System.out.println("Successfully logged in."+result);
}
}
Updated Code
package com.example.trafficviolationreporter;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class AsyncLoginWarden extends AsyncTask<String, Integer, String> {
ProgressDialog pd;
Context co;
MainActivity ma;
String username, password;
public AsyncLoginWarden(MainActivity ma, String username, String password) {
this.ma = ma;
this.co = ma;
this.password = password;
this.username = username;
pd = new ProgressDialog(co);
}
#Override
protected void onPreExecute() {
this.pd.show();
super.onPreExecute();
}
protected String doInBackground(String... str) {
WebserviceCall wb = new WebserviceCall();
wb.param1 = str[0];
wb.param2 = str[1];
String response = wb.LoginWarden("LoginWarden");
return response;
}
protected void onPostExecute(String result) {
System.out.println("Successfully logged in." + result);
pd.dismiss();
}
}
You can create the progress dialog in preexcecute of your async class and dismiss in onpostexecute of async class. Here is how you will do this:
public class AsyncLoginWarden extends AsyncTask<String, Integer, String> {
ProgressDialog pd;
Context co;
YourActivity ma;
String username, password;
public AsyncLoginWarden(YourActivity ma, String username, String password) {
this.ma = ma;
this.co = ma;
this.password = password;
this.username = username;
pd = new ProgressDialog(co);
pd.setTitle("title");
pd.setMessage("message");
}
#Override
protected void onPreExecute() {
this.pd.show();
super.onPreExecute();
}
protected String doInBackground(String... str) {
WebserviceCall wb = new WebserviceCall();
wb.param1 = str[0];
wb.param2 = str[1];
String response = wb.LoginWarden("LoginWarden");
return response;
}
protected void onPostExecute(String result) {
System.out.println("Successfully logged in." + result);
pd.dismiss();
}
}
call your async class from activity:
YourActivity ma = this;
new AsyncLoginWarden(ma,username,password).execute();
ProgressDialog pDialog;
public class AsyncLoginWarden extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String...str) {
WebserviceCall wb = new WebserviceCall();
wb.param1 = str[0];
wb.param2 = str[1];
String response = wb.LoginWarden("LoginWarden");
return response;
}
protected void onPostExecute(String result) {
System.out.println("Successfully logged in."+result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
The above code will show a ProgressDialog during the background task and will dismiss it when the background task is completed.

Categories

Resources