I’m trying to save the elements of a list (added by the user via a dialog box) into a file so that it stays the same when reopened. For some reason it throws a nullPointerException when I add elements to it the second time (first time works nicely). This is how I save:
public void onPause(){
super.onPause();
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(salvare, 0));
for(int i=0; i<lista.orase.size(); i++){
out.write(lista.getItem(i)+"\n"); //ia fiecare element al listei si il scrie in fisier urmat de endline;
}
out.close();
System.out.println("ON PAUSE!");
} catch (Throwable t){
}
}
And this is how I retrieve onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lista=new ListaOrase(this);
buton=(Button)findViewById(R.id.buton);
setListAdapter(lista);
try {
InputStream in= openFileInput(salvare);
if(in!=null){
InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(tmp);
String str;
while(reader.readLine()!=null){
str=reader.readLine();
lista.add(str);
}
in.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The exception is thrown by this function (which worked beautifully before adding the save feature). It gets the intent from the dialog box and adds the element to the list.
public void onActivityResult (int requestCode, int responseCode, Intent data){
if(responseCode==1){
String s=data.getStringExtra("oras");
lista.add(s);
setListAdapter(lista);
}
}
What could possibly be the connection between them and how could I fix it?
The problem was that I wasn’t “refreshing” my ListAdapter. Along with notifyDataSetChanged() I readded setListAdapter(lista) as Chunhui suggested.