Created
December 12, 2010 00:48
-
-
Save zapnap/737753 to your computer and use it in GitHub Desktop.
Android ListActivity example using db4o
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example.events; | |
import java.text.SimpleDateFormat; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import com.db4o.Db4oEmbedded; | |
import com.db4o.ObjectContainer; | |
import com.db4o.ObjectSet; | |
import android.app.ListActivity; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.view.KeyEvent; | |
import android.widget.ArrayAdapter; | |
public class Events extends ListActivity { | |
private final static String TAG = "EVENTS"; | |
private ObjectContainer db = null; | |
private ArrayList<String> events = new ArrayList<String>(); | |
private ArrayAdapter<String> adapter; | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
getEvents(); | |
adapter = new ArrayAdapter<String>(this, | |
android.R.layout.simple_list_item_1, events); | |
setListAdapter(adapter); | |
addEvent("Hello, Android!"); | |
} | |
@Override | |
protected void onPause() { | |
db().close(); | |
super.onPause(); | |
} | |
@Override | |
public boolean onKeyDown(int keyCode, KeyEvent event) { | |
Log.d(TAG, "key down!"); | |
addEvent("key down!"); | |
return super.onKeyDown(keyCode, event); | |
} | |
private ObjectContainer db() { | |
try { | |
if (db == null) { | |
db = Db4oEmbedded.openFile(dbPath()); | |
Log.d(TAG, "opened new database connection"); | |
} | |
return db; | |
} catch (Exception e) { | |
Log.e(TAG, "unable to open database"); | |
return null; | |
} | |
} | |
private String dbPath() { | |
return this.getDir("data", 0) + "/" + "events.db4o"; | |
} | |
private void addEvent(String string) { | |
SimpleDateFormat sdf = new SimpleDateFormat(); | |
Event event = new Event("[" + sdf.format(new Date()) + "] " + string); | |
db().store(event); | |
db().commit(); | |
events.add(event.toString()); | |
adapter.notifyDataSetChanged(); | |
} | |
private void getEvents() { | |
ObjectSet<Event> result = db().queryByExample(new Event(null)); | |
events.clear(); | |
while (result.hasNext()) { | |
String event = result.next().toString(); | |
events.add(event); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment