簡體   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