繁体   English   中英

我的应用程序出现Arraylist Nullpointer异常

[英]Arraylist Nullpointer exception with my app

heloo每个我都有一个带有静态arraylist的应用程序类,当我尝试将一个项目添加到arraylist时,我会得到nullpointer异常。这是我的代码

public class SomeApp extends Application {
   public static ArrayList<String> ids = new ArrayList<String>();
   //then i have getters and setters for ids..
   public static ArrayList<String> getIds() {
    return ids;
   }
   public static void setIds(ArrayList<String> ids) {
    SomeApp.ids = ids;
   }
}

现在这是我的服务班

public class BpA extends Service {
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
      // note i created a new thread so the below code could run in..       
      SomeApp.getIds().add(UserIdname);  // i get nullpointer exception on this line
      return START_STICKY;
}

有人可以帮我吗?

您已在清单文件中设置了SomeAppDid。

<application
        android:name="you_package.SomeApp"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >

</application>

在ArrayList中添加UserIdname之前,添加空检查。

在ArrayList中检查null是否为null,然后重新创建。

public class BpA extends Service {
 @Override 
 public int onStartCommand(Intent intent, int flags, int startId) {
      // note i created a new thread so the below code could run in..  
if(SomeApp.getIds() != null)      
      SomeApp.getIds().add(UserIdname);  // i get nullpointer exception on this line 
      return START_STICKY;
} 

直接尝试...

if(UserIdname != null){
    SomeApp.ids.add(UserIdname);
}

我正在召唤您的代码,并在所有情况下运行它。.因此,请尝试首先删除getter和setter的方法。您可以通过以下方式直接访问/设置ID:

SomeApp.ids

并设置为

 SomeApp.ids = (another array)

因为它是“公共静态”,所以不需要获取器和设置器
2:并在添加到数组之前检查字符串是否为空

if(userIdname != null && !userIdname.IsEmpty){
   SomeApp.ids.add(userIdname);
 }

并将UserIdname更改为userIdname ..像我一样.. nullpointer异常的可能情况是来自您的getter或String ..(我猜是)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM