当前位置: 首页 > 面试题库 >

使用JSON将字符串与今天的日期匹配

董翰池
2023-03-14
问题内容

我有以下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的功能表:

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)

我该如何解决?


问题答案:

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

您需要一些类似…

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


 类似资料:
  • 获取今天的日期(年、月、日) 用法 Your browser does not support the video tag. 案例:小闹钟 功能:2019年12月25日,播放圣诞快乐歌

  • 问题内容: 我已经编写了一些代码来检查两个日期,即开始日期和结束日期。如果结束日期早于开始日期,则会提示您结束日期早于开始日期。 我还想添加检查开始日期是否在今天之前(今天和用户使用该应用程序的那天一样)。(下面的日期检查器代码,如果有任何影响,那么所有这些都为Android编写) 问题答案: 这有帮助吗?

  • 问题内容: 我有以下 我想将此日期与今天的日期进行比较(即我想知道这是今天之前还是今天之前) 我需要使用什么功能? 问题答案: 将其转换为时间值 给你几秒钟 将检查是否已在最后一天之内。

  • 我是Java新手,尝试使用Calendar对象来获取now的日期和时间字符串。我特别关注对象和对象转换。

  • 问题内容: 将日期转换为JSON时,javascript会以以下格式保存日期: 但是,我不确定如何将其放入python datetime对象。我已经尝试过这些: 我相信javascript会将字符串保存为官方ISO格式,因此似乎应该有一种方法可以让python 读取它? 问题答案: 请尝试以下格式: 例如: 该的日期只是手段,它应该被解释为UTC时间,所以忽略它不会造成任何信息丢失。您可以在这里找

  • 问题内容: 我有以下方法,如果没有别的,我想缩短或更短时间。欢迎所有评论: 贝娄方法采用日期对象,对其进行格式化(“ EEE hh:mma MMM d,yyyy”),然后确定日期是今天还是昨天,如果不是,则返回“((昨天|今天))hh:mma ”格式的字符串。 问题答案: 您可以通过以下方法使用标准API进行改进: 这是使用Jodatime的方法: