Home > Back-end >  Using Android Studio to switch between pages, error occurs saying "not an enclosing class:MainA
Using Android Studio to switch between pages, error occurs saying "not an enclosing class:MainA

Time:07-23

package com.example.multipage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle ;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;


public class Page2 extends Activity {

    Button btn;

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

        btn = (Button) findViewById(R.id.btnl);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intentMain2Activity = new Intent(MainActivity.this,MainActivity.class);
                startActivity(intentMain2Activity);
            }
        });
    }
}

code does not work, giving error error: not an enclosing class: MainActivity Intent intentMain2Activity = new Intent(MainActivity.this,MainActivity.class);

CodePudding user response:

You need a context for the Intent. Change the following line:

Intent intentMain2Activity = new Intent(MainActivity.this,MainActivity.class);

to

Intent intentMain2Activity = new Intent(Page2.this, MainActivity.class);

CodePudding user response:

Here is your fault:

 Intent intentMain2Activity = new Intent(MainActivity.this,MainActivity.class);

We use the intent object to move from one page to another. but you placed the same pages in the intent object. So use this:

Intent intentMain2Activity = new Intent(Page2.this, MainActivity.class);

If you want to send data to the page to be passed with the intent object, use:

intentMain2Activity.putExtra("object_name", *your object*); 
  • Related