2

hi all i have an arraylist and array in an activity and have two function. i declared arraylist and array in activity and used in a function. but i cannot access in those variables in second function. both function is in same activity. in second function gives NullPointerException in Logcat. code:

public class testapplication extends Activity {
 ArrayList<String> getdatabase = new ArrayList<String>();
 public  String[] array;
 protected void onStart() {
      getdatabase.add("1");
      getdatabase.add("2");
      array=new String[getdatabase.size()];
      getdatabase.toArray(array);
      Log.e("app",""+array.length()); // print as app  2

   }

 public void onCreate(Bundle savedInstanceState) {

 Log.e("app",""+array.length()); // NullPointerException.
 }

}

please help me.

2
  • Are you sure that onStart is running before onCreate? Commented Apr 26, 2011 at 7:15
  • According to Activity life cycle,onCreate is called before onStart, so you do the code in onCreate rather than onStart() and i want to know any particular reason for doing it in onStart() Commented Apr 26, 2011 at 8:34

3 Answers 3

3

The problem is that onCreate() is the method that is first called if your Activity starts. At this point, you haven't yet initialized your variable array. That's why you get a NullPointerException there.

To solve the problem you have to assure that you call this:

array=new String[getdatabase.size()];

before you try to access the array.

As coder_tim pointed out, in the documentation you can clearly see that onCreate() is always called before onStart().

Sign up to request clarification or add additional context in comments.

2 Comments

Good link, there you can see that onStart is always called after onCreate.
0

onStart() is called after onCreate(), so array is not created yet. See here.

Comments

0

Referencing to Android activity life cycle, onCreate is called before onStart, that's why you got NullPointerException Besides, just a heads up. You should call super.onCreate and super.onStart somewhere in the methods you overrided.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.