-3

I am studying and learning Android with a YouTube tutorial, I went to change between activities, followed it step by step and it just doesn't work.

I tried the only way I find, with the Intent, some codes may vary but at the end uses Intent.

This is what I have. The Button at activity_main.xml:

<Button
                    android:id="@+id/btnNext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toBottomOf="@+id/lvFood"
                    android:text="@string/btnNext" />

The Button at MainActivity.java:

Button btnNext;
btnNext = findViewById(R.id.btnNext);

The Listener of the Button:

btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toSecond = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(toSecond);
            }
        });

Also tried this, but the same result.

Intent toSecond = new Intent (v.getContext(), SecondActivity.class);
                startActivityForResult(toSecond, 0);

My manifest file:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/hello"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SecondActivity"></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>

The Run Log:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.helloworld, PID: 11503
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld/com.example.helloworld.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.helloworld.SecondActivity.onCreate(SecondActivity.java:19)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6669) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Edit

The code on MainActivity:

package com.example.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button btnSayHello, btnSayAnything, btnNext;
    TextView tvHelloWorld;
    EditText etSayAnything;
    Spinner spOptions;
    ListView lvFood;

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

        btnSayHello = findViewById(R.id.btnSayHello);
        tvHelloWorld = findViewById(R.id.tvHelloWorld);
        btnSayAnything = findViewById(R.id.btnSayAnything);
        etSayAnything = findViewById(R.id.etSayAnything);
        spOptions = findViewById(R.id.spOptions);
        lvFood = findViewById(R.id.lvFood);
        ArrayAdapter<CharSequence> spOptionsAdapter = ArrayAdapter.createFromResource(this, R.array.spOptions, android.R.layout.simple_spinner_item);
        spOptions.setAdapter(spOptionsAdapter);
        ArrayAdapter<CharSequence> lvFoodAdapter = ArrayAdapter.createFromResource(this, R.array.lvFood, android.R.layout.simple_list_item_1);
        lvFood.setAdapter(lvFoodAdapter);
        btnNext = findViewById(R.id.btnNext);

        btnSayHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(tvHelloWorld.getVisibility() == View.INVISIBLE)
                {
                    tvHelloWorld.setVisibility(View.VISIBLE);
                }else
                {
                    tvHelloWorld.setVisibility(View.INVISIBLE);
                }
            }
        });

        btnSayAnything.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvHelloWorld.setText(etSayAnything.getText());
                etSayAnything.setText("");
            }
        });

        lvFood.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvHelloWorld.setText(lvFood.getItemAtPosition(position).toString());
            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toSecond = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(toSecond);
            }
        });
    }
}

The code on SecondActivity:

package com.example.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SecondActivity extends AppCompatActivity {

    Button btnBack;
    Button btnExit;

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

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toMain = new Intent(SecondActivity.this, MainActivity.class);
                startActivity(toMain);
            }
        });
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

The videos I was following:

It should take me to the activity SecondActivity, which only have two buttons, one for back to the MainActivity and one for close the app.

But, the app just stop and closes.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Soham May 16 '19 at 14:10
  • 2
    You never included the code for `SecondActivity`, so we can't answer your question ;) – EpicPandaForce May 16 '19 at 14:12
  • Can you paste the complete activity code here ? – deepThought May 16 '19 at 14:14
  • 1
    There is error in your `SecondActivity`. Thats why its not able to open. – Rajat Mittal May 16 '19 at 14:15
  • 1
    You have to add full code of your MainActivity then only can able find solution. I think your btnNext was NULL. So need full code MainActivity. – Mohanraj May 16 '19 at 14:23
  • 1
    You're probably trying to find the button through its id before inflating the view. Can you show us exactly where you're calling findViewById to get the button? – Ricardo Costeira May 16 '19 at 14:27

5 Answers5

1

The button you are attempting the action click is not found; make sure you do this in your oncreate() of the SecondActivity.

setContentView(R.layout.your_second_activity_layout);

And also make you sure you instantiate your two button in the second activity like you did in your first activity:

btnNext = findViewById(R.id.btnNext);

Edit

After I saw your SecondActivity, you forgot:

btnback = findViewById(R.id.btnBack);
btnExit = findViewById(R.id.btnExit);
halfer
  • 19,824
  • 17
  • 99
  • 186
ismail alaoui
  • 5,748
  • 2
  • 21
  • 38
1

When you create an Android activity, you also have to define a layout that will become the activity's user interface. You bind the layout to the activity through the setContentView method, called as soon as possible on the activity's onCreate method (you have to override this method). Only after binding the layout to the activity can you start binding specific items on the layout (in this case, your button) to the appropriate objects declared in your code. If you try to bind these items before binding the layout to the activity, you'll get a null pointer instead of the actual item. Fore more information on Activities and their lifecycles, read this.

Edit:

You're not initializing your buttons. Please make sure that you have something similar to this in SecondActivity:

public class SecondActivity extends Activity {  

  private Button btnBack;
  private Button btnExit;;

  @Override  
  public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_second);

    btnBack = findViewById(R.id.btnBack);  
    btnExit = findViewById(R.id.btnExit);  

    // set the button listeners
  }
}  
Ricardo Costeira
  • 3,171
  • 2
  • 23
  • 23
  • 1
    The question states that there's `btnNext = findViewById(R.id.btnNext);` in `MainActivity` and we can see from the crash log that a button was pressed to go to the second activity, so the `setContentView()` must be there too or there wouldn't be a button to press in `MainActivity`. The crash log also states that the crash happens in `SecondActivity`. So far we can't really tell what's wrong there, although people's guesses _can_ be right. But still they are just guesses. – Markus Kauppinen May 16 '19 at 15:00
  • Ah, you're right. The problem is the click listener setting in the second activity. Gonna edit my answer accordingly. – Ricardo Costeira May 16 '19 at 15:17
0

This could be caused because you try to find your button before the layout for it is created. Are you sure you are using findViewbyIdafter the onCreate (or in it) ?

Please post your whole main activity code (and the second one).

Edit: I just saw the exception is thrown at your second activity so its probably not what i said above

GravityWell
  • 92
  • 1
  • 8
0

Try to always look for the words like 'Error', 'Exception', 'Caused By' in the Log report, cause in that line you will mostly find the reason of the crash.

Like in your case at the Log line number 3 it says...

Unable to start activity ...com.example.helloworld.SecondActivity 

because

Attempt to invoke method Button.setOnClickListener on a null object reference

that probably means your Button btnNext is null. Why? We can't see the whole the code but I assume it is because you have not set the layout view with setContentView() inside your onCreate() method.

NKoyee
  • 551
  • 6
  • 12
0

I have solved it, I forgot findViewById in my SecondActivity.

halfer
  • 19,824
  • 17
  • 99
  • 186