c75
c75

Reputation: 1

When to use "new" keyword android API

I am new to programming and trying to understand why sometimes it appears that objects are instantiated without a "new" keyword. For instance the basic tutorial app from google's android tutorial:

In the "Build an Intent" example, an Intent is created using the new keyword:

/** Called when the user taps the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
...
}

But later in "Display the Message", they make an Intent object this way if I am understanding correctly:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    // Get the Intent that started this activity and extract the string
    Intent intent = getIntent();
    ...
}

And use the getIntent() method. Also, where is getIntent() method defined? It is a method from the Intent class?

Also on the previous section (https://developer.android.com/training/basics/firstapp/starting-activity.html) they make a new editText but I still don't understand why the "new" keyword isn't used:

EditText editText = (EditText) findViewById(R.id.editText);

Thanks for any help.

Upvotes: 0

Views: 462

Answers (1)

Niels Vanwingh
Niels Vanwingh

Reputation: 604

Good to learn that you want to start learning code.. I have added the solutions to your two questions, best is to just keep going and then everything will start to look logical, step by step.. The beginning is the hardest..

Intent intent = getIntent();

This instantiates an Intent object, the value comes from the function getIntent().. In the following link you can find that it is a method from the class Activity and returns the intent that started this activity.

https://developer.android.com/reference/android/app/Activity.html

EditText editText = (EditText) findViewById(R.id.editText);

This is a referral to a field "editText", defined in your Layout File. You refer to the ressource in the layout.. Better and clear is to use another naming..

EditText "how you want to name the field" = (EditText) findViewById (R.id."name of the field in the layout")

As suggested below, try to take some basic classes online, watch some tutorials and hang in there!

Good luck!

Upvotes: 1

Related Questions