0
votes

So I've been trying to register when a checkbox is toggled. So far I haven't had any luck. Would a onClickListener be appropriate for this case? When I try to use one it shows up I receive an error.

MainActivity.java

  private static final String TAG = "MainActivity";
    private HabitHelper mHelper;
    private ListView mHabitView;
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHelper = new HabitHelper(this);
        mHabitView = (ListView) findViewById(R.id.habitList);

        FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.addHabit);
        CheckedTextView chkBox = (CheckedTextView) findViewById(R.id.habitItem);

        myFab.setOnClickListener(this);


        chkBox.setOnClickListener(this);

        updateUI();
    }

    public void onClick (View v){

        final EditText habitText = new EditText(this);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("Add a new habit")
                .setMessage("What habit would you like to start working on?")
                .setView(habitText)
                .setPositiveButton("Add", new DialogInterface.OnClickListener(){
            @Override
                    public void onClick(DialogInterface dialog, int which) {
                String habit = String.valueOf(habitText.getText());
                SQLiteDatabase db = mHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(HabitContract.HabitEntry.COLUMN_NAME_TITLE, habit);
                db.insertWithOnConflict(HabitContract.HabitEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                db.close();
                updateUI();

            }
        })
                .setNegativeButton("Cancel", null)
                .create();
                dialog.show();

    }


    public class CheckBoxClick implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            CheckedTextView ctv = (CheckedTextView)arg1.findViewById(R.id.habitItem);
            if (ctv.isChecked()){
                Toast.makeText(MainActivity.this, "You have completed your habit for the day", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(MainActivity.this, "Make sure you complete your task before checking me!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void updateUI(){
        ArrayList<String> habitList = new ArrayList<>();
        SQLiteDatabase db = mHelper.getReadableDatabase();
        Cursor cursor = db.query(HabitContract.HabitEntry.TABLE, new String[]{HabitContract.HabitEntry._ID, HabitContract.HabitEntry.COLUMN_NAME_TITLE}, null, null, null, null, null);
        while (cursor.moveToNext()){
            int idx = cursor.getColumnIndex(HabitContract.HabitEntry.COLUMN_NAME_TITLE);
            habitList.add(cursor.getString(idx));
        }
        if (mAdapter == null){
            mAdapter = new ArrayAdapter<>(this, R.layout.item_habit, R.id.habitItem, habitList);
            mHabitView.setAdapter(mAdapter);
        }
        else {
            mAdapter.clear();
            mAdapter.addAll(habitList);
            mAdapter.notifyDataSetChanged();
        }
        cursor.close();
        db.close();
    }

    private void deleteHabit(View view){
        View parent = (View) view.getParent();
        TextView habitTextView = (TextView) parent.findViewById(R.id.habitItem);
        String habit = String.valueOf(habitTextView.getText());
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.delete(HabitContract.HabitEntry.TABLE, HabitContract.HabitEntry.COLUMN_NAME_TITLE + " = ?", new String[] {habit});
        db.close();
        updateUI();
    }}

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.jonathan.myapplication.MainActivity"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp">


    <ListView
        android:id="@+id/habitList"
        android:layout_width="0dp"
        android:layout_height="0dp"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginEnd="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="8dp"
        tools:layout_constraintLeft_creator="1"
        android:layout_marginBottom="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/addHabit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        app:fabSize="mini"
        app:srcCompat="@android:drawable/ic_input_add"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintRight_toRightOf="parent"
        tools:ignore="RtlHardcoded" />
</android.support.constraint.ConstraintLayout>

item_habit.xml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">


    <CheckedTextView
        android:id="@+id/habitItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:checkMark="?android:attr/listChoiceIndicatorMultiple"
        android:padding="5dp"
        android:checked="false"
        android:clickable="true"
        android:focusable="true"
        android:text=""
        />

</RelativeLayout>

Error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jonathan.myapplication/com.example.jonathan.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckedTextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckedTextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.jonathan.myapplication.MainActivity.onCreate(MainActivity.java:50) at android.app.Activity.performCreate(Activity.java:6975) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6541)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

2
try using setOnCheckedChangeListener instead of onClickListener on the checkboxchornge
NullPointerException !!!!!!!!!!!!!!!!!!!!!!!greenapps

2 Answers

1
votes

You arent creating views for your ListView, and your CheckedTestView is not inside the layout.

The place you try to set a listener for it actually should be inside the ListAdapter where your CheckedTestViews will be created on.

I see, you used CursorAdapter, you can check clicks then into the listView trough:

 listView.setOnItemClickListener(new OnItemClickListener(){/**/});

But you have to remove the chb.setOnClickListener(this) since they are items on a list, and not a single view in the layout.

0
votes

Your CheckedTextView is part of item_habit.xml and not activity_main.xml chBox will obviously be null and hence it's throwing Null pointer exception.

I am not sure if you have an adapter and not included it here or you don't have an adapter. If later is the case,I would suggest to correct your list view and adapter initializations. If you have an adpater, you should have ckeckedchangelistener in your GetCell() method of adapter.