Nizzy
Nizzy

Reputation: 379

MyFirstApp tutorial Android Studio -- sendMessage Issue

So I just started to learn Android Studio for android development and started going through the myFirstApp tutorial on their website. I am trying to add a method to the button but can't get it to work. I have the sendMessage method in MainActivity.java and when i go to select it from the "on click" drop down list, it doesn't appear. I have the correct imports as well. Does anyone know why this may be? Thanks.

Here is what my code looks like:

package com.example.tyler.myfirstapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user taps the Send button */
    public void sendMessage(View view) {
    // Do something in response to button
    }
}

Upvotes: 4

Views: 2998

Answers (3)

coolistic
coolistic

Reputation: 1

The answer for this is that you do not have the function INSIDE of the last curly brace at the bottom. Just undo the function you pasted and make sure to repaste just before the last curly brace and then it will all be fixed.

Upvotes: 0

user11105662
user11105662

Reputation: 1

I got stuck with this one as well, so i skipped down the page a bit and grabbed the complete code for MainActivity.java (apart from the first line that i kept). Once i'd replaced this i got the sendMessage[MainActivity] appear on the onClick Button attribute.

package com.example.your....

public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/** 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);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}
}

Upvotes: 0

Sajal Narang
Sajal Narang

Reputation: 400

Add android:onClick="sendMessage" attribute to your button tag in activity_main.xml.

From the tutorial you are following:

Now return to the activity_main.xml file to call this method from the button:

  1. Click to select the button in the Layout Editor.

  2. In the Properties window, locate the onClick property and select sendMessage [MainActivity] from the drop-down list.

You must've skipped this step.

Upvotes: 2

Related Questions