Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot resolve constructor (Android Intent)

Tags:

java

android

I'm trying to create a simple button that opens to a different activity:

package com.example.xxx.buttonexample;

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

public class MainActivity extends Activity {

Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnClick();
}
public void btnClick() {
    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(this,emergencyIntent.class);
            startActivity(intent);
        }
    });
}
}

Here is my emergencyIntent.class file:

package com.example.xxx.buttonexample;

import android.app.Activity;
import android.os.Bundle;

public class emergencyIntent extends Activity
{

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    // The activity is being created.

}

}       

I received a error:

"Cannot resolve constructor 'intent(anonymous android.view.View.OnClickListener, java.lang.Class(com.example.xxx.buttonexample.emergencyIntent))'.

like image 407
User Avatar asked Jun 21 '15 13:06

User


1 Answers

Just replace this in first parameter with MainActivity.this. like:

 Intent intent = new Intent(MainActivity.this,emergencyIntent.class);

The error is because you are writing it in public void onClick(View v), where 'this' will mean instance of anonymous class that implements View.OnClickListener. while first parameter in Intent constructor Intent(Context context, Class<?> cls) requires Activity context.

like image 63
Krupal Shah Avatar answered Oct 10 '22 22:10

Krupal Shah