java.lang.InstantiationException:类没有零参数构造函数错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43229867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:12:40  来源:igfitidea点击:

java.lang.InstantiationException: class has no zero argument constructor error

javaandroidbroadcastreceiverandroid-broadcastandroid-broadcastreceiver

提问by Kalol Party

I've read the other threads that exist but none of them have been able to solve my problem.

我已经阅读了存在的其他线程,但没有一个能够解决我的问题。

I'm building an app which caches messages when there's no internet and stores them to a Database. The idea is when there is network connected, it pulls the data from the DB and sends message in the background - for which I made a Broadcast Receiver and made it receive "android.net.conn.CONNECTIVITY_CHANGE" broadcast - which then makes the app POST the message to the server

我正在构建一个应用程序,它在没有互联网时缓存消息并将它们存储到数据库中。这个想法是当有网络连接时,它从数据库中提取数据并在后台发送消息 - 为此我制作了一个广播接收器并让它接收“android.net.conn.CONNECTIVITY_CHANGE”广播 - 然后制作应用程序POST 消息到服务器

The error I get when the Network changes :

网络更改时出现的错误:

java.lang.RuntimeException: Unable to instantiate receiver com.tanvirsingh.fragmentsdemo.NetworkChangeReceiver: java.lang.InstantiationException: java.lang.Class<com.tanvirsingh.fragmentsdemo.NetworkChangeReceiver> has no zero argument constructor

The Broadcast Receiver Class (NetworkChangeReceiver.java):

广播接收器类 (NetworkChangeReceiver.java):

public class NetworkChangeReceiver extends BroadcastReceiver{

    private static final String TAGNCR = "JSON";

    private final Handler handler; // Handler used to execute code on the UI thread

    public NetworkChangeReceiver(Handler handler) {
        this.handler = handler;
    }

    DataBaseHelper myDB;
    final String MESSAGES_ENDPOINT = ""; 



    @Override
    public void onReceive(Context context, Intent intent) {

        int[] type = {ConnectivityManager.TYPE_MOBILE, ConnectivityManager.TYPE_WIFI};
        if (isNetworkAvailable(context) == true){
            //check for messages to be sent
            myDB = new DataBaseHelper(context);

            Cursor res = myDB.getAllData();
            if (res.getCount() == 0)
            {
                Log.d(TAG,"No data found");
                return;

            }

            StringBuffer buffer = new StringBuffer();
            while( res.moveToNext()){
                buffer.append("Params: "  + res.getString(0)+ "\n");
            }

            Log.d(TAGNCR,buffer.toString());

            return;

        } else {

        }
    }

    public void SendMessageFromDB(RequestParams param){

        AsyncHttpClient client = new AsyncHttpClient();

        //pusher
        PusherOptions options = new PusherOptions();
        options.setCluster("");
        Pusher pusher = new Pusher("", options);

        Channel channel = pusher.subscribe("my-channel");

        channel.bind("my-event", new SubscriptionEventListener() {
            @Override
            public void onEvent(String channelName, String eventName, final String data) {
                System.out.println(data);
            }
        });

        pusher.connect();

        final RequestParams params = param;

        client.post(MESSAGES_ENDPOINT + "/messages", params, new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, params.toString());
                        }
                    });
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    //Toast.makeText(, "Something went wrong :(", Toast.LENGTH_LONG).show();
                }
            });

            return;

    }



    //function to check if internet is available
    private static boolean isNetworkAvailable(Context context){
        try{
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null) { // connected to the internet and not in Airplane mode
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                    // connected to wifi
                    Toast.makeText(context, activeNetwork.getTypeName() + " Connected", Toast.LENGTH_SHORT).show();
                    return true;
                } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    // connected to the mobile data
                    Toast.makeText(context, activeNetwork.getTypeName() + " Connected", Toast.LENGTH_SHORT).show();
                    return true;
                }
            } else {
                // not connected to the internet
                Toast.makeText(context, "No internet connection available!", Toast.LENGTH_SHORT).show();

            }
        } catch (Exception e){
            return false;
        }
        return false;
    }
}

Stack Trace as requested:

根据要求进行堆栈跟踪:

04-05 16:36:29.828 3420-3420/com.tanvirsingh.fragmentsdemo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.tanvirsingh.fragmentsdemo, PID: 3420
                                                                             Theme: themes:{default=overlay:system, iconPack:com.baranovgroup.nstyle, fontPkg:com.baranovgroup.nstyle, com.android.systemui=overlay:com.baranovgroup.nstyle, com.android.systemui.navbar=overlay:system}
                                                                             java.lang.RuntimeException: Unable to instantiate receiver com.tanvirsingh.fragmentsdemo.NetworkChangeReceiver: java.lang.InstantiationException: java.lang.Class<com.tanvirsingh.fragmentsdemo.NetworkChangeReceiver> has no zero argument constructor
                                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2752)
                                                                                 at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                 at android.os.Looper.loop(Looper.java:148)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5471)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                 at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
                                                                              Caused by: java.lang.InstantiationException: java.lang.Class<com.tanvirsingh.fragmentsdemo.NetworkChangeReceiver> has no zero argument constructor
                                                                                 at java.lang.Class.newInstance(Native Method)
                                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2747)
                                                                                 at android.app.ActivityThread.-wrap14(ActivityThread.java)?
                                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)?
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:102)?
                                                                                 at android.os.Looper.loop(Looper.java:148)?
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5471)?
                                                                                 at java.lang.reflect.Method.invoke(Native Method)?
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)?
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)?
                                                                                 at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)?

回答by Andrey Danilov

Broadcast Receiversame as Fragmentand same as many other classes should have default constructor without arguments.

Broadcast ReceiverFragment许多其他类一样,应该有没有参数的默认构造函数。

Just add default constructor:

只需添加默认构造函数:

public NetworkChangeReceiver() {
}

That is so because Android system knows name of class and its package, but know nothing about its arguments. It uses reflection, something like

这是因为 Android 系统知道类的名称和它的包,但对它的参数一无所知。它使用反射,类似于

   Class c = Class.forName(className);
   YourBroadcastReceiver broadcastReceiver = (YourBroadcastReceiver)c.newInstance();

Without default constgructor newInstance() will generate error.

没有默认构造函数 newInstance() 会产生错误。

UPD:

更新:

In your case you should remove SendMessageFromDBmethod from BroadcastReceiver to separate class.

在您的情况下,您应该SendMessageFromDB从 BroadcastReceiver 中删除方法以分离类。