Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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):

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) 
like image 666
Kalol Party Avatar asked Mar 09 '23 10:03

Kalol Party


1 Answers

Broadcast Receiver same as Fragment and same as many other classes should have default constructor without arguments.

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

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

Without default constgructor newInstance() will generate error.

UPD:

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

like image 89
Andrey Danilov Avatar answered Mar 22 '23 23:03

Andrey Danilov