Skip to content

Instantly share code, notes, and snippets.

@eluleci
Last active August 29, 2015 14:02
Show Gist options
  • Save eluleci/1952b6914481195c2ddb to your computer and use it in GitHub Desktop.
Save eluleci/1952b6914481195c2ddb to your computer and use it in GitHub Desktop.
Medium Post - Android'de veritabanı kullanımı
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.cengalabs.dbusage.model.User;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
/**
* 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 {
private static final String DATABASE_NAME = "sampleDatabase.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
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");
// You must create table of the classes that you need to keep in database
TableUtils.createTable(connectionSource, User.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
/**
* 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");
// You need to handle the new structure of the class when it changes
TableUtils.dropTable(connectionSource, User.class, true);
// After dropping the database, you need to create it again
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
}
public class MainActivity extends ActionBarActivity {
private String TAG = getClass().getSimpleName();
private UserPersistenceManager userPersistenceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// manager objesini oluşturma
userPersistenceManager = new UserPersistenceManager(this);
// kişileri kaydetme
userPersistenceManager.create(new User(1, "Barış", "Manço"));
userPersistenceManager.create(new User(2, "Kemal", "Sunal"));
userPersistenceManager.create(new User(3, "Barış", "Akarsu"));
// kişi listesini alma
List<User> personList = userPersistenceManager.readAll();
// kişi listesini yazdırma
Log.d(TAG, "Kayıtlı kişiler:");
for (User person : personList) {
Log.d(TAG, person.toString());
}
// ismi Barış olan kişilerin listesini yazdırma
Log.d(TAG, "İsmi Barış olan kişiler:");
for (User person : userPersistenceManager.getUsersWithName("Barış")) {
Log.d(TAG, person.toString());
}
// kullanıcları listview'da gösterme
((ListView) findViewById(R.id.personList))
.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, personList));
}
}
import android.content.Context;
import android.util.Log;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import java.sql.SQLException;
import java.util.List;
/**
* This class creates an abstraction for making the model storage easier. You can extend this class
* to have a simple DAO for your model.
*
* IMPORTANT: The class you use to store must have an empty constructor which is required ormlite.
* @param <E>
*/
public abstract class PersistenceManager<E extends PersistenceManager.Modal> {
protected Dao dao;
private String TAG = "PersistenceManager";
protected PersistenceManager(Context context, Class c) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
try {
dao = DaoManager.createDao(helper.getConnectionSource(), c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public final boolean create(E e) {
if (exists(e.getId())) {
Log.e(TAG, "An entry with the same id already exists.");
return false;
}
try {
dao.create(e);
return true;
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
public final E read(int id) {
try {
return (E) dao.queryForId(id + "");
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public final List<E> readAll() {
try {
return (List<E>) dao.queryForAll();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public final boolean update(E e){
try {
dao.update(e);
return true;
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
public final boolean delete(int id) {
try {
dao.deleteById(id);
return true;
} catch (SQLException e1) {
e1.printStackTrace();
return false;
}
}
public final boolean exists(int id) {
try {
return dao.queryForId(id + "") != null;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public interface Modal {
public int getId();
}
}
import com.cengalabs.dbusage.db.PersistenceManager;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "Users")
public class User implements PersistenceManager.Modal {
@DatabaseField(id = true)
private int id;
@DatabaseField
private String name;
@DatabaseField
private String surName;
public User() {
// ORMLite needs a no-arg constructor
}
public User(int id, String name, String surName) {
this.id = id;
this.name = name;
this.surName = surName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
@Override
public String toString() {
return "Kullanıcı: " + id + ", " + name + " " + surName;
}
}
import android.content.Context;
import com.cengalabs.dbusage.model.User;
public class UserPersistenceManager extends PersistenceManager<User> {
/**
* This constructor is used to initialise the DAO object for the given class.
* @param context
*/
public UserPersistenceManager(Context context) {
super(context, User.class);
}
/**
* Returns the records that contains the given name in the 'name' column
*
* @param name: The string that is expected in the 'name' column
* @return
*/
public List<User> getUsersWithName(String name) {
// query for all users which has the given name
try {
return dao.query(dao.queryBuilder().where().eq("name", name).prepare());
} catch (SQLException e) {
e.printStackTrace();
return new ArrayList<User>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment