Reputation: 25
I created a listView that is based on the user input. User has to enter text in an editText and then it's added into the list. It works great. My question though, is how do I save this data so even when they close the app, and then open it back up again, the listView still has the items in it from last time? Here is my code:
MainActivity.java
package com.kass.planner2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity implements View.OnClickListener {
private Button btn;
private EditText et;
private ListView lv;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(this);
et = (EditText)findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
lv=(ListView)findViewById(R.id.listView);
lv.setAdapter(adapter);
}
public void onClick(View v)
{
String input = et.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.kass.planner2.MainActivity"
android:weightSum="1">
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_weight="1.12">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="60dp"
android:layout_alignEnd="@+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:onClick="saveEvent"/>
<ListView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="@+id/listView"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:layout_toEndOf="@+id/editText" />
</RelativeLayout>
</LinearLayout>
Thank you.
Upvotes: 0
Views: 5845
Reputation: 2113
If you don't want to use the database, here is a trick that might help you with using file handling with a little logic
public void writeData(String data) // to writeData to file
{
String fileName="listData.txt";
try {
FileOutputStream fileout=openFileOutput(fileName, MODE_APPEND);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(data);
outputWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String readFile()
{
String fileName="listData.txt";
String line,data="";
try {
FileInputStream fIn = openFileInput ( fileName ) ;
InputStreamReader isr = new InputStreamReader ( fIn ) ;
BufferedReader br = new BufferedReader ( isr ) ;
while((line=br.readLine())!=null)
{
data=data+line;
}
isr.close ( ) ;
} catch ( IOException ioe ) {
ioe.printStackTrace ( ) ;
}
return data;
}
Here are the methods to have to call
public void storeData() // call this in the onclick
{
String res="";
res= res + editText().getText().toString() + "\n"; // used \n as delimiter
writeData(res);
}
Now here is the trick. In the oncreate, call the splitIntoList() method , before creating the arrayadapter
public void splitIntoList()
{
String result=readFile();
//Here is a little logic
StringTokenizer st=new StringTokenizer(result,"\n");
while(st.hasMoreTokens())
{
list.add(st.nextToken());
}
}
Please check for errors because I haven't ran this code on the IDE
Upvotes: 0
Reputation: 313
Considering you are still learning I suggest you start with using the SQLite methods. http://www.tutorialspoint.com/android/android_sqlite_database.htm
For a quicker and cleaner implementation you could use an ORM like SugarORM: http://satyan.github.io/sugar/
They have simple to follow commands that could be used to easy build databases and extract data from them.
Upvotes: 1
Reputation: 2520
Listview, as the name suggests is a View
which can show data. It doesn't actually saves data. To save the data, you have to use a database or SharedPreferences
. Normally shared preferences are used to save quick settings of the app.
To save data, you need to use the SQLite database present in each android device. This is done using SQLiteDatabase
and SQLiteOpenHelper
classes in android.
To bind the data to a view like a ListView which shows multiple data rows at once, you need to use an adapter. A SimpleCursorAdapter
class does this job easily.
You can find a tutorial here for binding data to controls like TextView
here. It will give you an idea of how to set up a database on your device.
Once you've done that, you can read about SimpleCursorAdapter
here.
Upvotes: 1