How can I name the intention in reverse order?

I want to display a new action on a successful callback of my WebService called by Retrofit. And it's hard for me to find examples of how to use the result of the Retrofit callback to start a new activity. Is this a good way to do this? Should I clean some things 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) {
            ...
        }
    });
}
+4
source share
2 answers

You can implement Callbackwith weak link toContext

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
    }

}  

- , Context , , , Context.

+7

, : getApplicationContext().

100% , , , .

:

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) {
            ...
        }
    });
}
+2

All Articles