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

时间:2017-04-05 11:27:15

标签: java android broadcastreceiver android-broadcast android-broadcastreceiver

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

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

网络更改时收到的错误:

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

广播接收器类(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;
    }
}

按要求堆栈跟踪:

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) 

1 个答案:

答案 0 :(得分:4)

Broadcast ReceiverFragment相同,并且与许多其他类相同,应该有没有参数的默认构造函数。

只需添加默认构造函数:

public NetworkChangeReceiver() {
}

之所以如此,是因为Android系统知道类及其包的名称,但对其参数一无所知。 它使用反射,类似

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

如果没有默认的constgructor,newInstance()将生成错误。

UPD:

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