我正在编写解析和显示JSON内容的简单小部件。
小部件在布局中只有一个TextView。我不想自动更新。用户单击此文本后,Widget将更新TextView。
我开始使用Android编程。这是我的第一个应用程序。
现在我有了这段代码:
public class MainActivity extends AppWidgetProvider {
String temperature;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i = 0; i < appWidgetIds.length; i++) {
int currentWidgetId = appWidgetIds[i];
String url = "http://example.net/json.php";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse(url));
PendingIntent pending = PendingIntent.getActivity(context, 0,
intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.activity_main);
views.setOnClickPendingIntent(R.id.textView1, pending);
/*
try {
String a = "{ \"temperature\": 4.3\" }";
JSONObject reader = new JSONObject(a);
String x = reader.getString("temperature");
Log.i("temperature", x);
views.setTextViewText(R.id.textView1, x);
} catch (JSONException e) {
e.printStackTrace();
}
*/
fetchJSON(url);
views.setTextViewText(R.id.textView1, temperature+new Date().getSeconds());
appWidgetManager.updateAppWidget(currentWidgetId, views);
Toast.makeText(context, "widget added", Toast.LENGTH_SHORT).show();
}
}
public void fetchJSON(final String url) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL u = new URL(url);
HttpURLConnection urlConn = (HttpURLConnection) u
.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
InputStream in = httpConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(1000);
int read = 0;
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
while (true) {
read = bis.read(buffer);
if (read == -1) {
break;
}
baf.append(buffer, 0, read);
}
String queryResult = new String(baf.toByteArray());
JSONObject jsonObject = new JSONObject(queryResult);
temperature = jsonObject.getString("temperature");
Log.i("TEMP", temperature);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
如果我在String中使用JSON取消注释部分,则会在窗口小部件上将字符串写入TextView - 确定。
在模拟器中运行app后,我看到“null3”。 3秒是秒。如果我点击widget,android打开浏览器窗口但不更新widget文本。我仍然看到“null3”。在控制台中,我看到“TEMP”条目具有正确的值。
可能只更新小部件的文本而不打开网络浏览器?
答案 0 :(得分:0)
这是因为当您在Thread
中设置文字时,TextView
尚未运行。你必须等待。看看Asynctask,这是特别针对像你这样的任务。您可以更新onPostExecute()