I don't know what is wrong here
package mytwistedidea.wordpress.com.testingdata;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Message;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by Nishant on 22-02-2017.
*/
public class DatabaseHelper {
static MyHelper helper;
public DatabaseHelper(Context context){
helper = new MyHelper(context);
}
public long insertStudent(int roll, String name, String attended){
SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MyHelper.ROLL,roll);
contentValues.put(MyHelper.NAME,name);
contentValues.put(MyHelper.ATTENDED,attended);
Long id = sqLiteDatabase.insert(MyHelper.TABLE_NAME_STUDENT,null,contentValues);
sqLiteDatabase.close();
return id;
}
public static ArrayList<String> getStudent(Integer roll){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<Integer> previousRoll = new ArrayList<Integer>();
String columns[] = {MyHelper.ROLL};
String query = "SELECT * FROM "+MyHelper.TABLE_NAME_STUDENT+" WHERE roll='" + roll;
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
if (cursor != null) {
cursor.moveToFirst();
}
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL)));
arrayList.add(cursor.getString(cursor.getColumnIndex(MyHelper.NAME)));
arrayList.add(cursor.getString(cursor.getColumnIndex(MyHelper.ATTENDED)));
return arrayList;
/*
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousRoll.add(Integer.parseInt(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL))));
}while (cursor.moveToNext());
}if(previousRoll.size() == 0){
previousRoll.add(0,0);
return previousRoll;
}
return previousRoll;*/
}
public static ArrayList<String> getAllStudent(){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<String> previousStudent = new ArrayList<String>();
String columns[] = {MyHelper.ROLL,MyHelper.NAME,MyHelper.ATTENDED};
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousStudent.add(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL)));
previousStudent.add(cursor.getString(cursor.getColumnIndex(MyHelper.NAME)));
previousStudent.add(cursor.getString(cursor.getColumnIndex(MyHelper.ATTENDED)));
}while (cursor.moveToNext());
}if(previousStudent.size() == 0){
previousStudent.add(0," ");
return previousStudent;
}
return previousStudent;
}
public static ArrayList<Integer> getStudentRoll(){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<Integer> previousRoll = new ArrayList<Integer>();
String columns[] = {MyHelper.ROLL};
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousRoll.add(Integer.parseInt(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL))));
}while (cursor.moveToNext());
}if(previousRoll.size() == 0){
previousRoll.add(0);
return previousRoll;
}
return previousRoll;
}
public static ArrayList<String> getStudentName(){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<String> previousName = new ArrayList<String>();
String columns[] = {MyHelper.NAME};
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousName.add(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL)));
}while (cursor.moveToNext());
}if(previousName.size() == 0){
previousName.add(0," ");
return previousName;
}
return previousName;
}
public static ArrayList<Integer> getStudentAttendence(){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<Integer> previousAttendence = new ArrayList<Integer>();
String columns[] = {MyHelper.ATTENDED};
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousAttendence.add(Integer.parseInt(cursor.getString(cursor.getColumnIndex(MyHelper.ATTENDED))));
}while (cursor.moveToNext());
}if(previousAttendence.size() == 0){
previousAttendence.add(0,0);
return previousAttendence;
}
return previousAttendence;
}
class MyHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "mystudent.db";
private static final String TABLE_NAME_STUDENT = "student";
private static final int DATABASE_VERSION = 1;
private static final String NAME = "name";
private static final String ROLL = "roll";
private static final String ATTENDED = "attended";
private static final String CREATE_TABLE = "CREATE TABLE"+TABLE_NAME_STUDENT+
"("+ROLL+" INTEGER PRIMARY KEY, "+
NAME+" VARCHAR(255), "+
ATTENDED+" INTEGER);";
private static final String DROP_STUDENT = "DROP TABLE IF EXISTS "+TABLE_NAME_STUDENT;
private Context context;
public MyHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
if(db != null){
try{
db.execSQL(CREATE_TABLE);
}
catch (SQLException e){
e.printStackTrace();
}
}
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
db.execSQL(DROP_STUDENT);
onCreate(db);
}
catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
db.execSQL(DROP_STUDENT);
onCreate(db);
}
catch (SQLException e){
e.printStackTrace();
}
}
}
}
I am new to databases.
I don't know which part is wrong so I posted the whole code.
The problem is in below line
private static final String CREATE_TABLE = "CREATE
TABLE"+TABLE_NAME_STUDENT+
"("+ROLL+" INTEGER PRIMARY KEY, "+
NAME+" VARCHAR(255), "+
ATTENDED+" INTEGER);";
it should be like
private static final String CREATE_TABLE = "CREATE TABLE
"+TABLE_NAME_STUDENT+
"("+ROLL+" INTEGER PRIMARY KEY, "+
NAME+" VARCHAR(255), "+
ATTENDED+" INTEGER);";
There should be a space between"CREATE TABLE" and TABLE_NAME_STUDENT
Related
I have 3 classes: MainActivity, DBHelper (extended SQLiteOpenHelper) and Student class.
In DBHelper I have methods like: addNewStudent, deleteStudent, findStudent and getAllStudents.
The method "getAllStudents" return arrayList and I want to show elements of this one in the listView on the mainactivity layou but I have problem with parameter of the ArrayList.
I tried on String just to understand using ArrayAdapter:
MAIN ACTIVITY
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
editTextID = (EditText) findViewById(R.id.editTextID);
editTextName = (EditText) findViewById(R.id.editTextName);
listViewStudents = (ListView) findViewById(R.id.listViewStudents);
mDBStudents = new DBhelper(this);
// ------> this one provisional works:
final ArrayList<String> namesArray = new ArrayList<String>();
namesArray.add("Hania");
namesArray.add("Kasia");
final ArrayAdapter<String> namesAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,namesArray);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
namesArray.add(editTextName.getText().toString());
mDBStudents.addNewStudent(editTextName.getText().toString());
listViewStudents.setAdapter(namesAdapter);
// ------> this one using <object> parameter in the ArrayList doesn't work and my app is stopped. I tried with Log.d but how to do it correctly with objects...
final ArrayList<Student> studentArray = new ArrayList<Student>();
Student s1 = new Student(1, "Natalia");
studentArray.add(s1);
final ArrayAdapter<Student> studentAdapter = new ArrayAdapter<Student>(MainActivity.this, android.R.layout.simple_list_item_1, studentArray);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Student s2 = new Student(Integer.parseInt(editTextID.getText().toString()), editTextName.getText().toString());
studentArray.add(s2);
mDBStudents.addNewStudent(editTextName.getText().toString());
listViewStudents.setAdapter(studentAdapter);
I want to show elements from the ArrayList which I add when I click "addStudentButton" in the ListView. Later I want t open the new Intent when I click on one positon from the listView. Do you have any suggestions what is the best way for beginner user of android?
On some pages are info about using ArrayAdapter, Cursor etc. but they aren't so clarity for me
DBhelper class
public class DBhelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "studentDB.db";
public static final String TABLE_NAME = "student";
public static final String COLUMN_ID = "studentID";
public static final String COLUMN_NAME = "studentName";
//initialize the database
public DBhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_NAME + " TEXT " + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public int addNewStudent(String studentName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME,studentName);
return (int) db.insert(TABLE_NAME,null, values); //???
}
public ArrayList<Student> getAllStudents() {
ArrayList<Student> result = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
result.add(
new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_NAME)
)
)
);
}
csr.close();
db.close();
return result;
}
public Student findStudent(int studentID) {
Student result = null;
String whereclause = COLUMN_ID + "=?";
String[] whereargs = new String[]{String.valueOf(studentID)};
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
result = new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_NAME)
)
);
}
csr.close();
db.close();
return result;
}
public Student deleteStudent(int studentID) {
Student result = null;
String whereclause = COLUMN_ID + "=?";
String[] whereargs = new String[]{String.valueOf(studentID)};
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME, null, whereclause, whereargs, null, null, null);
if (csr.moveToFirst()) {
result = new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)), csr.getString(csr.getColumnIndex(COLUMN_NAME)));
db.delete(TABLE_NAME, whereclause, whereargs);
}
csr.close();
db.close();
return result;
}
public boolean updateStudent(int studentID, String studentName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(COLUMN_ID, studentID);
args.put(COLUMN_NAME, studentName);
return db.update(TABLE_NAME, args, COLUMN_ID + "=" + ID, null) > 0;
}
}
Student class
public class Student {
private int studentID;
private String studentName;
public Student(int id, String studentName) { //konstruktor
this.studentID = id;
this.studentName = studentName;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
I have code that imports data with sms! And now I need one method to export this data from the database to a variable on the IncomingSMSReceiver (I will probably make one method for each field); Can I export a single cell value to a variable?
E.g I tried to do it for the onoma column but I don't know what database method I should use and what sql, and how to export it.
DatabaseHelper.java
package toulios.ptixiakh.toulios;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Toulios.db";
public static final String TABLE_NAME="Foitites_table";
public static final String Col_AM="AM";
public static final String Col_ONOMA="ONOMA";
public static final String Col_EPITHETO="EPITHETO";
public static final String Col_EXAMINO="EXAMINO";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME+"(AM INTEGER PRIMARY KEY,ONOMA TEXT,EPITHETO TEXT, EXAMINO INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
onCreate(db);
}
public boolean eisagoghfititi(String am,String onoma,String epitheto,String examino)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_AM,am);
contentValues.put(Col_ONOMA,onoma);
contentValues.put(Col_EPITHETO,epitheto);
contentValues.put(Col_EXAMINO,examino);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public String exagwgh_onoma(String am){
String str="";
final String SQL_SELECT_QUERY = "SELECT "+DatabaseHelper.Col_ONOMA+" FROM "+DatabaseHelper.TABLE_NAME+" WHERE "+DatabaseHelper.Col_AM+" = "+am;
DatabaseHelper queryDbHelperObj = new DatabaseHelper(this);
SQLiteDatabase sqLiteDatabase = queryDbHelperObj.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(SQL_SELECT_QUERY,null);
if (cursor.moveToFirst()) {
str = cursor.getString(cursor.getColumnIndex("content"));
}
cursor.close();
return str;
}
}
IncomingSMSReceiver.java
public class IncomingSMSReceiver extends BroadcastReceiver{
private static final String SMS_RECEIVED ="android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context _context, Intent _intent) {
if (_intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = _intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage
.createFromPdu((byte[]) pdus[i]);
for (SmsMessage message : messages)
{
String strPhoneNo = message.getOriginatingAddress();
String msg = message.getMessageBody();
if (msg.startsWith("01"))
{
try {
final String[] temaxismeno_sms = msg.split(":");
DatabaseHelper dbHelper = new DatabaseHelper(_context.getApplicationContext());
dbHelper.eisagoghfititi(temaxismeno_sms[1],temaxismeno_sms[2],temaxismeno_sms[3],temaxismeno_sms[4]);
Toast.makeText(_context, "Egine eisagwgh fititi!!", Toast.LENGTH_LONG).show();
String message1 = "H Eisagwgh egine sthn vash.";// minima pou tha stalthei
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(strPhoneNo, null, message1, null, null);
Toast.makeText(_context, "O fititis idopiithike", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(_context, "SMS failed, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if (msg.startsWith("02"))
{
final String[] temaxismeno_sms = msg.split(":");
String apotelesma;
DatabaseHelper dbHelper = new DatabaseHelper(_context.getApplicationContext());
apotelesma = dbHelper.exagwgh_onoma(temaxismeno_sms[1]);
String message2 = "To onoma tou am pou epilexate einai "+apotelesma;
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(strPhoneNo, null, message2, null, null);
}
}
}
}
}
}
You can achieve that in the below way --
public static final String SQL_SELECT_QUERY = "SELECT COLUMN1 FROM "+AndroidOpenDbHelper.TEST_TABLE;
AndroidOpenDbHelper queryDbHelperObj = new AndroidOpenDbHelper(this);
SQLiteDatabase sqLiteDatabase = queryDbHelperObj.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(SQL_SELECT_QUERY,null);
if(cursor != null)
{
if(cursor.moveToFirst())
{
do
{
String ColumnVal = cursor.getString(cursor.getColumnIndex("Column1"));
}while(cursor.moveToNext());
}
}
EDITED:
"SELECT "+AndroidOpenDbHelper.ONOMA+" FROM "+AndroidOpenDbHelper.TEST_TABLE+" WHERE "+AndroidOpenDbHelper._ID+" = "+am;
Hope this helps!
i want to add some image uri's to the Database. my Database table has two columns id and String Uri. The Problem is it shows No such table exist when trying to insert some Uris to Table. Here is my Code of Database Adapter Class.
package com.example.mystorage;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
// for customer registration
static final String KEY_ID = "id";
static final String KEY_URI = "uri";
static final String DATABASE_NAME = "IMAGE_DB";
static final String DATABASE_TABLE = "temp_images1";
static final int DATABASE_VERSION = 2;
static final String DATABASE_CREATE = "create table temp_images1 (id integer autoincrement, "
+ "uri text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS temp_images1");
onCreate(db);
}
}
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
// //////////////////////////////////////for
// customerRegistration////////////////
// customer registration for retrieve data
public Cursor getAllImages() {
return db.query(DATABASE_TABLE, new String[] {KEY_URI}, null,
null, null, null, null);
}
public Cursor getContentimage(long id) throws SQLException {
Cursor c = db.query(true, DATABASE_TABLE,
new String[] { KEY_ID, KEY_URI },
KEY_ID + "=" + id, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// customer registration for update data
public boolean updateimages(long id, String uri) {
ContentValues args = new ContentValues();
// args.put(KEY_ID,id);
args.put(KEY_URI, uri);
return db.update(DATABASE_TABLE, args, KEY_ID + "=" + id, null) > 0;
}
// customer registration for insert data
public long insertImages(String uri) {
ContentValues args = new ContentValues();
//args.put(KEY_ID, id);
args.put(KEY_URI, uri);
long n = db.insert(DATABASE_TABLE, null, args);
//db.insertOrThrow(DATABASE_TABLE, null, args);
return n;
}
// customer registration for remove data
public boolean deleteImages(long id) {
return db.delete(DATABASE_TABLE, KEY_ID + "=" + id, null) > 0;
}
}
here is My ImageAdapter class where i am calling the insert method.
mThumbs is uri Arraylist to Store the Content of Database While Retrieving.
public ImageAdapter(Context c, android.net.Uri uri) {
mContext = c;
db= new DBAdapter(mContext);
try {
db.open();
db.insertImages(uri.toString());
db.close();
}catch(Exception e){
e.printStackTrace();
}
upadteAllImages();
notifyDataSetChanged();
}
public ImageAdapter(Context c, ArrayList<Uri> imageUris) {
mContext = c;
db= new DBAdapter(mContext);
try {
db.open();
for (int i = 0; i < imageUris.size(); i++){
db.insertImages(imageUris.get(i).toString());
}
db.close();
}catch(Exception e){
e.printStackTrace();
}
upadteAllImages();
notifyDataSetChanged();
}
private void upadteAllImages() {
mTHumbs.clear();
try{
db.open();
Cursor c = db.getAllImages();
if (c.moveToFirst()) {
while (c.moveToNext()){
String uri = c.getString(1);
mTHumbs.add(Uri.parse(uri));
}
}
//mTHumbs.add((Uri) db.getAllImages());
db.close();
}catch(Exception e){
e.printStackTrace();
}
}
String query = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_URI + " TEXT not null "+)";
Fix the syntax error in your CREATE TABLE. AUTOINCREMENT can only be used with INTEGER PRIMARY KEY and you're missing the PRIMARY KEY.
Remove the try-catch in your onCreate() so that you get an exception in case of a syntax problem.
Uninstall your app so that the old database is removed and your helper onCreate() gets run again with the fixed SQL.
Some minor changes are required to create a table in database.
Please see this-
" CREATE TABLE temp_images1 ( id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "uri TEXT NOT NULL ) ; ";
I'm building a note taking app in Android. I have developed insertion of the note in the app right now which I have done through SQLite database. Now I want to delete the particular note from the SQLite database through the context menu. When user long presses any record in the app it will through a context menu with "Delete" option. Now, My problem is I'm able to remove item from listview but it's not getting deleted from database.
Here's my code:
MainActivity.java:
#Override
public boolean onContextItemSelected(MenuItem item) {
int position;
super.onContextItemSelected(item);
if(item.getTitle().equals("Delete")) {
//Add code
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
position = (int)info.id;
//Notes note_id = (Notes)adapter.getNote(info.position);
db.deleteNote(new Notes(position));
list.remove(position);
this.adapter.notifyDataSetChanged();
}
return true;
};
DatabaseHandler.java:
package com.amitmerchant.notesapp;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notesManager";
private static final String TABLE_NOTES = "notes";
private static final String KEY_ID = "_id";
private static final String KEY_NOTE = "note";
private static final String KEY_DATE = "date_added";
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_NOTES_TABLE = "CREATE TABLE "+TABLE_NOTES+"("+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+KEY_NOTE+" TEXT,"+KEY_DATE+" DATE"+")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note.getNote()); // Contact Name
// Inserting Row
db.insert(TABLE_NOTES, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Notes getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[] { KEY_ID,
KEY_NOTE, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Notes note = new Notes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return note;
}
// Getting All Contacts
public List<Notes> getAllNotes() {
List<Notes> noteList = new ArrayList<Notes>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Notes note = new Notes();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setNote(cursor.getString(1));
// Adding contact to list
noteList.add(note);
} while (cursor.moveToNext());
}
// return contact list
return noteList;
}
// Getting contacts Count
public int getNotesCount() {
String countQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note.getNote());
// updating row
return db.update(TABLE_NOTES, values, KEY_ID + " = ?",
new String[] { String.valueOf(note.getId()) });
}
// Deleting single contact
public void deleteNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + " = ?",
new String[] { String.valueOf(note.getId()) });
db.close();
}
}
Notes.java
package com.amitmerchant.notesapp;
public class Notes {
// private variables
int _id;
String _note;
String _note_date;
// Empty constructor
public Notes() {
}
public Notes(int id, String _note) {
this._id = id;
this._note = _note;
}
public Notes(String _note) {
this._note = _note;
}
public Notes(int id) {
this._id = id;
}
public int getId() {
return this._id;
}
public void setId(int id) {
this._id = id;
}
public String getNote() {
return this._note;
}
public void setNote(String note) {
this._note = note;
}
}
Guys, what am I doing wrong here? Please correct me. Thanks!
I'm trying to understand how the connectivity works. I'm required to have a database in the assets folder(which I already built).I got an entire class adapter, was told to implement it in my code and start using it, but I'm not sure how to 'import' it. My main class is 'MainActivity', I tried DBAdapter adapter = new DBAdapter(); but that didn't work.
Here's the adapter class:
package com.example.movieass;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ID = "m_id";
public static final String KEY_TITLE = "m_title";
public static final String KEY_DESCRIPTION = "m_description";
public static final String KEY_RATING = "m_rating";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "database";
private static final String DATABASE_TABLE = "films";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"CREATE TABLE trailer (m_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"m_title TEXT NOT NULL, m_description TEXT NOT NULL, m_rating REAL NOT NULL);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL("DROP TABLE IF EXISTS trailer");
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS trailer");
onCreate(db);
}
} //end DatabaseHelper class
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertTrailer(String title, String description, String filename, double rating)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_DESCRIPTION, description);
initialValues.put(KEY_RATING, rating);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteTrailer(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllTrailers()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_TITLE,
KEY_DESCRIPTION, KEY_RATING}, null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getTrailer(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ID,
KEY_TITLE, KEY_DESCRIPTION, KEY_RATING}, KEY_ID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
do{
Log.d("DBAdapter", "ID: " + mCursor.getString(mCursor.getColumnIndex("ID")));
}while (mCursor.moveToNext());
}
return mCursor;
}
//---updates a contact---
public boolean updateTrailer(long rowId, String title, String description, String filename, double rating)
{
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_DESCRIPTION, description);
args.put(KEY_RATING, rating);
return db.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
}
public boolean updateRating(long rowId, double rating)
{
ContentValues args = new ContentValues();
args.put(KEY_RATING, rating);
return db.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
}
}
This is my working code to copy database.
private static String DB_PATH = "/data/data/com.demo.databaseDemo/databases/";
private static String DB_NAME = "myDatabase.db";
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();
}//end of copyDataBase() method
Also You can refer this for more details http://mobisys.in/blog/2012/01/tutorial-using-database-in-android-applications/