我正在尝试将JSON HTTP请求与窗口小部件一起使用,但没有任何事情发生在控制台上的消息
d/dalvikvm:GC_Concurrent Freed 366K,5%免费10713K/11207K,暂停了5ms 30ms v/asynchttprh:进度183,从121(151%)
请参阅Bellow代码
public class MyWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int count = appWidgetIds.length;
for (int i = 0; i < count; i++) {
int widgetId = appWidgetIds[i];
String number = getCurrentPrice();
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.bitcoin_widget);
remoteViews.setTextViewText(R.id.textView, number);
Intent intent = new Intent(context, MyWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
String value = "0.00";
private String getCurrentPrice() {
value = "0.00";
String url = "https://www.mywebservice.net/stock/";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String data= new String(responseBody, "UTF-8");
JSONObject res = new JSONObject(data);
JSONObject obj = res.getJSONObject("values");
String last = obj.getString("stock");
value = last;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("STK", error.getMessage());
}
});
return String.format("USD %.2f",Double.parseDouble(value));
}
return string.format(" USD%.2F",double.parsedouble(value));
因为client.get()
是一个异步调用,因此它立即执行并转到返回语句。这就是为什么您看不到更改的原因,因为value
仍然是0。将返回放入onSuccess()
中。您还需要从onFailure()
返回一个值。
编辑
由于Onsuccess是无效的,因此您需要通过回调,该回调将在解析后打电话。
interface ResponseCallback {
void success(String value);
}
然后,
getCurrentPrice(new ResponseCallback() {
@Override
void success(String value) {
remoteViews.setTextViewText(R.id.textView, value);
}
}
getCurrentPrice(不要返回值) -
private void getCurrentPrice(ResponseCallback callback) {
...
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
...
String last = obj.getString("stock");
callback.success(last);
} catch(...)
}