The correct way to create and initialize objects in android

I have several packages in my Android project containing several classes. When I want to create an object of a certain class in user interface activity, I used the method of creating a private object and initialized it to the method onCreate()where the user interface actions are in a separate package.

private SomeClass someClass = new SomeClass();

onCreate(Bundle savedInstanceState) {
   // Activity
}

I noticed that my senior programmers use a different method to declare an object before onCreate()and initialize it when the object is needed. What is the difference and suggest me the best way? I want me to be right if I am doing something wrong.

+4
source share
3

, , . . , . :

  • . , null, , .
  • , . . :
    String LOG_TAG = MyActivity.class.getSimpleName();
  • . , , , , . :

, .

0

- . nullpointer, . . , String:

String mystring;
//in some functions deep inside code
mystring = "hello world";//works great with string

:

StringBuffer mystring;
//in some functions deep inside code
mystring.append("hello world");

mystring = new StringBuffer(); ,.append nullpointer, , , . , . arrayList .

+1

, , / onCreate, . ( )

outside / , (onCreate), , , , , if(var != null), NullPointeException. ( Gloabal)

, , , , var

, MediaPlayer, Activity , , onCreate, onResume, onStop onDestroy, :

  • MediaPleyr (onCreate)

  • , (onResume), MediaPlayer

  • Activity MediaPlayer (onPause)

  • , , "IllegalState" (onDestroy)

* (onPreparedListener, onCompletionListener,...), .

+1
source

Source: https://habr.com/ru/post/1545058/


All Articles