简体   繁体   中英

Arraylist Nullpointer exception with my app

heloo every one i have an application class with a static arraylist, and when i try to add an item to the arraylist i get nullpointer exception.. here is my code

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;
   }
}

now this is my service class

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;
}

can some1 help me??

SomeAppDid you you set you Application name in manifest file .

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

</application>

Add null checking before add UserIdname in ArrayList.

Check null in your ArrayList if it is null then recreate it.

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;
} 

Try this directly...

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

im conjuring your code, and running it under all scenarios.. so try this might work first of all remove the getters and setters.. you can access/set ids directly by

SomeApp.ids

and set it by

 SomeApp.ids = (another array)

because it is "public static" so no need for getters and setters
2:and also check if the string is empty or not before adding to the array

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

and change the UserIdname to userIdname.. like i did.. possible scenarios for nullpointer exception was from your getter or String..(im guessing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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