Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call an intent in Retrofit Callback?

I want to display a new activity on success callback of my WebService called by Retrofit. And I have difficulties to find examples on how to use Retrofit callback result to launch new activity. Is that a good way to do it ? Do I have to clean up some stuff before?

public void validate(View view) {
    RetrofitWebServices.getInstance().webserviceMethod(params,new Callback<MyObject>() {
        @Override
        public void success(MyObject object, Response response) {
            Intent barIntent = new Intent(FooActivity.this, BarActivity.class);
            startActivity(barIntent);
        }

        @Override
        public void failure(RetrofitError error) {
            ...
        }
    });
}
like image 420
Labe Avatar asked Sep 04 '14 12:09

Labe


2 Answers

You can implement Callback with weak reference to Context

public class MyCallback implements Callback<MyObject> {

    WeakReference<Context> mContextReference;

    public MyCallback(Context context) {
        mContextReference = new WeakReference<Context>(context);
    }

    @Override
    public void success(MyObject arg0, Response arg1) {
        Context context = mContextReference.get();
        if(context != null){
            Intent barIntent = new Intent(FooActivity.this, BarActivity.class);
            context.startActivity(barIntent);
        } else {
            // TODO process context lost
        }
    }

    @Override
    public void failure(RetrofitError arg0) {
        // TODO process error
    }

}  

Just remember - this solution will not work if Context lost occurred while request in progress but you may don't worry about potential memory leak which may be if you keep strong reference to Context object.

like image 82
Viacheslav Avatar answered Oct 20 '22 10:10

Viacheslav


Hi have a solution that seems easier: use the getApplicationContext() function.

I am not 100% sure it is OK, but in my case it works as expected.

Your code would be:

public void validate(View view) {
    RetrofitWebServices.getInstance().webserviceMethod(params,new Callback<MyObject>() {
        @Override
        public void success(MyObject object, Response response) {
            Intent barIntent = new Intent(getApplicationContext(), BarActivity.class);
            startActivity(barIntent);
        }

        @Override
        public void failure(RetrofitError error) {
            ...
        }
    });
}
like image 21
bixente57 Avatar answered Oct 20 '22 10:10

bixente57