I am trying add couchbase lite in my android app.but i got following error.can anyone tell me what goes wrong


#1
//code

        // activity receiver not registered Exception
        IntentFilter filter = new IntentFilter();
        registerReceiver(mReceiver, filter);

        //
        enableLogging();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void enableLogging() {
        if (LOGGING_ENABLED) {
            Manager.enableLogging(TAG, Log.VERBOSE);
            Manager.enableLogging(Log.TAG, Log.VERBOSE);
            Manager.enableLogging(Log.TAG_SYNC_ASYNC_TASK, Log.VERBOSE);
            Manager.enableLogging(Log.TAG_SYNC, Log.VERBOSE);
            Manager.enableLogging(Log.TAG_QUERY, Log.VERBOSE);
            Manager.enableLogging(Log.TAG_VIEW, Log.VERBOSE);
            Manager.enableLogging(Log.TAG_DATABASE, Log.VERBOSE);
        }
    }

    private Manager getManager() {
        if (mManager == null) {
            try {
                AndroidContext context = new AndroidContext(getApplicationContext());
                mManager = new Manager(context, Manager.DEFAULT_OPTIONS);
            } catch (Exception e) {
                Log.e(TAG, "Cannot create Manager object", e);
            }
        }
        return mManager;
    }

    public Database getDatabase() {
        return mDatabase;
    }

    private void setDatabase(Database database) {
        this.mDatabase = database;
    }


    // Sets up communication with {@link BluetoothHDPService}.
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
            mHealthServiceBound = true;
            System.out.println("In ServiceConnection onServiceConnected");
            Message msg = Message.obtain(null,
                    BtHealthDeviceService.MSG_REG_CLIENT);
            msg.replyTo = mMessenger;
            mHealthService = new Messenger(service);
            if (mHealthService == null) {
                System.out.println(">> mHealthService is null");
            }
            try {
                // 4
                System.out.println("in ServiceConnection try...");
                mHealthService.send(msg);
            } catch (RemoteException e) {
                Log.w(TAG, "Unable to register client to service.");
                e.printStackTrace();
            }
        }

        public void onServiceDisconnected(ComponentName name) {
            System.out.println(" in onServiceDisconnected ");
            mHealthService = null;
            mHealthServiceBound = false;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHealthServiceBound)
            unbindService(mConnection);
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        // If Bluetooth is not on, request that it be enabled.
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            initialize();
        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Dashboard Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.com.healthdeviceprofilee/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    /**
     * Ensures user has turned on Bluetooth on the Android device.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                if (resultCode == Activity.RESULT_OK) {
                    initialize();
                } else {
                    finish();
                    return;
                }
        }
    }

    /**
     * Used by {@link SelectDeviceDialogFragment} to record the bonded Bluetooth
     * device selected by the user.
     *
     * @param position Position of the bonded Bluetooth device in the array.
     */
    public void setDevice(int position) {
        mDevice = this.mAllBondedDevices[position];
        mDeviceIndex = position;
    }

    private void connectChannel() {
        sendMessageWithDevice(BtHealthDeviceService.MSG_CONNECT_CHANNEL);
    }

    private void disconnectChannel() {
        sendMessageWithDevice(BtHealthDeviceService.MSG_DISCONNECT_CHANNEL);
    }

    private void initialize() {
        // Starts health service.
        Intent intent = new Intent(this, BtHealthDeviceService.class);
        startService(intent);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    // Intent filter and broadcast receive to handle Bluetooth on event.
    private IntentFilter initIntentFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        return filter;
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                        BluetoothAdapter.ERROR) == BluetoothAdapter.STATE_ON) {
                    initialize();
                }

            }
        }
    };

    // Sends a message to {@link BluetoothHDPService}.
    private void sendMessage(int what, int value) {
        if (mHealthService == null) {
            System.out
                    .println("In HDP activity sendMessage -Health Service not connected.");

            Log.d(TAG, "Health Service not connected.");
            return;
        }

        try {
            System.out.println("hdp activity send message");
            System.out.println("what******" + what);
            System.out.println("value*****" + value);

            mHealthService.send(Message.obtain(null, what, value, 0));

        } catch (RemoteException e) {
            Log.w(TAG, "Unable to reach service.");

            e.printStackTrace();
        }
    }

    // Sends an update message, along with an HDP BluetoothDevice object, to
    // {@link BluetoothHDPService}. The BluetoothDevice object is needed by the
    // channel creation
    // method.
    private void sendMessageWithDevice(int what) {
        if (mHealthService == null) {
            Log.d(TAG, "Health Service not connected.");
            System.out.println("in sendMessageWithDevice");
            return;
        }

        try {
            System.out.println("in sendMessageWithDevice try");

            mHealthService.send(Message.obtain(null, what, mDevice));
        } catch (RemoteException e) {
            Log.w(TAG, "Unable to reach service.");
            e.printStackTrace();
        }
    }

    @Override
    public void changed(Replication.ChangeEvent event) {

    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Dashboard Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.com.healthdeviceprofilee/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

    /**
     * Dialog to display a list of bonded Bluetooth devices for user to select
     * from. This is needed only for channel connection initiated from the
     * application.
     */
    public static class SelectDeviceDialogFragment extends DialogFragment {

        public static SelectDeviceDialogFragment newInstance(String[] names,
                                                             int position) {
            SelectDeviceDialogFragment frag = new SelectDeviceDialogFragment();
            Bundle args = new Bundle();
            args.putStringArray("names", names);
            args.putInt("position", position);
            frag.setArguments(args);
            return frag;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            String[] deviceNames = getArguments().getStringArray("names");
            int position = getArguments().getInt("position", -1);
            if (position == -1)
                position = 0;
            return new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.select_device)
                    .setPositiveButton(R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    ((DashboardActivity) getActivity())
                                            .connectChannel();
                                }
                            })
                    .setSingleChoiceItems(deviceNames, position,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    ((DashboardActivity) getActivity())
                                            .setDevice(which);
                                }
                            }).create();
        }
    }

    private void sendData() {
        jsonObj = new JSONObject();

        bpdata = Integer.toString(sys) + "," + Integer.toString(dia) + ","
                + Integer.toString(pul);
        System.out.println("Bp data is " + bpdata);

        pulseoxidata = Integer.toString(pulsedata) + ","
                + Integer.toString(oxi);

        System.out.println("Pulse Oxi  data is " + pulseoxidata);

        new RestConnection().execute();
    }

    private class RestConnection extends AsyncTask<Void, Void, String> implements Replication.ChangeListener {

        private String TAG = this.getClass().getName();

        ProgressDialog progressDialog;

        public RestConnection() {
            super();
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected String doInBackground(Void... arg0) {
            String st = jsonObj.toString();
            String response = "";

            Log.i(TAG, st);

            JSONObject item = null;
            try {
                item = new JSONObject(st);
            } catch (JSONException e) {
                Log.e(TAG, "Could not parse malformed JSON:" + st);
            }

            if (item == null) {
                Log.e(TAG, "Null");
            }

            // doing the respective post
            try {
                // POST DATA
                String url = Constants.getDataPost();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                HttpConnectionParams.setConnectionTimeout( httpClient.getParams(), 10000);
                JSONObject json = new JSONObject();
                HttpResponse httpResponse = httpClient.execute(httpPost);
                if(httpResponse.getStatusLine().getStatusCode()==200) {
                    json.put( "siteId", "" );
                    if (wtConnected == true) {
                        json.put( "patientId", 5 );
                        json.put( "deviceMACId", healthDeviceMac );
                        json.put( "readingType", 103 );
                        json.put( "deviceData", Double.toString( weight ) );
                        json.put( "deviceType", "WeightScale" );

                    } else if (bpConnected == true) {
                        json.put( "patientId", 5 );

                        json.put( "deviceMACId", healthDeviceMac );
                        json.put( "readingType", 102 );
                        json.put( "deviceData", bpdata );
                        json.put( "deviceType", "BPMonitor" );

                    } else if (pulseOxiConnected == true) {
                        json.put( "patientId", 5 );

                        json.put( "deviceMACId", healthDeviceMac );
                        json.put( "readingType", 101 );
                        json.put( "deviceData", pulseoxidata );
                        json.put( "deviceType", "PulseOxi" );

                    }
                    json.put( "assetId", "" );

                    json.put( "geoLocationLatitude", "" );

                    json.put( "clientId", "" );

                    json.put( "timeStamp", System.currentTimeMillis() );

                    json.put( "deviceRawData", "" );
                    json.put( "geoLocationLongitude", "" );

                    System.out.println( "Json Is:" + json );
                    StringEntity se = new StringEntity( json.toString() );
                    se.setContentType( new BasicHeader( HTTP.CONTENT_TYPE,
                            "application/json" ) );
                    httpPost.setEntity( se );
                    //HttpResponse httpResponse = httpClient.execute(httpPost);
                    Log.i( TAG, "response "
                            + httpResponse.getStatusLine().getStatusCode() );
                    HttpEntity entityPost = httpResponse.getEntity();
                    InputStream is = entityPost.getContent();
                    String response1 = convertStreamToString( is );
                    Log.i( TAG, "response message " + response1 );
                }else if( httpResponse.getStatusLine().getStatusCode()!=200)
                {
                        /*Replication*/
                    getSyncUrl();
                    Document document = mDatabase.createDocument();
                    Map<String, Object> properties = new HashMap<String, Object>();
                    properties.put( "siteId", "" );
                    if (wtConnected == true) {
                        properties.put( "patientId", 5 );
                        properties.put( "deviceMACId", healthDeviceMac );
                        properties.put( "readingType", 103 );
                        properties.put( "deviceData", Double.toString( weight ) );
                        properties.put( "deviceType", "WeightScale" );

                    } else if (bpConnected == true) {
                        properties.put( "patientId", 5 );

                        properties.put( "deviceMACId", healthDeviceMac );
                        properties.put( "readingType", 102 );
                        properties.put( "deviceData", bpdata );
                        properties.put( "deviceType", "BPMonitor" );

                    } else if (pulseOxiConnected == true) {
                        properties.put( "patientId", 5 );

                        properties.put( "deviceMACId", healthDeviceMac );
                        properties.put( "readingType", 101 );
                        properties.put( "deviceData", pulseoxidata );
                        properties.put( "deviceType", "PulseOxi" );

                    }
                    properties.put( "assetId", "" );

                    properties.put( "geoLocationLatitude", "" );

                    properties.put( "clientId", "" );

                    properties.put( "timeStamp", System.currentTimeMillis() );

                    properties.put( "deviceRawData", "" );
                    properties.put( "geoLocationLongitude", "" );
                    document.putProperties( properties );
                    System.out.println("Database Content is.....:" +properties);

                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "Post error:Error");
                Log.i(TAG, "response :" +response);
            }
            return response;


        }
        @Override
        protected void onPostExecute(String result) {
        }
        /*Replication*/
        private URL getSyncUrl() {
            URL url = null;
            try {
                url = new URL(SYNC_URL_HTTP);
            } catch (MalformedURLException e) {
                Log.e(TAG, "Invalid sync url", e);
            }
            return url;
        }
        private void startReplication(Authenticator auth) {
            if (mPull == null) {
                mPull = mDatabase.createPullReplication(getSyncUrl());
                mPull.setContinuous(true);
                mPull.setAuthenticator(auth);
                mPull.addChangeListener(this);
            }

            if (mPush == null) {
                mPush = mDatabase.createPushReplication(getSyncUrl());
                mPush.setContinuous(true);
                mPush.setAuthenticator(auth);
                mPush.addChangeListener(this);
            }

            mPull.stop();
            mPull.start();

            mPush.stop();
            mPush.start();
        }

        private void stopReplication() {
            if (mPull != null) {
                mPull.removeChangeListener(this);
                mPull.stop();
                mPull = null;
            }

            if (mPush != null) {
                mPush.removeChangeListener(this);
                mPush.stop();
                mPush = null;
            }
        }

        @Override
        public void changed(Replication.ChangeEvent event) {
            Throwable error = null;
            if (mPull != null) {
                if (error == null)
                    error = mPull.getLastError();
            }

            if (error == null || error == mReplError)
                error = mPush.getLastError();

            if (error != mReplError) {
                mReplError = error;
                if (mReplError != null)
                    showErrorMessage(mReplError.getMessage(), null);
            }
        }

    }
    public void showErrorMessage(final String errorMessage, final Throwable throwable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                android.util.Log.e(TAG, errorMessage, throwable);
                String msg = String.format("%s: %s",
                        errorMessage, throwable != null ? throwable : "");
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    // Progress Dialog for Data Reading

    private Dialog progress;

    private void showIndicator(String message) {
        if (progress == null) {
            progress = new Dialog(DashboardActivity.this);
            // AlertDialog.Builder builder = new AlertDialog.Builder(context);
            progress.getWindow().setBackgroundDrawable(new ColorDrawable(0));
            progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
            progress.setContentView(R.layout.custom_alert);
            progress.setCancelable(false);
        }

        setIndicatorMessage(message);

        if (!progress.isShowing()) {
            progress.show();
        }
    }

    private void setIndicatorMessage(String message) {
        if (progress == null) {
            return;
        }
        TextView syncMessages = (TextView) progress
                .findViewById(R.id.syncMessages1);

        if (message == null) {
            message = "";
        }

        if (syncMessages != null) {
            syncMessages.setText(message);
        }
    }

    private void dismissIndicator() {
        if (progress == null) {
            return;
        }

        progress.dismiss();
        progress = null;
    }

    // Are you sure you want to exit? Alert Box
    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                DashboardActivity.this.finish();
                            }
                        })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();

    }

}


//Error

10-05 15:09:31.961 2616-2616/com.com.healthdeviceprofilee I/System.out: Bp data is 106,80,91
10-05 15:09:31.961 2616-2616/com.com.healthdeviceprofilee I/System.out: Pulse Oxi  data is 0,0
10-05 15:09:32.061 2616-4216/com.com.healthdeviceprofilee I/com.com.healthdeviceprofilee.DashboardActivity$RestConnection: {}
10-05 15:09:32.451 2616-4216/com.com.healthdeviceprofilee I/System.out: Thread-31765(ApacheHTTPLog):Reading from variable values from setDefaultValuesToVariables
10-05 15:09:32.451 2616-4216/com.com.healthdeviceprofilee I/System.out: Thread-31765(ApacheHTTPLog):isSBSettingEnabled false
10-05 15:09:32.451 2616-4216/com.com.healthdeviceprofilee I/System.out: Thread-31765(ApacheHTTPLog):isShipBuild true
10-05 15:09:32.451 2616-4216/com.com.healthdeviceprofilee I/System.out: Thread-31765(ApacheHTTPLog):SMARTBONDING_ENABLED is false
10-05 15:09:32.451 2616-4216/com.com.healthdeviceprofilee I/System.out: Thread-31765(ApacheHTTPLog):SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
10-05 15:09:33.151 2616-4216/com.com.healthdeviceprofilee W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'com.couchbase.lite.Document com.couchbase.lite.Database.createDocument()' on a null object reference
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee W/System.err:     at com.com.healthdeviceprofilee.DashboardActivity$RestConnection.doInBackground(DashboardActivity.java:917)
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee W/System.err:     at com.com.healthdeviceprofilee.DashboardActivity$RestConnection.doInBackground(DashboardActivity.java:823)
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee W/System.err:     at java.lang.Thread.run(Thread.java:818)
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee E/com.com.healthdeviceprofilee.DashboardActivity$RestConnection: Post error:Error
10-05 15:09:33.161 2616-4216/com.com.healthdeviceprofilee I/com.com.healthdeviceprofilee.DashboardActivity$RestConnection: response :