0

I'm trying to do a to-do list where when I add a new element on the listView the file where the data is stored automatically saves the changes.

The problem appears when I call the method listView.getChildAt(i) because it returns null.

The function is called after adding a new element on the list and after calling adapter.notifyDataSetChanged() method.

public void save(){
        int i = 0;
        View row= null;
        CheckBox x;
        File archive = new File(getExternalFilesDir(null),"file.txt");
        //list has been declared before
        try{
            PrintWriter fOUT = new PrintWriter(archive);
            for(String article : list){

                row = (View) listView.getChildAt(i);
                x = (CheckBox) row.findViewById(R.id.check);

                if(x.isChecked())
                {
                    fOUT.println(article+";1");
                }
                else
                {
                    fOUT.println(article+";0");
                }
                i++;
            }
            fOUT.close();
            MediaScannerConnection.scanFile(this,new String[]{archive.getPath()},null,null);
        }
        catch(IOException ignored){
        }
    }

Here there is the XML layout of the ListItem

<?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"
    android:minHeight="40dp"
    >
    <TextView
        android:id="@+id/testo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="5dp"
        android:layout_toStartOf="@+id/check"
        android:shadowColor="#000000"
        android:shadowRadius="5"
        android:textColor="@color/bianco"
        android:textSize="15sp"
        android:textStyle="bold" />

    <ImageButton
        android:id="@+id/bottone"
        android:layout_width="28dp"
        android:layout_height="28dp"
        android:layout_centerVertical="true"
        android:layout_alignParentEnd="true"
        android:onClick="rimuovi"
        android:background="@drawable/my_icon_delete" />
    <CheckBox
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toStartOf="@+id/bottone"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="formattazioneTesto"
        android:checked="false"/>
</RelativeLayout>
Mattia
  • 3
  • 2

0 Answers0