使用JSON将String与今天的日期进行匹配

时间:2013-11-19 21:22:12

标签: java android json

我有以下JSON文件:

[
    {   
        "Date" : "11182013",
        "Quote" : "Today Is Monday",
        "By" : "SiKni8"
    },
    {   
        "Date" : "11192013",
        "Quote" : "Today Is Tuesday",
        "By" : "SiKni8"
    }
]

我的Java代码可以在这里找到: http://pastebin.com/9Wta9GYh

代码:

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 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.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;

    @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++) {
            int 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);

            views.setTextViewText(R.id.tvParkStatus, "Alternate Parking is Suspended");


            // 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, Void> {
         @Override
         protected Void 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 null;
         }

         @Override
         protected  void onPreExecute() { //Activity is on progress
         }

         @Override
        protected void onPostExecute(Void v) {
             try {
                 jsonArray = new JSONArray(result);
                    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");
                    } // End the for loop
                    views.setTextViewText(R.id.tvToday, date[0]);
             }
             catch (JSONException e) {
                 e.printStackTrace();
             }
        }
    }
}

我正在尝试在窗口小部件TextView中显示日期,但我收到的是带有以下LogCat的FC:

11-19 16:18:15.226: E/AndroidRuntime(1562): FATAL EXCEPTION: main
11-19 16:18:15.226: E/AndroidRuntime(1562): java.lang.NullPointerException
11-19 16:18:15.226: E/AndroidRuntime(1562):     at com.test.dailyhadith.testing$GetJSON.onPostExecute(testing.java:134)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at com.test.dailyhadith.testing$GetJSON.onPostExecute(testing.java:1)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at android.os.AsyncTask.finish(AsyncTask.java:631)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at android.os.Looper.loop(Looper.java:137)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at java.lang.reflect.Method.invokeNative(Native Method)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at java.lang.reflect.Method.invoke(Method.java:511)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-19 16:18:15.226: E/AndroidRuntime(1562):     at dalvik.system.NativeStart.main(Native Method)

我该如何解决?

1 个答案:

答案 0 :(得分:1)

这与JSON无关。您永远不会初始化String [] date数组。

你需要的东西......

date = new String[jsonArray.length()];