从另一个类存储和访问数组时,出现“ java.lang.NullPointerException:尝试从空数组读取”错误

时间:2018-08-07 17:57:39

标签: java android android-studio

我正在尝试从przezwiska访问位于data.java中的数组AlarmReciever。该数组用于访问数组中的随机位置,以生成通知。我导入了data文件,但是在编译并运行之后,我得到了java.lang.NullPointerException: Attempt to read from null array

我的AlarmReciever.java:

public void onReceive(Context context, Intent intent) {

    int x = (int) getRandomNumber();

    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(context, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
            context).setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("My title text "+ data.przezwiska[x] + data.sercoweOczyStr)
            .setContentText("My content text " + data.smileyStr).setSound(alarmSound)
            .setAutoCancel(true).setWhen(when)
            .setContentIntent(pendingIntent)
            .setVibrate(new long[]{500, 250, 250, 250});
    notificationManager.notify(0, mNotifyBuilder.build());
}

data.java:

package com.example.palidon.myapplication.Data;

public class data {


public static int kotekSerce = 0x1F63B;
public static int slonce = 0x1F31E;
public static int sercoweOczy = 0x1F60D;
public static int serce = 0x1F49E;
public static int zloteSerce = 0x1F49B;
public static int smiley = 0x1F60A;


public static String kotekSerceStr = getEmojiByUnicode(kotekSerce);
public static String slonceStr = getEmojiByUnicode(slonce);
public static String sercoweOczyStr = getEmojiByUnicode(sercoweOczy);
public static String serceStr = getEmojiByUnicode(serce);
public static String smileyStr = getEmojiByUnicode(smiley);

public static String[] przezwiska;

public static void main(String[] args) {

    przezwiska = new String[20];
    przezwiska[0] = "kotku! " + kotekSerceStr;
    przezwiska[1] = "słońce! " + slonceStr;
    przezwiska[2] = "kochanie! " + serceStr;
    }
}

1 个答案:

答案 0 :(得分:1)

将您的main()方法更改为静态初始值设定项。这个:

public static void main(String[] args) {

    przezwiska = new String[20];
    przezwiska[0] = "kotku! " + kotekSerceStr;
    przezwiska[1] = "słońce! " + slonceStr;
    przezwiska[2] = "kochanie! " + serceStr;
}

应该变成这样:

static {
    przezwiska = new String[20];
    przezwiska[0] = "kotku! " + kotekSerceStr;
    przezwiska[1] = "słońce! " + slonceStr;
    przezwiska[2] = "kochanie! " + serceStr;
}

您需要执行此操作,因为关于Android系统的所有操作都不会为您调用main()方法,因此您的数组将永远不会初始化。另一方面,将自动调用静态初始化程序块 ,因此当您尝试使用它时,数组将被正确初始化。