I have created an array. I want to be able to save it and have it load when the app is closed from memory. . I did some research and found you can use use these commands: SaveArrayListToSD and ReadArrayListFromSD.
However, I don't know how to relate these to the rest of my code...
How do I save and load the array when the app is opened/closed?
After further research, I have changed my mind about the SQLite database - I don't mind using it if it's easier. If I was to use an SQLite database, how would I go about saving my arraylist into the database?
Code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) { //Rendering the UI
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Creating Array of Strings
final ArrayList todoItems = new ArrayList();
final ArrayAdapter aa;
aa = new ArrayAdapter(this,android.R.layout.simple_list_item_1,
todoItems);
myListView.setAdapter(aa);
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
return true;
}
return false;
}
});
}
public static void SaveArrayListToSD(Context mContext, String savedArray, ArrayList todoItems) {
try {
FileOutputStream fos = mContext.openFileOutput(savedArray + ".dat", mContext.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(todoItems);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object ReadArrayListFromSD(Context mContext,String savedArray){
try {
FileInputStream fis = mContext.openFileInput(savedArray + ".dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj= (Object) ois.readObject();
fis.close();
return obj;
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<Object>();
}
}
}
You can use internal storage to save the strings in you ArrayList. Here is more info on using internal storage. You can write the data in onStop or onDestory and read the data in onCreate.
Well i can write you simple example for you.
initialise SQLite
SQLiteDatabase db = db=openOrCreateDatabase("yourDBName", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Employee(id VARCHAR,name VARCHAR,email VARCHAR);");
db.execSQL("INSERT INTO student VALUES('"+idField.getText()+"','"+nameTextfield.getText()+"','"+emailtextfield.getText()+"');");
db.execSQL("DELETE FROM Employee WHERE id='"+idField.getText()+"'");
db.execSQL("UPDATE Employee SET name='"+nameTextfield.getText()+"',email='"+emailTextfield.getText()+"'WHERE id='"+idField.getText()+"'");
And to Select from database please follow this
Cursor c=db.rawQuery("SELECT * FROM Employee WHERE id='"+idField.getText()+"'", null);
if(c.moveToFirst()){
//String id = c.getString(0);
String name = c.getString(1);
String email = c.getString(2);
}
Related
I am new to Android. I am running SQLite Filter ListView. I added an EditText, priceEditTxt, in the dialog box and another column "Price " in the database. When I search or click the save button, the application stops. I don't know how to solve it.
The Display() function has two EditText and one save button. When I click the save button, the application, unfortunately, stops working.
The getPlanet() function is used to show a search list when I click on the searchview. I don't have much understanding about it.
MainActivity.java:
private void displayDialog()
{
Dialog d=new Dialog(this);
d.setTitle("SQLite Database");
d.setContentView(R.layout.dialog_layout);
nameEditText= (EditText) d.findViewById(R.id.nameEditTxt);
**////////////////////Price edit text which I add/////////////**
priceEditText= (EditText) d.findViewById(R.id.priceEditTxt);
saveBtn= (Button) d.findViewById(R.id.saveBtn);
retrieveBtn= (Button) d.findViewById(R.id.retrieveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
save(nameEditText.getText().toString(),priceEditText.getText().toString());
}
});
retrieveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getPlanets(null);
}
});
d.show();
}
** //save button took one argument "name" only, i add "price" later//**
private void save(String name,String price)
{
DBAdapter db=new DBAdapter(this);
db.openDB();
if(db.add(name,price))
{
nameEditText.setText("");
priceEditText.setText("");
}else {
Toast.makeText(this,"Unable To Save",Toast.LENGTH_SHORT).show();
}
db.closeDB();
this.getPlanets(null);
}
private void getPlanets(String searchTerm)
{
planets.clear();
DBAdapter db=new DBAdapter(this);
db.openDB();
Planet p=null;
Cursor c=db.retrieve(searchTerm);
while (c.moveToNext())
{
int id=c.getInt(0);
String name=c.getString(1);
p=new Planet();
p.setId(id);
p.setName(name);
planets.add(p);
}
db.closeDB();
lv.setAdapter(adapter);
}
DBAdapter.java contains the add and retrieve functions, which I call from MainActivity.
DBAdapter.java:
public class DBAdapter {
Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context c) {
this.c = c;
helper=new DBHelper(c);
}
//OPEN DB
public void openDB()
{
try
{
db=helper.getWritableDatabase();
}catch (SQLException e)
{
e.printStackTrace();
}
}
//CLOSE
public void closeDB()
{
try
{
helper.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
//INSERT DATA
public boolean add(String name,String price)
{
try
{
ContentValues cv=new ContentValues();
cv.put(Constants.NAME, name);
cv.put(Constants.PRICE, price);
//Log.d(Constants.PRICE,"here we gooooooooooooooooooooooooooooooooooooooooooooooooooo");
db.insert(Constants.TB_NAME, Constants.ROW_ID, cv);
return true;
}catch (SQLException e)
{
e.printStackTrace();
}
return false;
}
//RETRIEVE DATA AND FILTER
public Cursor retrieve(String searchTerm)
{
String[] columns={Constants.ROW_ID,Constants.NAME};
Cursor c=null;
if(searchTerm != null && searchTerm.length()>0)
{
String sql="SELECT * FROM "+Constants.TB_NAME+" WHERE "+Constants.NAME+" LIKE '%"+searchTerm+"%'";
c=db.rawQuery(sql,null);
return c;
}
c=db.query(Constants.TB_NAME,columns,null,null,null,null,null);
return c;
}
}
Constants.java contains the creatable and droptable query. I don't know if create table query is right or not.
Constants.java:
public class Constants {
//COLUMNS
static final String ROW_ID="id";
static final String NAME="name";
static final String PRICE="price";
//DB
static final String DB_NAME="ii_DB";
static final String TB_NAME="ii_TB";
static final int DB_VERSION=2;
//CREATE TB
static final String CREATE_TB="CREATE TABLE ii_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL,price TEXT NOT NULL);";
//DROP TB
static final String DROP_TB="DROP TABLE IF EXISTS "+TB_NAME;
}
You are creating different instances of DBAdapter for each operation and opening a new connection to the database on these operations. Also, you are closing these connections each time you are done with the operation.
Trying to get a new connection to your database is expensive, as stated here: Persisting database connection. The database is probably not open or not ready when you do a new operation to your database.
Knowing these simple things, we probably would assume that dbAdapter.openDB() may throw an exception when the database is not yet ready. Thus, leaving the variable db still be equal to null. I assume that your error is NullPointerException and because of this, you cant do operations to your database.
TL;DR
Create a single instance of DBAdapter. Call openDB once. And call closeDB on destroy.
More or Other Sources
Kevin Galligan's Answer for Best Practices
I want to show my data from sqlite to Custom ListView (java , Android studio , sqlite ).
But it's force stop.
picture from my Main Activity:
picture from my Database class:
Please Help me!!!!
(my English is not good sorry but can i understand your words)
first you have to create a custom adapter for your listview and populate that adapter with listview and your code should be like this
and to get the data from database create a method in database class name getdata() take it in a form of cursor
public class UserDbHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "DATABASENAME2";
public static final int DB_VERSION = 3;
public static final String TABLE_NAME = "student";
public static final String DEVICE = "device"; //your coloumn
public static final String ADDRESS = "address";//your coloumn
public static final String Date = "Date"; //your coloumn
public String CREATE_QUERY = "CREATE TABLE "+TABLE_NAME+"("+DEVICE+" TEXT,"+ADDRESS+" TEXT,"+Date+"TEXT);";
public UserDbHelper(Context context)
{
super(context,DATABASENAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_QUERY);
}
public List<Datalist> getdata()
{
List<Datalist> result = new ArrayList<>();
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM Table_name,null";);
while (c.moveToNext()) {
result.add(
new Datalist(
c.getString(c.getColumnIndex("YOUR COLOUMN")),
c.getString(c.getColumnIndex("YOUR COLOUMN")),
date
)
);
}
c.close();
return result;
}
and populate your database with listview
this will be in your button click that button which retrive the data
List<Datalist> itemFromDatabase = getItemFromDatabase();
MyAdapter adapter = new MyAdapter(getApplicationContext(), 0, itemFromDatabase);
listOfDatabaseObject.setAdapter(adapter);
adapter.notifyDataSetChanged();
MainActivity.java
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDbHelper;
List<String> stringList;
ListView listView;
List<Mivejat> mivejatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDbHelper = new DataBaseHelper(this);
stringList = new ArrayList<>();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
myDbHelper = new DataBaseHelper(this);
mivejatList = myDbHelper.MiveName();
for (int i = 0 ; 0 < mivejatList.size() ; i++) {
stringList.add(mivejatList.get(i).name);
}
listView = (ListView) findViewById(R.id.listViewMive);
mainListViewClass mainListViewClass = new mainListViewClass(MainActivity.this , stringList);
listView.setAdapter(mainListViewClass);
mainListViewClass.notifyDataSetChanged();
myDbHelper.close();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDbHelper;
List<String> stringList;
ListView listView;
List<Mivejat> mivejatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDbHelper = new DataBaseHelper(this);
stringList = new ArrayList<>();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
myDbHelper = new DataBaseHelper(this);
mivejatList = myDbHelper.MiveName();
for (int i = 0 ; 0 < mivejatList.size() ; i++) {
stringList.add(mivejatList.get(i).name);
}
listView = (ListView) findViewById(R.id.listViewMive);
mainListViewClass mainListViewClass = new mainListViewClass(MainActivity.this , stringList);
listView.setAdapter(mainListViewClass);
mainListViewClass.notifyDataSetChanged();
myDbHelper.close();
}
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/mivejat.rezaahmadpour.ir.mivejat/databases/";
private static String DB_NAME = "KhavasMiveha.db";
public static final int DB_VERS = 1;
private SQLiteDatabase myDataBase;
private final Context myContext;
private static String TAG = "KhavasMiveha.db";
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERS);
this.myContext = context;
}
/**
* Creates an empty database on the system and rewrites it with your own
* database.
*/
public boolean createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
Log.d(TAG, "database already exist");
//Running this method causes SQLite class checking for if New DB Version Exists and runs upgrade method
getReadableDatabase();
close();
return true;
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
return false;
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transferring bytestream.
*/
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "UPGRADING Database...");
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
public List<Mivejat> MiveName() {
String query = "SELECT Name FROM tbl_mive";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
List<Mivejat> result = new ArrayList<>();
Mivejat m;
while (cursor.moveToNext()) {
m = new Mivejat();
m.name = cursor.getString(0);
result.add(m);
}
return result;
}
I am trying to implement an activity, that has 3 spinners (drop down lists) each of which are populated by a different table from an sqlite database. I managed to create one spinner that is populated correctly, but i am having trouble creating the other two and populating them correctly.
this is my main activity so far:
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener {
private DBManager data;
private SQLiteDatabase db;
private final String DB_NAME = "hanakolfein.s3db";
private Spinner spinner;
List<String> list;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Spinner sp1, sp2, sp3;
sp1 = (Spinner) findViewById(R.id.spinner1);
sp2 = (Spinner) findViewById(R.id.spinner2);
sp3 = (Spinner) findViewById(R.id.spinner3);
sp1.setOnItemSelectedListener(null);
sp2.setOnItemSelectedListener(null);
sp3.setOnItemSelectedListener(null); */
data = new DBManager(this, DB_NAME);
db = data.openDataBase();
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
loadSpinner();
}
private void loadSpinner() {
Set<String> set = data.getAllData();
List<String> list = new ArrayList<String>(set);
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setWillNotDraw(false);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
and this is my database manager:
public class DBManager extends SQLiteOpenHelper {
//Path to the device folder with databases
public static String DB_PATH;
//Database file name
public static String DB_NAME;
public SQLiteDatabase database;
public final Context context;
public final static int DB_VERSION = 6;
public SQLiteDatabase getDb() {
return database;
}
public DBManager(Context context, String databaseName) {
super(context, databaseName, null, DB_VERSION);
this.context = context;
//full path to the databases
String packageName = context.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
DB_NAME = databaseName;
openDataBase();
}
//This piece of code will create a database if it’s not yet created
public void createDataBase() {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e(this.getClass().toString(), "Copying error");
throw new Error("Error copying database!");
}
} else {
Log.i(this.getClass().toString(), "Database already exists");
}
}
//Performing a database existence check
private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
try {
String path = DB_PATH + DB_NAME;
checkDb = SQLiteDatabase.openDatabase(path, null,SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
Log.e(this.getClass().toString(), "Error while checking db");
}
//Android doesn’t like resource leaks, everything should
// be closed
if (checkDb != null) {
checkDb.close();
}
return checkDb != null;
}
//Method for copying the database
private void copyDataBase() throws IOException {
//Open a stream for reading from our ready-made database
//The stream source is located in the assets
InputStream externalDbStream = context.getAssets().open(DB_NAME);
//Path to the created empty database on your Android device
String outFileName = DB_PATH + DB_NAME;
//Now create a stream for writing the database byte by byte
OutputStream localDbStream = new FileOutputStream(outFileName);
//Copying the database
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
//Don’t forget to close the streams
localDbStream.close();
externalDbStream.close();
}
public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (database == null) {
createDataBase();
database = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
}
return database;
}
#Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}
public Set<String> getAllData() {
Set<String> set = new HashSet<String>();
String selectQuery = "select * from cuisine";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return set;
}
#Override
public void onCreate(SQLiteDatabase db) {}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
Alright, first of all you should not query your database from the main Thread.
I recommend using a Loader as described here. You can have as many Loaders as you like, in your case 1 for each Spinner (just make sure to give them different IDs).
You need to clear that arraylist which you pass to arrayadapter. Because when you use first spinner, you are calling gatAllData & storing that data in arraylist, passing it to arrayadapter. Next time for second spinner you are doing same procedure but it is concatenating to previous entries of arraylist. So before calling to getAllData you need to clear your arraylist. It'll solve your problem.
Im working on an app and in it i made an arraylist of strings.
i searched for ways to save the list for the next visit but i did not find a good one.
i tried shared preferences but didn't manage to make it work.
Can someone please help me find the way to save the data in the array list and restore it in every app visit ?
The array i want to save called here "ContactList".
I put my code below:
public class Work_Contacts extends Activity {
public static final int PICK_CONTACT = 1;
private ArrayList<String> contactList;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> contactList2;
private ArrayAdapter<String> arrayAdapter2;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_work__contacts);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
contactList=new ArrayList<String>();
contactList2=new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
arrayAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList2);
final ListView lv = (ListView) findViewById(R.id.ContactListView);
lv.setAdapter(arrayAdapter);
lv.setLongClickable(true);
lv.setClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
arrayAdapter.notifyDataSetChanged();
arrayAdapter.remove(arrayAdapter.getItem(pos));
Log.v("long clicked","pos: " + pos);
return true;
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int pos, long id) {
String url = "tel:"+arrayAdapter2.getItem(pos);
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
arrayAdapter.add(name + " - " + phoneNumber);
arrayAdapter.notifyDataSetChanged();
arrayAdapter2.add(phoneNumber);
arrayAdapter2.notifyDataSetChanged();
}
break;
}
}
}
}
I would store the list in sqlite. You can find many examples on the web on how to do this.
/**
* 序列化数据
*
* #param o
* #param file
*/
public static void serializationOfObject(Object o, File file) {
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(o);
oos.flush();
oos.close();
} catch (IOException e) {
Log.e("Utility", e.getMessage(), e);
}
}
/**
* 反序列化数据
*
* #param file
* #return
*/
public static Object deserializationOfObject(File file) {
if (!file.exists())
return null;
Object object = null;
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
object = ois.readObject();
ois.close();
} catch (Exception e) {
Log.e("Utility", e.getMessage(), e);
}
return object;
}
when you want to save,just call serializationOfObject(arraylist,file);
when you want to get,call (ArrayList<T>)deserializationOfObject(file);
hope to help you.
in my android application I have a Button which adds a new dynamic Spinner to the Layout. All of the created Spinners are using the same Array.
What is working until now, I can save the number of created Spinners and recreate them after restarting the Application.
But I really would like to save the selectedPosition of each Spinner in the sharedPreferences and this is where I'm stucking in a ForceClose Desaster...
In my understanding, every Spinner gets an ID when created so you can save the Position bounded on this ID in the preferences.
So this is what I did:
public void addSpinner(){
LinearLayout AddLayout = (LinearLayout)findViewById(R.id.linearAddScroll);
spinner = new Spinner(this);
ArrayAdapter<?> adapt = ArrayAdapter.createFromResource(this,
R.array.Filter, android.R.layout.simple_spinner_item);
adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapt);
AddLayout.addView(spinner);
}
this creates the Spinner.
public void onClick(View v) {
addSpinner();
int ID = 1000+x;
spinner.setId(ID);
Toast.makeText(MatReporterActivity.this,"ID" + ID, 5)
.show();
x++;
}
set the ID.
This is what I do in the on Create method:
x = settings.getInt("xsave", 1);
for(y = 1; y < x; y++){
addSpinner();
int ID = 1000+y;
Spinner s = (Spinner) findViewById(ID);
String ys= Integer.toString(ID);
Toast.makeText(MatReporterActivity.this,"ID" +ys, 5)
.show();
int yf = settings.getInt(ys, 1);
s.setSelection(yf);
}
And this onStop():
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("xsave", x);
for(y = 1; y < x; y++){
int ID = 1000+y;
Spinner s2= (Spinner) findViewById(ID);
int possS = s2.getSelectedItemPosition();
Toast.makeText(MatReporterActivity.this, "IDStop" + ID, 5)
.show();
String ys= Integer.toString(ID);
editor.putInt(ys, possS);
}
editor.commit();
}
I think there is a logical Problem in the onCreate Method, but I'm not able to find it, also I didn't find any help in the web how to populate and save dynamically created spinners.
So maybe someone has an idea.
thanks.
SharedPreferences are not a good way to store this kind of data. You should try to follow those 2 steps :
Create a class which implements Serializable to represent the data you want to store (you might use a list of Serializable objects)
public class SpinnerSave implements Serializable {
public String ID;
public int selection;
public SpinnerSave(String ID, int selection){
this.ID = ID;
this.selection = selection;
}
}
Then you should write your data into a file like so
private void saveState() {
final File cache_dir = this.getCacheDir();
final File suspend_f = new File(cache_dir.getAbsoluteFile() + File.separator + SUSPEND_FILE);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(this.gameState);
}
catch (Exception e) {
keep = false;
Log.e("MyAppName", "failed to suspend", e);
}
finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
if (keep == false) suspend_f.delete();
}
catch (Exception e) { /* do nothing */ }
}
}