我有一个主页小部件,它应该“显示”从我的服务器上从JSON文件中提取的文本,但它没有显示任何内容。
我的Java代码:
package com.test.testing
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Locale;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class DisplayHadith extends AppWidgetProvider {
public static String CLOCK_WIDGET_UPDATE = "CLOCK_WIDGET_UPDATE";
Calendar c = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("LLDyyyy", Locale.US);
DefaultHttpClient httpclient;
HttpPost httppost;
InputStream inputStream = null;
String result = null;
StringBuilder sb;
JSONArray jsonArray;
String[] date, quote, by;
RemoteViews views;
int appWidgetId;
String t1, t2;
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
}
//new GetJSON().execute(null, null, null);
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
Log.i("ExampleWidget", "Updating widgets " + Arrays.asList(appWidgetIds));
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
appWidgetId = appWidgetIds[i];
// Create an Intent to launch MainActivity
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
views = new RemoteViews(context.getPackageName(),
R.layout.widgetlayout);
views.setOnClickPendingIntent(R.id.ivCal, pendingIntent);
views.setOnClickPendingIntent(R.id.tvParkStatus, pendingIntent);
views.setOnClickPendingIntent(R.id.tvToday, pendingIntent);
new GetJSON().execute();
views.setTextViewText(R.id.tvToday, t1);
views.setTextViewText(R.id.tvParkStatus, t2);
// Tell the AppWidgetManager to perform an update on the current app
// widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
public class GetJSON extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/hadith.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
@Override
protected void onPreExecute() { //Activity is on progress
}
@Override
protected void onPostExecute(String result) {
try {
df.format(new Date());
jsonArray = new JSONArray(result);
date = new String[jsonArray.length()];
quote = new String[jsonArray.length()];
by = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject) jsonArray.get(i);
date[i] = jsonObj.getString("Date");
quote[i] = jsonObj.getString("Quote");
by[i] = jsonObj.getString("By");
Log.i("DATE", date[i]);
Log.i("QUOTE", quote[i]);
Log.i("BY", by[i]);
} // End the for loop
t1 = date[0];
t2 = quote[0];
//views.setTextViewText(R.id.tvToday, date[0]);
//views.setTextViewText(R.id.tvParkStatus, quote[0]);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
}
我的小部件XML:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="@dimen/app_min_width"
android:minHeight="@dimen/app_min_height"
android:updatePeriodMillis="200"
android:initialLayout="@layout/widgetlayout" >
<!-- hourly check -->
</appwidget-provider>
我的XML布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="@drawable/background" >
<ImageView
android:id="@+id/ivCal"
android:layout_width="@dimen/cal_icon_size"
android:layout_height="@dimen/cal_icon_size"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#FF0000" />
<LinearLayout
android:id="@+id/llTexts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:layout_toRightOf="@+id/ivCal"
android:weightSum="2" >
<TextView
android:id="@+id/tvToday"
android:layout_width="match_parent"
android:layout_height="0dp"
android:textSize="@dimen/date_text_size"
android:textStyle="bold"
android:paddingLeft="@dimen/text_padding_left"
android:text=""
android:gravity="center"
android:layout_weight="1.6"
android:background="#FFFFFF"
android:textColor="#000000" />
<TextView
android:id="@+id/tvParkStatus"
android:layout_width="match_parent"
android:layout_height="0dp"
android:textSize="@dimen/status_text_size"
android:textStyle="bold"
android:paddingRight="@dimen/text_padding_right"
android:text=""
android:gravity="center_vertical|right"
android:layout_weight="0.4"
android:background="#00FF00"
android:textColor="#CC0000" />
</LinearLayout>
</RelativeLayout>
Log
显示从JSON文件中提取的信息,但我的小部件没有显示任何内容。
请帮忙......
答案 0 :(得分:1)
您正在运行AsyncTask,这是一个线程,然后更新您的小部件。你永远不会以这种方式得到数据。在加载数据之前,对AsyncTask的调用不会等待。一种简单的方法是使用服务来获取JSON数据。将该信息写入本地数据库,然后让您的小部件知道数据库中有新项目要更新。
老实说,我认为这是最好的方法。