Search code examples
javaandroidandroid-activity

Change of Activity with Intent doesn't work and don't know why


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.


Solution

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