lundi 1 mai 2017

Any operation with Checkbox is giving Errors in Android

I want to detect whether if a checkbox is checked or not.

MainActivity.java

package com.example.vivek.trackblue;

import android.bluetooth.BluetoothAdapter;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import static android.bluetooth.BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
import static android.bluetooth.BluetoothAdapter.ACTION_REQUEST_ENABLE;



public class MainActivity extends AppCompatActivity{
    final int Request_code = 1;
    BluetoothAdapter  bt = BluetoothAdapter.getDefaultAdapter();
    private static int  flag_bt_state = 0;



        Button button2;
        ImageView cold2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // All local views declared here
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button button = (Button)findViewById(R.id.button5);
        final Toast bt_disabled = Toast.makeText(getApplicationContext(), "Bluetooth Disabled", Toast.LENGTH_SHORT);
        button2 = button;
        final ImageView cold = (ImageView)findViewById(R.id.imageView);
        cold2 = cold;
        CheckBox cb1 = (CheckBox)findViewById(R.id.checkbox);

        //Bluetooth Adapter State
        if(bt.isEnabled()) {
                flag_bt_state = 1;
                button.setText("Stop Bluetooth");
            cold.setImageResource(R.color.green);
            }
            else if(!bt.isEnabled()){
                flag_bt_state=0;
                button.setText("Start Bluetooth");
            cold.setImageResource(R.color.red);



}
//Bluetooth Button Click Listener
    button.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {

           if(bt.isEnabled()) {
               flag_bt_state = 1;
               button.setText("Stop Bluetooth");
               cold.setImageResource(R.color.green);
           }
           else if(!bt.isEnabled()){
               flag_bt_state=0;
               button.setText("Start Bluetooth");
               cold.setImageResource(R.color.red);

           }

            if(flag_bt_state==0 ){


                Intent enableBtIntent = new



Intent(ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, Request_code);


                        button.setText("Stop Bluetooth");
                        flag_bt_state=1;
                        cold.setImageResource(R.color.green);


                    }

                    else if(flag_bt_state==1){

                        button.setText("Start Bluetooth");
                        bt.disable();
                        bt_disabled.show();
                        flag_bt_state=0;
                        cold.setImageResource(R.color.red);
                    }
               }
           });

            cb1.setChecked(true);
      // cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
       //     @Override
         //   public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
           //     if(b){
             //       Toast.makeText(getApplicationContext(), "checked", Toast.LENGTH_SHORT).show();
//
  //              }else{
    //                Toast.makeText(getApplicationContext(), "unchecked", Toast.LENGTH_SHORT).show();
      //          }
        //    }
        //});






 }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Toast bt_enabled = Toast.makeText(getApplicationContext(), "Bluetooth Enabled", Toast.LENGTH_SHORT);
        Toast bt_Permission_denied = Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT);
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Request_code){
            if(resultCode == RESULT_OK){

                bt_enabled.show();
                cold2.setImageResource(R.color.green);
            }
            else
            {
               bt_Permission_denied.show();
                flag_bt_state = 0;
                button2.setText("Start Bluetooth");
                cold2.setImageResource(R.color.red);
            }

        }

}

}

Layoutfile.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.vivek.trackblue.MainActivity"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">


<ImageView
    android:id="@+id/imageView"
    android:layout_width="155dp"
    android:layout_height="39dp"
    android:src="@color/red"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.034" />

<Button
    android:id="@+id/button5"
    android:layout_width="152dp"
    android:layout_height="40dp"
    android:text="Start Bluetooth"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.034"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintLeft_creator="1" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="Make Device Discoverable"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.471"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.125" />

</android.support.constraint.ConstraintLayout>

logcat

05-01 18:42:17.017 12720-12720/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.vivek.trackblue, PID: 12720
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vivek.trackblue/com.example.vivek.trackblue.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3163)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3273)
                                                       at android.app.ActivityThread.access$1000(ActivityThread.java:219)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1735)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:145)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6959)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference
                                                       at com.example.vivek.trackblue.MainActivity.onCreate(MainActivity.java:100)
                                                       at android.app.Activity.performCreate(Activity.java:6609)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3116)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3273) 
                                                       at android.app.ActivityThread.access$1000(ActivityThread.java:219) 
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1735) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                       at android.os.Looper.loop(Looper.java:145) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:6959) 
                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                       at java.lang.reflect.Method.invoke(Method.java:372) 
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

 

when there is no checkbox operations like setOncheckedListener(), .onChecked(), etc, the application runs correctly and displays the checkbox in the Activity. But when I add a method to the checkbox variable the app starts and immediately stops with the message "Unfortunately, TrackBlue stopped responding". Also I am unable to figure out the source of the error.




Aucun commentaire:

Enregistrer un commentaire