Skip to content

Commit

Permalink
Save scanned items to database
Browse files Browse the repository at this point in the history
Apie tai, kaip susikurti ORM Lite duomenų bazės `Helper` klasę
galima paskaityti/pažiūrėti štai čia:
* [ORM use with Android](http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_4.html#Use-With-Android)
* [ORM Android pavyzdžiai](http://ormlite.com/android/examples/)
* [ORM Android pavyzdys (GitHub'e)](https://github.com/j256/ormlite-examples/blob/master/android/HelloAndroid/src/com/example/helloandroid/DatabaseHelper.java)

Pasinaudojant `Helper` klase išsaugoti įrašą duomenų bazėje.
  • Loading branch information
ViliusKraujutis committed Feb 8, 2014
1 parent a3d19b7 commit e8f589d
Show file tree
Hide file tree
Showing 6 changed files with 285 additions and 14 deletions.
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,18 @@ Nuskenuota prekė `ScannedItem`:
* place - Vieta
* volunteer - Savanoris

[Pakeitimai]()
[Pakeitimai](https://github.com/gdgvilnius/MaistoBankas/commit/a3d19b796b8731e38383bde4b664b38107565d5e)

### Išsaugoti naujai nuskenuojamas prekes į DB

Reikės sukurti naują `ScannedItem` objektą ir išsaugoti duomenų bazėje.

Apie tai, kaip susikurti ORM Lite duomenų bazės `Helper` klasę
galima paskaityti/pažiūrėti štai čia:
* [ORM use with Android](http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_4.html#Use-With-Android)
* [ORM Android pavyzdžiai](http://ormlite.com/android/examples/)
* [ORM Android pavyzdys (GitHub'e)](https://github.com/j256/ormlite-examples/blob/master/android/HelloAndroid/src/com/example/helloandroid/DatabaseHelper.java)

Pasinaudojant `Helper` klase išsaugoti įrašą duomenų bazėje.

[Pasikeitimai]()
6 changes: 4 additions & 2 deletions app/src/main/java/lt/andro/maistobankas/BaseActivity.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package lt.andro.maistobankas;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

import lt.andro.maistobankas.db.DatabaseHelper;
import lt.andro.maistobankas.db.OrmLiteBaseActivity;

/**
* @author Vilius Kraujutis [email protected]
* @since 2014-02-08 12:23
*/
public class BaseActivity extends ActionBarActivity {
public class BaseActivity extends OrmLiteBaseActivity<DatabaseHelper> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Expand Down
53 changes: 49 additions & 4 deletions app/src/main/java/lt/andro/maistobankas/MainActivity.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package lt.andro.maistobankas;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.sql.SQLException;
import java.util.Date;

import lt.andro.maistobankas.db.ScannedItem;

public class MainActivity extends BaseActivity {

@Override
Expand All @@ -24,7 +29,7 @@ protected void onCreate(Bundle savedInstanceState) {

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
Expand All @@ -45,8 +50,48 @@ public boolean onOptionsItemSelected(MenuItem item) {
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
Toast.makeText(this, "ScanResult=" + scanResult.getContents(), Toast.LENGTH_LONG).show();
// TODO save scan result into database
final String barcode = scanResult.getContents();
Toast.makeText(this, "ScanResult=" + barcode, Toast.LENGTH_LONG).show();
final ScannedItem scannedItem = new ScannedItem();
scannedItem.setBarcode(barcode);
scannedItem.setPlace("Vilnius");
scannedItem.setTime(new Date());
scannedItem.setVolunteer("Vilius");

try {
getHelper().getScannedItemDao().create(scannedItem);
} catch (SQLException e) {
Log.e("MB", "Failed saving scanned Item.", e);
}
// // you get the SQLiteOpenHelper from your Android Activity
// ConnectionSource connectionSource =
// new AndroidConnectionSource(get);
//
//// instantiate the DAO to handle Account with String id
// Dao<Account,String> accountDao =
// BaseDaoImpl.createDao(connectionSource, Account.class);
//
//// if you need to create the 'accounts' table make this call
// TableUtils.createTable(connectionSource, Account.class);
//
//// create an instance of Account
// String name = "Jim Smith";
// Account account = new Account(name, "_secret");
//
//// persist the account object to the database
//// it should return 1 for the 1 row inserted
// if (accountDao.create(account) != 1) {
// throw new Exception("Failure adding account");
// }
//
//// retrieve the account
// Account account2 = accountDao.queryForId(name);
//// show its password
// System.out.println("Account: " + account2.getPassword());
//
//// close the connection source
// connectionSource.close();
// // TODO save scan result into database
}
// else continue with any other code you need in the method
}
Expand Down
99 changes: 99 additions & 0 deletions app/src/main/java/lt/andro/maistobankas/db/DatabaseHelper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package lt.andro.maistobankas.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**
* Database helper class used to manage the creation and upgrading of your database. This class also usually provides
* the DAOs used by the other classes.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

// name of the database file for your application -- change to something appropriate for your app
private static final String DATABASE_NAME = "helloAndroid.db";
// any time you make changes to your database objects, you may have to increase the database version
private static final int DATABASE_VERSION = 1;

// the DAO object we use to access the SimpleData table
private Dao<Item, Integer> itemDao = null;
private Dao<ScannedItem, Integer> scannedItemDao = null;

public DatabaseHelper(Context context) {
// TODO create a config file super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

/**
* This is called when the database is first created. Usually you should call createTable statements here to create
* the tables that will store your data.
*/
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
TableUtils.createTable(connectionSource, Item.class);
TableUtils.createTable(connectionSource, ScannedItem.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}

/**
* This is called when your application is upgraded and it has a higher version number. This allows you to adjust
* the various data to match the new version number.
*/
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, Item.class, true);
TableUtils.dropTable(connectionSource, ScannedItem.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}

/**
* Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached
* value.
*/
public Dao<Item, Integer> getItemDao() throws SQLException {
if (itemDao == null) {
itemDao = getDao(Item.class);
}
return itemDao;
}

/**
* Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached
* value.
*/
public Dao<ScannedItem, Integer> getScannedItemDao() throws SQLException {
if (scannedItemDao == null) {
scannedItemDao = getDao(ScannedItem.class);
}
return scannedItemDao;
}

/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
itemDao = null;
scannedItemDao = null;
}
}
110 changes: 110 additions & 0 deletions app/src/main/java/lt/andro/maistobankas/db/OrmLiteBaseActivity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package lt.andro.maistobankas.db;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.logger.Logger;
import com.j256.ormlite.logger.LoggerFactory;
import com.j256.ormlite.support.ConnectionSource;

/**
* Base class to use for activities in Android.
* <p/>
* You can simply call {@link #getHelper()} to get your helper class, or {@link #getConnectionSource()} to get a
* {@link ConnectionSource}.
* <p/>
* The method {@link #getHelper()} assumes you are using the default helper factory -- see {@link OpenHelperManager}. If
* not, you'll need to provide your own helper instances which will need to implement a reference counting scheme. This
* method will only be called if you use the database, and only called once for this activity's life-cycle. 'close' will
* also be called once for each call to createInstance.
*
* @author graywatson, kevingalligan
*/
public abstract class OrmLiteBaseActivity<H extends OrmLiteSqliteOpenHelper> extends ActionBarActivity {

private volatile H helper;
private volatile boolean created = false;
private volatile boolean destroyed = false;
private static Logger logger = LoggerFactory.getLogger(OrmLiteBaseActivity.class);

/**
* Get a helper for this action.
*/
public H getHelper() {
if (helper == null) {
if (!created) {
throw new IllegalStateException("A call has not been made to onCreate() yet so the helper is null");
} else if (destroyed) {
throw new IllegalStateException(
"A call to onDestroy has already been made and the helper cannot be used after that point");
} else {
throw new IllegalStateException("Helper is null for some unknown reason");
}
} else {
return helper;
}
}

/**
* Get a connection source for this action.
*/
public ConnectionSource getConnectionSource() {
return getHelper().getConnectionSource();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
if (helper == null) {
helper = getHelperInternal(this);
created = true;
}
super.onCreate(savedInstanceState);
}

@Override
protected void onDestroy() {
super.onDestroy();
releaseHelper(helper);
destroyed = true;
}

/**
* This is called internally by the class to populate the helper object instance. This should not be called directly
* by client code unless you know what you are doing. Use {@link #getHelper()} to get a helper instance. If you are
* managing your own helper creation, override this method to supply this activity with a helper instance.
* <p/>
* <p>
* <b> NOTE: </b> If you override this method, you most likely will need to override the
* {@link #releaseHelper(OrmLiteSqliteOpenHelper)} method as well.
* </p>
*/
protected H getHelperInternal(Context context) {
@SuppressWarnings({"unchecked", "deprecation"})
H newHelper = (H) OpenHelperManager.getHelper(context);
logger.trace("{}: got new helper {} from OpenHelperManager", this, newHelper);
return newHelper;
}

/**
* Release the helper instance created in {@link #getHelperInternal(Context)}. You most likely will not need to call
* this directly since {@link #onDestroy()} does it for you.
* <p/>
* <p>
* <b> NOTE: </b> If you override this method, you most likely will need to override the
* {@link #getHelperInternal(Context)} method as well.
* </p>
*/
protected void releaseHelper(H helper) {
OpenHelperManager.releaseHelper();
logger.trace("{}: helper {} was released, set to null", this, helper);
this.helper = null;
}

@Override
public String toString() {
return getClass().getSimpleName() + "@" + Integer.toHexString(super.hashCode());
}
}
16 changes: 9 additions & 7 deletions app/src/main/java/lt/andro/maistobankas/db/ScannedItem.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,22 @@
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import java.util.Date;

/**
* @author Vilius Kraujutis [email protected]
* @since 2014-02-08 14:50
*/
@DatabaseTable(tableName = "scanned_item")
public class ScannedItem {

@DatabaseField(id = true)
@DatabaseField(generatedId = true)
private long id;

@DatabaseField(canBeNull = false)
private String barcode;
@DatabaseField(canBeNull = false)
private long timestamp;
private Date time;
private String place;
private String volunteer;

Expand All @@ -36,12 +38,12 @@ public void setBarcode(String barcode) {
this.barcode = barcode;
}

public long getTimestamp() {
return timestamp;
public Date getTime() {
return time;
}

public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
public void setTime(Date time) {
this.time = time;
}

public String getPlace() {
Expand All @@ -65,7 +67,7 @@ public String toString() {
return "ScannedItem{" +
"id=" + id +
", barcode='" + barcode + '\'' +
", timestamp=" + timestamp +
", time=" + time +
", place='" + place + '\'' +
", volunteer='" + volunteer + '\'' +
'}';
Expand Down

0 comments on commit e8f589d

Please sign in to comment.