我正在使用loop4j来获取HttpAsync请求。
我正在调用片段中的请求:
RestHttpClientUsage.registerUser(m_context);
这是我的其余客户端代码:
public static void registerUser(Context context) throws JSONException
{
RestHttpClient.get("?Operation=RegisterUser" , params, new JsonHttpResponseHandler()
{
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
...
}
@Override
public void onFailure(int statusCode, Header[] headers,String responseString, Throwable throwable)
{
...
}
});
}
我的问题是如何从onSuccess / onFailure回调中访问调用片段?
我需要在调用完成后调用我的片段UpdateUI。
我可以以某种方式从上下文对象中获取片段吗?
答案 0 :(得分:2)
您可以使用私人BroadcastReceiver
来更新用户界面。这里是BroadcastReceiver
的声明:
public class MyFragment extends Fragment {
// Declare UI elements
private final BroadcastReceiver receiver = new MyBroadcastReceiver();
// Initialize elements in onCreate
@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("UPDATE_MY_FRAGMENT");
getActivity().registerReceiver(receiver, filter);
}
@Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(receiver);
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Read data from intent.getExtras()
// update UI elements
}
}
}
从intent
发送registerUser
到私人BrodcastReceiver
:
public static void registerUser(final Context context) throws JSONException
{
RestHttpClient.get("?Operation=RegisterUser" , params, new JsonHttpResponseHandler()
{
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
Intent intent = new Intent("UPDATE_MY_FRAGMENT");
// pass data using intent.putExtra based on response
context.sendBroadcast(intent);
}
@Override
public void onFailure(int statusCode, Header[] headers,String responseString, Throwable throwable)
{
Intent intent = new Intent("UPDATE_MY_FRAGMENT");
// pass data using intent.putExtra based on response
context.sendBroadcast(intent);
}
});
}
答案 1 :(得分:0)
您可以做的只是将响应(在这种情况下为json对象/数组)序列化为全局变量或POJO,然后您可以从loop4j上下文外部调用UI。
这对你有意义吗?
答案 2 :(得分:0)
因为它在UI线程上提供响应(你在UI上创建请求)我认为你可以这样做:
callingFragment.this.getActivity().getSupportFragmentManager().findFragmentBytag("your calling fragment tag").updatUI;