Search code examples
javaandroidlistviewfile-iofileoutputstream

Writing data from a ListView to a Text File on Android


I'm new to Java and Android and am trying to figure out how to write a ListView and load the ListView from where it is saved.

I have ListView and each item on the ListView has a string and bool that changes if a checkbox for the item is checked or unchecked. I have a working method to add items to the ListView and am now trying to figure out how to write the ListView to a textfile.

I got some code for saving the ListView by clicking a menu item and them I'm trying to load it when I re-run the program in my OnCreate, but nothing is loading. I'm not sure if its the write or load that is not working or both.

Here is a class I made that works with my ListView.

Item.java

public class Item {
String name;
boolean isChecked = false;

public Item(String name) {this.name = name;}

public Item(String name, boolean checked){
    this.name = name;
    this.isChecked = checked;

}
@Override
public String toString(){
    return name;
}
}

Here is my MainActivity.java that includes my saveList() and readFile()

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getName();
ArrayList<Item> items = new ArrayList<>();
private ListView lv;
private static final String sFile = "Saved.txt";
protected ListView getListView() {
    if (lv == null) {
        lv = (ListView) findViewById(android.R.id.list);
    }
    return lv;
}

protected void setListAdapter(ListAdapter adapter) {
    getListView().setAdapter(adapter);
}

protected ListAdapter getListAdapter() {
    ListAdapter adapter = getListView().getAdapter();
    if (adapter instanceof HeaderViewListAdapter) {
        return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
    } else {
        return adapter;
    }

}

private void deleteList()
{
    if (!items.isEmpty())
    {
        items.clear();
    }
    lv.invalidateViews();
}

private void deleteCheckedItems()
{
    SparseBooleanArray checked = lv.getCheckedItemPositions();
   for(int i = 0; i < lv.getCount(); i++)
    {
        if (checked.get(i)==true)
        {
            items.remove(i);
        }
        lv.invalidateViews();
    }

    lv.clearChoices();

}

private void saveList(ArrayList<Item> itemlist) {
    try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput(sFile, 0));
        int iCnt = 0;
        String allstring = "";
        for (Item s : items)
        {
            if (s.isChecked)
            {
                iCnt++;
                if (iCnt < items.size()) {
                    String thisstring;
                    thisstring = s.name + "\r\n";
                    out.write(thisstring);
                    allstring += thisstring;
                } else {
                    String thisstring;
                    thisstring = s.name;
                    out.write(thisstring);
                    allstring += thisstring;
                }
            }

        }
        out.close();
        //Toast.makeText(activity, allstring + " Written", duration).show();
    }
    catch (java.io.FileNotFoundException e)
    {

    }
    catch (Exception ex)
    {
      //  Toast.makeText(activity, "Write Exception : " + ex.getMessage(), duration).show();
    }

}

public String readFile(ArrayList<Item> itemsList)
{
    String sRet = "Nothing";

    try
    {
        InputStream is = openFileInput(sFile);
        if (is != null)
        {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String sLine;
            StringBuffer sb = new StringBuffer();

            while ((sLine = br.readLine()) != null)
                sb.append(sLine + "\r\n");

            is.close();
            sRet = sb.toString();
           // Toast.makeText(Toast.LENGTH_LONG).show();
        }
    }

    catch (java.io.FileNotFoundException e)
    {

    }

    catch (Exception ex)
    {
     //   Toast.makeText(activi"Read Exception" + ex.getMessage(), Toast.LENGTH_LONG).show();
    }

    return sRet;
}


private void addItemDialog()
{

    LayoutInflater inflater = LayoutInflater.from(this);
    final View addView = inflater.inflate(R.layout.add, null);

    new AlertDialog.Builder(this)
            .setTitle("Add Item")
            .setView(addView)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    EditText txtAdd = (EditText) addView.findViewById(R.id.etInput);
                    String sItem = (txtAdd).getText().toString();
                    items.add(new Item(sItem));
                    for (int i = 0; i < items.size(); i++)
                    {
                        lv.setItemChecked(i, items.get(i).isChecked);
                    }

                }

            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                        }
                    }).show();
}


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

    setListAdapter(new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_multiple_choice, items));

    lv = this.getListView();
    for (int i = 0; i < items.size(); i++)
    {
        lv.setItemChecked(i, items.get(i).isChecked);
    }
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    readFile(items);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {


    switch(item.getItemId()){
        case R.id.add_item:
            addItemDialog();
            return true;
        case R.id.clear_all:
            deleteList();
            return true;
        case R.id.clear_checked:
            deleteCheckedItems();
            return true;
        case R.id.write:
            saveList(items);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }


}
}

Solution

  • put your oncreate method above after declaration that means after this line

         private static final String sFile = "Saved.txt";
          @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
            .......
            .......
            //your code
            }
    
        //other method
    

    Read Android activity lifecyle for better understanding