0

Background

Just to set some context, I'm very new to Android app development. After using Android Developers guide on developing a basic app that would teach me how to create a "Hello, World!" project. However, after learning to build a user interface and start another activity. Ultimately, the main focus was to add some code to the MainActivity that starts a new activity to display a message when the user would tap the Send button. After running the app on my device, I attempted to type out a message and click send, only for the send button to ultimately close my app with no lag, or explaination as to why it closed.

MainActivity.java

package com.example.giglitz;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

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

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.giglitz">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".DisplayMessageActivity">
                  android:parentActivityName=".MainActivity">
            <!-- The meta-data tag is required if you support API level 15 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

DisplayMessageActivity.java

package com.example.giglitz;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class DisplayMessageActivity extends AppCompatActivity {

    @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();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        // Capture the layout's TextView and set the string as its text
        TextView textView = findViewById(R.id.textView);
        textView.setText(message);
    }
}

activity_display_message.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DisplayMessageActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Logcat (after filtering Error, Show only selected application)

Process: com.example.giglitz, PID: 6422
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
        at android.view.View.performClick(View.java:7201)
        at android.view.View.performClickInternal(View.java:7170)
        at android.view.View.access$3500(View.java:806)
        at android.view.View$PerformClick.run(View.java:27562)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
        at android.view.View.performClick(View.java:7201) 
        at android.view.View.performClickInternal(View.java:7170) 
        at android.view.View.access$3500(View.java:806) 
        at android.view.View$PerformClick.run(View.java:27562) 
        at android.os.Handler.handleCallback(Handler.java:883) 
        at android.os.Handler.dispatchMessage(Handler.java:100) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7682) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.example.giglitz.MainActivity.sendMessage(MainActivity.java:24)
        at java.lang.reflect.Method.invoke(Native Method) 
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
        at android.view.View.performClick(View.java:7201) 
        at android.view.View.performClickInternal(View.java:7170) 
        at android.view.View.access$3500(View.java:806) 
        at android.view.View$PerformClick.run(View.java:27562) 
        at android.os.Handler.handleCallback(Handler.java:883) 
        at android.os.Handler.dispatchMessage(Handler.java:100) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7682) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editTextTextPersonName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/edit_message"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toStartOf="@+id/button"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:onClick="sendMessage"
        android:text="@string/button_send"
        app:layout_constraintBaseline_toBaselineOf="@+id/editTextTextPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/editTextTextPersonName" />
</androidx.constraintlayout.widget.ConstraintLayout>
RunMildew
  • 67
  • 1
  • 13
  • Hi RunMildew can you share displaymessageactivity and XML files. So I can give you better answer. – MAHI Aug 22 '20 at 19:34
  • Thanks for the replies! MAHI, I've just updated my post with the requested information. Beko, the application is still able to run on my device without any errors prohibiting me from doing so, the only problem is that once I type anything out and click "send" the application suddenly closes. However, checking Logcat after running the application and keeping my device plugged in via USB has prompted me to filter the errors. Upon which there is a long list of red errors. Seeing as thought I am new to this process, how would I be able to diagnose the root cause of this? – RunMildew Aug 22 '20 at 20:14

5 Answers5

1

I think you either did not put anything in the 'onclick' field for your button, or you didn't set an ID for your EditText. Can you send your activity_main.xml file as well? If you want to know where it is, go to the 'res' directory, and then go into the 'layout' directory.

Dev Randalpura
  • 126
  • 1
  • 4
  • Sure thing, just updated the post with the activity_main.xml file. Thanks for helping! – RunMildew Aug 22 '20 at 22:20
  • Ok, so I think this is your error: in your `activity_main.xml` file, you set the ID of the EditText to `editTextTextPersonName`. However, in the Java file, in the line `EditText editText = (EditText) findViewById(R.id.editText);`, you put `R.id.editText`, while it should be `R.id.editTextPersonName`. So, everytime, you try to use `findViewById`, the Id should be the exact same thing you put in your .xml file. Tell me if it works. – Dev Randalpura Aug 22 '20 at 23:35
  • It works! Thank you so much, please take this upvote! – RunMildew Aug 23 '20 at 00:27
  • 1
    @RunMildew if it works you can also mark this as the answer to your question. If you see you have a tick sign next to the votes, just click on it and it will become green – Antonino Oct 20 '20 at 03:47
0

I will need to see your logcat output to determine what problems you encountered. Generally, when using Intent extras, I recommend checking for nullability of objects, as that string might not exist, although it clearly does in this case. So, please send a transcript of your logs. Thanks!

Akash Veerappan
  • 76
  • 1
  • 1
  • 6
  • Just updated my post with this information, although to be prompt, i had filtered through and highlighted Error and Show only selected application. Thanks for the reply! – RunMildew Aug 22 '20 at 20:22
  • @MAHI just updated my post with the activity_main.xml – RunMildew Aug 22 '20 at 22:24
0

It looks like you did not implement the 'onclick' behavior correctly in your app. In the XML file, you should add this line for your send button android:onClick="sendMessage"

Also, check out this for more details about implementing onClick behaviors in Android: https://developer.android.com/guide/topics/ui/controls/button#HandlingEvents, https://stackoverflow.com/a/4153842/1725535

Shubham Naik
  • 410
  • 1
  • 7
  • 18
  • Hi Shubham, i had just updated my post with the activity_main.xml, in which the recommendation you proposed is already there. Would there be any other error? – RunMildew Aug 22 '20 at 22:32
  • It looks like https://stackoverflow.com/questions/63540189/clicking-the-button-to-second-activity-automatically-closes-app-android-studio/63540842#comment112361337_63540842 has resolved your issue. You should still look into the provided docs for more deep understanding of the concept. Happy coding. – Shubham Naik Aug 23 '20 at 05:15
0

It looks like you did not implement the 'onclick' behavior correctly in your app. In the XML file, you should add this line for your send button android:onClick="sendMessage"

To tell activity to listen the button click and call the onClickListner method.

MAHI
  • 51
  • 3
  • i had just updated my post with the activity_main.xml, in which the recommendation you proposed is already there. So what would be the actual issue? – RunMildew Aug 22 '20 at 23:19
0
It looks like you did not implement the 'onclick' behavior correctly in your app.
 In the XML file, you should add this line for your send button 
 android:onClick="sendMessage"  or you can use it programmatically by button id
For eg:-
        Button btn = (Button) findViewById(R.Id.sendButton);
        btn.setOnClickListner(new View.OnClickListner){
          @Override
           public onClick(View view){
                  // Your statement 
                  }
       }

To tell activity to listen the button click and call the onClickListner method.

MAHI
  • 51
  • 3