2

Previously I create a ticket because I have this error

Attempt to invoke interface method 'int java.util.List.size()' on a null object reference?

I have this error when I wanted to close all applications in my phone to have less memory on it.

I show you all my files before my modification

List.java

public class List extends AppCompatActivity implements ItemDialog.ItemDialogListener, AdapterView.OnItemClickListener {
    private ListView listView ;

    private Button addBtn ;
    private ArrayList<EltList> eltList ;
    private ArrayAdapter<EltList> adapter ;

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

        addBtn = findViewById(R.id.addTask);
        listView = findViewById(R.id.listView);

        eltList = FileHelper.readData(this);
        adapter = new TextAdapter(this,eltList);

        listView.setAdapter(adapter);

        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openDialog();
            }
        });
        listView.setOnItemClickListener(this);

    }

    public void openDialog(){
        ItemDialog itemDialog = new ItemDialog();
        itemDialog.show(getSupportFragmentManager(),"example dialog");
    }

    @Override
    public void applyText(String newTask, String newDateTimeTask) {
        EltList elt = new EltList(newTask,newDateTimeTask);
        adapter.add(elt);

        FileHelper.writeData(eltList,List.this);
        Toast.makeText(List.this,"Item added",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        eltList.remove(position);
        adapter.notifyDataSetChanged();
        FileHelper.writeData(eltList,this);
        Toast.makeText(this,"Delete",Toast.LENGTH_SHORT).show();
    }
}

TextAdapter.java

public class TextAdapter extends ArrayAdapter<EltList> {

    public TextAdapter(Context context, java.util.List<EltList> eltList){
        super(context,0,eltList);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item,parent,false);
        }

        ItemList itemList = (ItemList) convertView.getTag();
        if(itemList == null){
            itemList = new ItemList();
            itemList.taskName = convertView.findViewById(R.id.task);
            itemList.taskDate = convertView.findViewById(R.id.task_date) ;

            convertView.setTag(itemList);
        }

        EltList eltList = getItem(position);
        itemList.taskName.setText(eltList.getTaskName());
        itemList.taskDate.setText(eltList.getTaskDate());

        return convertView ;

    }

    private class ItemList{
        public TextView taskName ;
        public TextView taskDate ;
    }
}

FileHelper

public class FileHelper {
    public static final String FILENAME = "file.dat";

    public static void writeData(ArrayList<EltList> items, Context context){
        try{
            FileOutputStream fos = context.openFileOutput(FILENAME,Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(items);
            oos.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }

    }

    public static ArrayList<EltList> readData(Context context){
        ArrayList<EltList> itemList = null ;
        try{
            FileInputStream fis = context.openFileInput(FILENAME);
            ObjectInputStream ois = new ObjectInputStream(fis);
            itemList = (ArrayList<EltList>) ois.readObject();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();

            itemList = new ArrayList<>();
        }
        catch (IOException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return itemList ;
    }

}

So I modify this

ArrayList<EltList> itemList = null ;

in my FileHelper by

ArrayList<EltList> itemList = new ArrayList<>() ;

It works but if I previously write tasks it removes it.

So I remove keep ArrayList<EltList> itemList = null and I wanted to catch the error with NullPointerException but it doesn't work.

UPDATE

It's not a duplicate I just wanted to explain why all my previous task were clear, my answer is how can I keep my previous task in my list.

Soleyne
  • 77
  • 8
  • Seems you are passing `null` list to your adapter and when `adapter` tries to get `size()` of `list` throws `exception` – Yupi Sep 02 '19 at 13:07
  • @Yupi yes I know as I say I resolve it but know my error is If I replace ArrayList itemList = null by ArrayList itemList = new ArrayList<>() I have no error it works but I previously wrote task all my task are removed. – Soleyne Sep 02 '19 at 13:14
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Rogue Sep 02 '19 at 14:18
  • Personally, in this situation, I would "bubble up"/not catch/rethrow the `IOException` and `FileNotFoundException`, since if they occur you don't really have a valid case to handle the errors. Bubble it up to code which can eloquently handle it, like your `#onCreate` method. Then you don't have to worry about the null case for your list. – Rogue Sep 02 '19 at 14:24
  • @Rogue it's not a duplicate because it's actually not my error, I previously I have this error but I try to something so I don't have the error but all my task in the list are removed if I replace ArrayList itemList = null by ArrayList itemList = new ArrayList <> (). And I don't understand what do you want to say. I just wanted to improve myself with android. – Soleyne Sep 02 '19 at 14:32
  • Well, if you really want to improve, [I would take a look at Oracle's online tutorials](https://docs.oracle.com/javase/tutorial/java/index.html). They're quite up-to-date and in-depth. In short, you put a bandaid on the problem (now instead of a null list, it's a brand-new empty list whenever you have an error). The real problem is you're getting an error in #readData which is preventing you from filling the list in the first place. So don't catch those errors, and instead throw them from the #readData method, and handle them when you call #readData. – Rogue Sep 02 '19 at 14:39
  • More on exceptions: https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html. In general, this is called the "XY problem". You're asking how to fix your list being null/empty/etc, but the answer lies in not giving it any opportunity to be such. As for why the IOException/FileNotFoundException is getting thrown, that'd be due to whatever conditions are within your tests. E.g. calling #readData when there isn't a file before #writeData is called. At the heart of it all though, this seems like a major sidestep taken just for sharing data within the same program. – Rogue Sep 02 '19 at 14:47
  • @Rogue but if I don't #readData I don't know if my list is null. Thank you for your help. – Soleyne Sep 02 '19 at 14:59
  • @Rogue the problem is I previously have the same code without my TextAdapter and it works well even if I close the application. The difference in the 2 project is my adapter and the ArrayList because previously it was a list of string. – Soleyne Sep 02 '19 at 15:06
  • That's what I'm saying, if `#readData` threw a `FileNotFoundException`, or always generated a new blank file, that's an easy fix after that. You're stuck in the face-value details of the problem, and missing the bigger picture. Not "why did the list become null", but "why is #write overwriting bad data" and "why is #read failing" – Rogue Sep 02 '19 at 15:20
  • @Rogue I add #write before #read I have the same error I try to do : File file = context.getFileStreamPath(FILENAME); if(file.exists()){ doSomething(); } else{ Log.d("ERROR","FILE NOT FOUND"); return null ; } the file exists if i create it with #write before call #read but I don't know why when I close all the application it clear my file. – Soleyne Sep 02 '19 at 16:08

0 Answers0