如何在扩展Worker类并使其可用作字符串的线程中放置字符串数组资源?

时间:2019-04-15 09:01:57

标签: java android

我想通过将Worker线程放入String []数组中来使用Worker线程中的字符串数组资源,但是它在Logcat中为我提供了“空对象引用”结果。我该如何在不导致“空对象引用”的情况下将字符串数组资源获取到线程,并使数据可用作字符串?

MyWorker.java 扩展Worker类

public class MyWorker extends Worker {

    Context context = (Context) getApplicationContext();

    public DTipsDB myDb;
    int arrayIndex = 0;
    String[] tipsArray = context.getResources().getStringArray(R.array.tipsOfTheDay);




    @NonNull
    @Override
    public Result doWork() {
        myDb = new DTipsDB(getApplicationContext());
        StoreAndNotify();
        return Result.SUCCESS;
    }

    private int generateNum() {
        Random r = new Random();
        arrayIndex = r.nextInt(tipsArray.length);
        return arrayIndex;
    }

    private void StoreAndNotify() {
        myDb.addData(tipsArray[generateNum()]);
        int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
        Intent repeating_intent = new Intent(getApplicationContext(), DailyTips_Activity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
        stackBuilder.addNextIntentWithParentStack(repeating_intent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                .setContentIntent(resultPendingIntent)
                .setSmallIcon(R.drawable.lightbulbpng)
                .setContentTitle("Hackuna:Tip of the day!")
                .setContentText(tipsArray[generateNum()])
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(tipsArray[generateNum()]))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setAutoCancel(true);
        notificationManager.notify(m, builder.build());
    }
}

Logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
        at org.company.app.MyWorker.(MyWorker.java:23)

0 个答案:

没有答案