Adam S Adam S - 4 months ago 9
Java Question

Error:(21, 8) error: class MyActivity is public - Can't edit MyActivity

When trying to edit MyActivity, it opens up MainActivity.java.

When trying to change the read only flag this error message shows up


Failed to change read-only flag for /root/AndroidStudioProjects/MyApplication3/app/src/main/java/xyz/adamstephenson/android/myapplication/MainActivity.java


I'm trying to make a public class that outputs information when a button is pressed on Android.

The error is:


Error:(21, 8) error: class MyActivity is public, should be declared in
a file named MyActivity.java


package xyz.adamstephenson.android.myapplication;

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

import static
xyz.adamstephenson.android.myapplication.R.layout.activity_main;


public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(activity_main);

final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("button", "This is my message");
}
});
}
}

Answer

This error occurs when your class file name is not same as the class name inside the class file.

in drive you make a class

A.java 
but write it as 
public class A1{}

It will throw exception : class A1 is public, should be declared in a file named A1.java

How ever if you do something like following

A.java
and code it as 
class A1{}

Above will not throw any exception, but this class will not be accessible from outside the package.

Comments