How do I send exception to callback in Android? -
i have class (named c) check structure of json , if structure wrong, throws exception. class called class b. can use try catch
in class b. actually, class b called class a, provide callback class b. how send exception class c called class b callback (onfinishlistener
) in class a? want provide try catch
in callback declaration in class a, not class b.
public class { b b = new b(); b.getresponsefromserver(new b.onfinishlistener { @override public void onfinish(object response) { }); } public class b { public static interface onfinishlistener { void onfinish(object response); } //other code public void getresponsefromserver(onfinishlistener onfinishlistener) { response.listener<jsonobject> listener = new response.listener<>() { @override public void onresponse(jsonobject response) { try { onfinishlistener.onfinish(c.somemethod(response); catch (jsonexception e) { log.e("error", e.getmessage()); } } } //do volley tasks } } public class c { public static object somemethod(jsonobject json) throws jsonexception { if (json.has("something")) { //return } else { throw new jsonexception("error"); } } }
i got solution. need add 1 method interface (onexception) , deliver exception interface on catch(exception)
.
public class { b b = new b(); b.getresponsefromserver(new b.onfinishlistener { @override public void onfinish(object response) {} @override public void onexception(jsonexception response) {} ); } public class b { public static interface onfinishlistener { void onfinish(object response); void onexception(jsonexception e); } //other code public void getresponsefromserver(onfinishlistener onfinishlistener) { response.listener<jsonobject> listener = new response.listener<>() { @override public void onresponse(jsonobject response) { try { onfinishlistener.onfinish(c.somemethod(response); catch (jsonexception e) { onfinishlistener.onexception(e); } } } //do volley tasks } }