ActionBarSherlock change ProgressBar from external AsyncTask - android

I want to set ProgressVisibility(true) in an AsyncTask. Is the AsyncTask in the Main, all is fine.
public class GlanceActivity extends SherlockActivity implements ActionBar.OnNavigationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This has to be called before setContentView and you must use the
//class in com.actionbarsherlock.view and NOT android.view
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_glance);
}
public class TestTask extends AsyncTask<String, String, ArrayList<String>> {
#Override
public void onPreExecute() {
// Show IndeterminateProgressBar
setSupportProgressBarIndeterminateVisibility(true);
}
#Override
protected ArrayList<String> doInBackground(String... params) {
// Load some Data...
return null;
}
protected void onPostExecute(ArrayList<String> arg) {
// Hide IndeterminateProgressBar
setProgressBarIndeterminateVisibility(false);
}
}
}
But if I want to generate an Extra File for the AsyncTask, the setProgressBarIndeterminateVisibility is undefined for GroupPageTask...
How can I use this method in an seperate AsyncTask File?
GlanceActivity.java
public class GlanceActivity extends SherlockActivity implements ActionBar.OnNavigationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This has to be called before setContentView and you must use the
//class in com.actionbarsherlock.view and NOT android.view
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_glance);
}
}
GroupPageTask.java
public class GroupPageTask extends AsyncTask<String, String, ArrayList<String>> {
#Override
public void onPreExecute() {
// Show IndeterminateProgressBar
setSupportProgressBarIndeterminateVisibility(true);
}
#Override
protected ArrayList<String> doInBackground(String... params) {
// Load some Data...
return null;
}
protected void onPostExecute(ArrayList<String> arg) {
// Hide IndeterminateProgressBar
setProgressBarIndeterminateVisibility(false);
}
}

You could hand over the context during AsyncTask construction:
public class GroupPageTask extends AsyncTask<String, String, ArrayList<String>>
{
private Context context;
public AsyncTask(Context context)
{
this.context = context;
}
protected void onPreExecute()
{
((Activity) context).setProgressBarIndeterminateVisibility(true);
}
protected void onPostExecute(ArrayList<String> arg)
{
((Activity) context).setProgressBarIndeterminateVisibility(false);
}
}
Then create your AsyncTask with the new constructor from your activity:
GroupPageTask groupPageTask = new GroupPageTask(this);

With the Answer of Matt Handys, i found the right way...
GlanceActivity.java
public class GlanceActivity extends SherlockActivity implements ActionBar.OnNavigationListener {
public static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
GroupPageTask groupPageTask = new GroupPageTask(getSherlock());
}
}
GroupPageTask.java
public class GroupPageTask extends AsyncTask<String, String, ArrayList<Mannschaft>> {
private ActionBarSherlock sherlock;
#Override
public void onPreExecute() {
// Show IndeterminateProgressBar
sherlock.setProgressBarIndeterminateVisibility(true);
}
protected void onPostExecute(ArrayList<Mannschaft> arg) {
sherlock.setProgressBarIndeterminateVisibility(false);
}
}

Related

Android: call main activity method from Async onPostExecute method

Trying to call MainActivity method on onPostExecute(), but not getting any success. I tried so many things, but I think I am doing something wrong. processFinish() method on MainActivity is not called from onPostExecute().
//myClass.java
public class myClass extends Activity {
public AsyncResponse delegate=null;
public myClass(Context context){
this.mContext = context;
}
public interface AsyncResponse {
void processFinish(String output);
}
public class GetNotification extends AsyncTask<Integer, Void, String>{
public GetNotification() {
super();
}
#Override
protected String doInBackground(Integer... mArgs){
//code
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
delegate.processFinish(result);
}
#Override
protected void onPreExecute(){
}
}
public void getValue(int f){
m_flag = f;
if(Build.VERSION.SDK_INT >= 11){
new GetNotification().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, f);
}
else{
new GetNotification().execute(f);
}
}
}
//MainActivity.java
public class MainActivity extends Activity implements AsyncResponse{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code
}
#Override
public void processFinish(String output){
getComActivity(output);
}
private void getData(String mURL){
this.getUrl=new com.sample.myClass(this);
getUrl.getValue(1);
}
public void getComActivity(String gStr){
if (gStr != null && gStr.trim() != ""){
Intent mIntent = new Intent(this.getApplicationContext(), myActivity.class);
this.startActivity(mIntent);
}
}
}
You need to initialze delegate. Change the code in myClass constructor.
public myClass(Context context){
delegate = (AsyncResponse) context;
}
public GetNotification() {
super();
}
//In your AsyncTask class
//use MainActivity or myClass instead of Activity
private Activity activity;
public GetNotification(Activity activity) {
this.activity = activity;
}
private void callMethod()
{
activity.some_method();
}
public class myClass extends Activity {
public AsyncResponse delegate=null;
Context mContext;
public myClass(Context context){
this.mContext = context;
}
public interface AsyncResponse {
void processFinish(String output);
}
public class GetNotification extends AsyncTask<Integer, Void, String>{
public GetNotification() {
super();
}
#Override
protected void onPreExecute(){
//start dialog progress over here
}
#Override
protected String doInBackground(Integer... mArgs){
//code
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
delegate.processFinish(result);
}
}
#SuppressLint("NewApi")
public void getValue(int f){
int m_flag = f;
if(Build.VERSION.SDK_INT >= 11){
new GetNotification().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, f);
}
else{
new GetNotification().execute(f);
if( MainActivity.activity!=null)
MainActivity.getComActivity("PassYourStringOverHere"); //here I am giving example how to call MainActivity method from other activity
}
}
public class MainActivity extends Activity implements AsyncResponse{
private myClass getUrl;
public static Activity activity=null;
public static Context context=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity=this;//use to initialize the activity...later you can call...and start intent using this activity object...
context=this;//use for Intent...why I used this pattern because i made a static method so I have to do...or else it will show error...
//code
}
#Override
public void processFinish(String output){
getComActivity(output);
}
private void getData(String mURL){
this.getUrl=new com.sample.myClass(this);
getUrl.getValue(1);
}
public static void getComActivity(String gStr){
if (gStr != null && gStr.trim() != ""){
Intent mIntent = new Intent(context, myActivity.class);
activity.startActivity(mIntent);
}
}
}

Android - Function execute listener

Hey i don't know if that's the right way to do it but if it is how can i do it...
I have one abstact class with AsyncTask
public abstract class A{
A(){
new Task().execute();
}
public abstract void postAction();
private class Task extends AsyncTask<String, String, String>{
protected String doInBackground(String... args)
{
//smth
}
protected void onPostExecute(String file_url){
postAction();
}
}
}
After that i have class that extends A class and overrides it's postAction() method:
public class B extends A{
B(){
//smth
}
postAction(){
//some action
}
}
In my activity i have instance of B and i want to perform action when postAction is called... so i want function listener if possible and how can i do it
class C extends Activity{
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
//somethingggg happeiningggg
}
MyListener listener = new MyListener(){
onPostActionCalled()
{
//start another activity or smt :D
}
};
}
So i have class for json response(class A) and class B that extends it and overrides it's post method so i can do what i want for specific situation(expect different data or smth else nvm)
In my activity i want to perform action when class B's post method is called
I don't know if i need to do listener or handler idk at all....
Stefan is right, why complicate things?
See this real simple example of threading:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyTask(new TaskListener() {
#Override
public void finished(boolean result) {
// back on main thread after task finishes
}
}).execute();
}
private interface TaskListener{
void finished(boolean result);
}
private class MyTask extends AsyncTask<Object, Integer, Boolean>{
private TaskListener mListener;
public MyTask(TaskListener mListener) {
super();
this.mListener = mListener;
}
#Override
protected Boolean doInBackground(Object... params) {
// long running background operation
return true;
}
#Override
protected void onPostExecute(Boolean result) {
mListener.finished(result);
super.onPostExecute(result);
}
}
}

Calling AsyncTask from the Activity

For this code snippet( I have excluded the doInBackground(), postExecute() etc. )
How should I pass the Activity parameter while calling the Async Task from the CheckServer Activity?
public class CheckServer extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
HttpTicket ticket= new HttpTicket(); //HOW IS THIS LINE DONE? WHAT PARAM SHOULD BE PASSED?
}
#SuppressWarnings("unused")
private class HttpTicket extends AsyncTask<String, String, String>
{
private Activity activity;
private ProgressDialog dialog;
public HttpTicket(Activity activity) {
this.activity = activity;
}
You can sipmly do
HttpTicket mHttpTicket = new HttpTicket(this);
mHttpTicket.execute();
You could also delete the constructor, and just pass it to OnPreExecute as param. Then you give it in execute(this);
In your Activity onCreate()
HttpTicket ticket= new HttpTicket(Activity.this);
//passing context to the asynctask constructor
ticket.execute();
//call execute to laod asynctask
Define asynctask as below
private class HttpTicket extends AsyncTask<String, String, String>
{
private Activity activity;
private ProgressDialog dialog;
public HttpTicket(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
dialog.setTitle("Wait...");
}
protected void onPreExecute()
{
dialog.show();
}
protected String doInBackground(String params)
{
//background opearation
return "string";
}
protected void onPostExecute(String result)
{
dialog.dismiss();
//update ui
}
}

AsyncTask for showing dialog

How can i use AsyncTask Class to showing dialog when execute a task???
class TestAsynTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
ProgressDialog.show(???, null, null);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
Assuming that TestAsyncTask is an inner class to an Activity, then you can use the activity name .this to get the context. If TestAsyncTask is not an inner class, then you will want to pass an instance of your Activity into the constructor so that you can provide it as the Context to the ProgressDialog.show() method.
Here is an example of the inner class method:
class MyActivity extends Activity {
//Activity Lifecycle methods
class TestAsynTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MyActivity.this, "title", "message");
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//very long computation...
return null;
}
#Override
protected void onPostExecute(Void void) {
dialog.cancel();
}
}
}
You will notice that you should save off the ProgressDialog to a instance variable in the onPreExecute() method and call cancel() on it in the onPostExecute() method.
The other approach looks similar:
class MyActivity extends Activity {
//Activity Lifecycle methods
}
class TestAsynTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
MyActivity activity;
TaskAsynTask(MyActivity activity) {
this.activity = activity;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(activity, "title", "message");
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//very long computation...
return null;
}
#Override
protected void onPostExecute(Void void) {
dialog.cancel();
}
}

Finish the calling activity when AsyncTask completes

My calling activity:
public class Hello extends Activity {
public void onCreate(Bundle savedInstanceState) {
MyTask mt = new MyTask(this);
mt.execute();
}
Now In MyTask (an external class):
public class MyTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
public MyTask(Context context) {
mContext = context;
}
//doinbackground, etc
protected void onPostExecute() {
mContext.finish();
}
Other things are working as expected if I remove mContext.finish() above.
But if I'm calling mContext.finish() , I'm getting an error: The method finish() is undefined for the type Context (Eclipse doesn't show finish() when I write mContext. so that suggests I'm using finish() wrongly.)
What do I need to do to finish the calling activity Hello after MyTask completes the task
((Activity)mContext).finish();
Would be the correct way to cast a Context to an Activity and call its finish() method. Not sure why you'd want to finish an Activity from an AsyncTask though
What you can try to do instead of calling context.finish(), why don't you do a callback interface like this:
public interface TaskCallback{
void done();
}
Then you implement this into your Activity
public Hello extends Activity implements TaskCallback{
.....BUNCH OF ACTIVITY CODE.....
public void onCreate(Bundle savedInstanceState) {
MyTask mt = new MyTask(this);
mt.execute();
}
public void done() {
finish();
}
}
And instead of having Context as a parameter you have TaskCallback
public class MyTask extends AsyncTask<Void, Void, Void> {
private TaskCallback mCallback;
public MyTask(TaskCallback callback) {
mCallback = callback;
}
//doinbackground, etc
protected void onPostExecute() {
mCallback.done();
}
There you go, it gives you more flexibility to custom each implementation.
I got the same situation, then I do as follows:
public class MyTask extends AsyncTask<Void, Void, Void> {
private Activity mActivity;
private Context mContext;
public MyTask(Activity activity) {
mActivity = activity;
mContext = mActivity.getApplicationContext();
}
//doinbackground, etc
protected void onPostExecute() {
mActivity.finish();
}
Hope it help :)
Define a method in your activity class like this:
public void FinishAfterAsyncTask()
{
this.finish();
}
And call this method from the OnPostExecute method of the AsynTask class.
You could create a new private AsyncTask extended from your public one.
In this private AsyncTask you have access to the Activity stuff and you can override the onPostExecute method to finish it.
Your truly AsyncTask
public class MyPublicAsyncTask extends AsyncTask<Void, Void, Void> {
Context context;
public GetHorariosAsyncTask(Context ctx){
context = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// prepare yourself for an async work
}
#Override
protected Void doInBackground(Void... params) {
// Do yout cool async stuff
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// you're finish, let's tell to user
}
}
Your Activity with private AsyncTask
public class MyActivity extends Activity {
Activity mAct;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mAct = this;
}
private class MyPrivateAsyncTask extends MyPublicAsyncTask {
public MyPrivateAsyncTask(Context ctx) {
super(ctx);
// TODO Auto-generated constructor stub
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// our async task is completed! let's take care of this activity
mAct.finish();
}
}
}
Can you try
this.finish()
Seems like its because of calling it using mContext that it says undefined.

Categories

Resources