此类应在 android manifest 中提供默认构造函数(不带参数的公共构造函数)

Posted

技术标签:

【中文标题】此类应在 android manifest 中提供默认构造函数(不带参数的公共构造函数)【英文标题】:This class should provide a default constructor (a public constructor with no arguments) in android manifest 【发布时间】:2021-09-19 17:19:24 【问题描述】:

您好,我一次又一次地收到此错误。 进程:pandaboo.run.carromking,PID:30965 java.lang.RuntimeException:无法实例化活动 ComponentInfopandaboo.run.carromking/pandaboo.run.carromking.MainActivity:java.lang.InstantiationException:java.lang.Class 没有零参数构造函数

android清单如下:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:fullBackupContent="@xml/backup_descriptor"
    tools:ignore="AllowBackup">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

构建没有错误但是.MainActivity下的manifest中有一个红色下划线有错误:

This class should provide a default constructor (a public constructor with no arguments) (`pandaboo.run.carromking.MainActivity`)

请帮忙。


确定 MainActivity 如下:

public class MainActivity extends Activity 
@SuppressLint("StaticFieldLeak")
static Context context;
public final ThreadLocal<Discovery> disc;


    disc = new ThreadLocal<Discovery>() 
        @Override
        protected Discovery initialValue() 
            return new Discovery(Discovery.DiscoveryType.MDNS);
        
    ;


public static Publisher gamePublisher;
Subscriber gameSubscriber;
Thread testPublishing;
RenderThread renderThread;
private final Node node;

public MainActivity(Node node) 
    this.node = node;


public class TestPublishing extends Application implements Runnable 

    @Override
    public void run() 
        while (gamePublisher != null) 
            Log.v("CarromGame: umundo", "run");
            //gamePublisher.send(message.getBytes());
            try 
                Thread.sleep(1000);
                Log.v("CarromGame:", "sleep");
             catch (InterruptedException e) 
                Log.v("CarromGame: exception", "in run");
                e.printStackTrace();
            
            pandaboo.run.carromking.MainActivity.this.runOnUiThread(() -> 
                //tv.setText(tv.getText() + "o");
                Log.v("CarromGame: umundo", "context view o");
                //contentView = true;

                renderThread = new RenderThread(new pandaboo.run.carromking.MainActivity.displayComponents().getHolder(), new MainGamePanel(pandaboo.run.carromking.MainActivity.this));
                renderThread.start();
            );
        
    


public class TestReceiver extends Receiver 
    byte[] msgb;
    String type = null;

    public void receive(Message msg) 
        msgb = msg.getData();
        type = msg.getMeta("CLASS");
        Log.v("CarromGame:umundo value", "TYPE = " + type);
        for (String key : msg.getMeta().keySet()) 
            Log.v("CarromGame: umundo", key + ": " + msg.getMeta(key) + " value for class" + msg.getMeta("CLASS"));
        

        pandaboo.run.carromking.MainActivity.this.runOnUiThread(() -> 
            //tv.setText(tv.getText() + "i");
            Log.v("CarromGame: umundo", "context view i before");


            ObjectInputStream is = null;
            if ((type != null) && (!type.equals(""))) 
                try 
                    type = null;
                    ByteArrayInputStream in = new ByteArrayInputStream(msgb);
                    is = new ObjectInputStream(in);
                    is.readObject();
                    Log.v("CarromGame: umundo", "inside try block " + is.toString());
                 catch (Exception e) 
                    e.printStackTrace();
                
                assert is != null;
                Log.v("CarromGame: umundo", "context view i after" + is.toString());
                renderThread = new RenderThread(new pandaboo.run.carromking.MainActivity.displayComponents().getHolder(), new MainGamePanel(pandaboo.run.carromking.MainActivity.this));
                renderThread.start();
            
        );
    


public class displayComponents extends SurfaceView implements SurfaceHolder.Callback 
    public displayComponents() 
        super(getApplicationContext());
        this.getHolder().addCallback(this);
    

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) 
    

    @Override
    public void surfaceCreated(SurfaceHolder holder) 
        renderThread.running = true;
        renderThread.start();
    

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) 
        while (true) 
            try 
                renderThread.join();
                break;
             catch (InterruptedException ignored) 
            
        

    


//Called when activity is created for the first time
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    // To check if there is any active Wifi connection
    if (!wifi.isWifiEnabled()) 
        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
    
    //Allow the application to receive Wifi Multicast packets.
    WifiManager.MulticastLock mcLock = wifi.createMulticastLock("gameLock");
    mcLock.acquire();
    System.loadLibrary("umundoNativeJava");
    Objects.requireNonNull(disc.get()).add(node);

    Log.v("CarromGame:", "on create");
    gamePublisher = new Publisher("Carrom"); //Carrom: channel Name
    node.addPublisher(gamePublisher);

    //gamePublisher.send();

    gameSubscriber = new Subscriber("Carrom", new pandaboo.run.carromking.MainActivity.TestReceiver());
    node.addSubscriber(gameSubscriber);

    testPublishing = new Thread(new pandaboo.run.carromking.MainActivity.TestPublishing());
    //contentView();
    testPublishing.start();

    Log.v("CarromGame: umundo", "inside context view");
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    //setTitle(title);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    MainGamePanel.PANEL_HEIGHT = this.getWindowManager().getDefaultDisplay().getHeight();
    MainGamePanel.PANEL_WIDTH = this.getWindowManager().getDefaultDisplay().getWidth();
    setContentView(new MainGamePanel(this));



@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_carrom_game_umundo, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    return super.onOptionsItemSelected(item);

【问题讨论】:

请显示pandaboo.run.carromking.MainActivity 类。错误消息准确地解释了这个问题:“类没有零参数构造函数”和“这个类应该提供一个默认构造函数(一个没有参数的公共构造函数)”。 在常规 Java 应用程序中 “此类应提供默认构造函数(不带参数的公共构造函数)” 当然意味着您应该提供默认构造函数(a没有参数的公共构造函数)。在 Android 中,您不应该为 Activity 编写任何构造函数或自己实例化它,因此您需要找到其他方法将 Node node 传递给 Activity。 任何相关代码都应该通过编辑添加到问题中,而不是作为答案或评论。 【参考方案1】:

你不能这样做:

public MainActivity(Node node) 
    this.node = node;

不要为Activity 声明任何构造函数。只有 Android 框架可以实例化 Activity,您不能定义任何额外的构造函数。

【讨论】:

以上是关于此类应在 android manifest 中提供默认构造函数(不带参数的公共构造函数)的主要内容,如果未能解决你的问题,请参考以下文章

如何在清单文件中包含 Maven 依赖项

运行项目时缺少 android manifest 的变化

Android 6.0 运行时权限管理

android 多渠道打包

Android manifest文件中的标签详细介绍

Android manifest之manifest标签详细介绍