Update a determinate field in a table - java

I want to modify a field of a determinate id, in my case the field is notify_datetime.
But when I run the app and try to do that, the app crashes giving this error.
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.msnma.movienotifier, PID: 4047
android.database.sqlite.SQLiteException: no such column: notify_datetime (Sqlite code 1): , while compiling: UPDATE MovieTypeTable SET notify_datetime=? WHERE notify_datetime = ?, (OS error - 2:No such file or directory)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:910)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:521)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1856)
at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1799)
at com.example.msnma.movienotifier.database.MovieDatabase.updateNotifyDate(MovieDatabase.java:299)
at com.example.msnma.movienotifier.adapter.MoviesAdapter$9.onClick(MoviesAdapter.java:445)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
The method is called updateNotifyDate and should modify notify_datetime.
MovieDatabase.java
package com.example.msnma.movienotifier.database;
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;
import com.example.msnma.movienotifier.MainActivity;
import com.example.msnma.movienotifier.databaseModel.MovieDBModel;
import com.example.msnma.movienotifier.databaseModel.TypeDBModel;
import com.example.msnma.movienotifier.mapper.MovieMapper;
import com.example.msnma.movienotifier.model.Movie;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class MovieDatabase extends SQLiteOpenHelper {
private static final String LOG = "DatabaseHelper";
private static final String DATABASE_NAME = "movieDatabase";
private static final int DATABASE_VERSION = 1;
//Table Names
private static final String TABLE_MOVIE = "MovieTable";
private static final String TABLE_TYPE = "TypeTable";
private static final String TABLE_MOVIE_TYPE = "MovieTypeTable";
//Table Fields
private static final String MOVIE_ID ="movie_id";
public static final String TITLE ="title";
private static final String OVERVIEW = "overview";
private static final String POSTER_URL = "posterUrl";
private static final String BACKDROP_URL = "backdropUrl";
private static final String TRAILER_URL = "trailerUrl";
private static final String RELEASE_DATE = "releaseDate";
private static final String RATING = "rating";
private static final String ADULT = "adult";
private static final String TYPE_ID = "type_id";
private static final String TYPE_DESCR = "type_descr";
private static final String MOVIE_TYPE_ID = "movie_type_id";
private static final String M_ID = "movie_id";
private static final String T_ID = "type_id";
private static final String notify_datetime = "notify_datetime";
// Table Create Statements
private static final String CREATE_TABLE_MOVIE = "CREATE TABLE "
+ TABLE_MOVIE + "(" + MOVIE_ID + " INTEGER PRIMARY KEY," + TITLE + " TEXT,"
+ OVERVIEW + " TEXT," + POSTER_URL + " TEXT," + BACKDROP_URL + " TEXT," + TRAILER_URL + " TEXT,"
+ RATING + " REAL," + ADULT + " INTEGER," + RELEASE_DATE + " DATETIME," + notify_datetime + " DATETIME" + ")";
// Tag table create statement
private static final String CREATE_TABLE_TYPE = "CREATE TABLE " + TABLE_TYPE
+ "(" + TYPE_ID + " INTEGER PRIMARY KEY," + TYPE_DESCR + " TEXT" + ")";
// todo_tag table create statement
private static final String CREATE_TABLE_MOVIE_TYPE = "CREATE TABLE "
+ TABLE_MOVIE_TYPE + "(" + MOVIE_TYPE_ID + " INTEGER PRIMARY KEY,"
+ M_ID + " INTEGER," + T_ID + " INTEGER" + ")";
static SQLiteDatabase database;
public MovieDatabase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
database = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_MOVIE);
db.execSQL(CREATE_TABLE_TYPE);
db.execSQL(CREATE_TABLE_MOVIE_TYPE);
insertType(db); //NOTA: questo va chiamato solo la prima volta che instanziamo il DB, AGGIUNGERE CONTROLLO!
//in teoria onCreate verrà chiamato solo la prima volta...
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TYPE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIE_TYPE);
// create new tables
onCreate(db);
}
//questa funzione serve solo per inserire casualmente dai suggested movies, alcuni notify e watched movies
public static void saveMoviesOnDB(List<Movie> movies, String type){
MovieDatabase db = MainActivity.getMovieDatabase();
MovieMapper mapper = new MovieMapper();
List<MovieDBModel> moviesDB = mapper.toMovieDBModelList(movies);
Integer typeId = 0;
int index = 0;
if(type.equals("notify")){
typeId = 1;
}else if(type.equals("watched")){
typeId = 2;
index = index+5;
}else{
//todo catch invalid type Id exception
}
for(int a = index; a<index+5; a++){
insertMovie(moviesDB.get(a), typeId, db);
}
}
//open the database, maybe not useful...
public MovieDatabase open() throws SQLException
{
database = getWritableDatabase();
return this;
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
//CRUDs
public static void insertMovie(MovieDBModel movie, Integer typeId, MovieDatabase db) {
SQLiteDatabase database = db.getWritableDatabase();
if(checkMovieUniqueness(movie.getTitle(), db)) { //NON VOGLIO INSERIRE PIù VOLTE LO STESSO FILM
ContentValues values = new ContentValues();
values.put(TITLE, movie.getTitle());
values.put(OVERVIEW, movie.getOverview());
values.put(POSTER_URL, movie.getPosterUrl());
values.put(BACKDROP_URL, movie.getBackdropUrl());
values.put(TRAILER_URL, movie.getTrailerUrl());
values.put(RELEASE_DATE, movie.getReleaseDate().toString());
values.put(RATING, movie.getRating());
values.put(ADULT, movie.isAdult());
//inizio nuovo codice
if(typeId == 1) {
values.put(notify_datetime, movie.getNotifyDate().toString());
Log.i("TYPEID", "Siamo dentro");
}
//else values.putNull(NOTIFY_TIME_DATE);
//fine nuovo codice
// insert row
long movieId = database.insert(TABLE_MOVIE, null, values);
insertMovieType(movieId, typeId, db);
}
}
public static void insertMovieType(Long movieId, Integer typeId, MovieDatabase db){
SQLiteDatabase database = db.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(M_ID, movieId.intValue());
values.put(T_ID, typeId);
database.insert(TABLE_MOVIE_TYPE, null, values);
}
private void insertType(SQLiteDatabase db){
ContentValues descr1 = new ContentValues();
descr1.put(TYPE_DESCR, "NOTIFY");
ContentValues descr2 = new ContentValues();
descr2.put(TYPE_DESCR, "WATCHED");
// insert row
db.insert(TABLE_TYPE, null, descr1);
db.insert(TABLE_TYPE, null, descr2);
}
private TypeDBModel getTypeByTypeDescr(String typeDescr) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_TYPE + " WHERE "
+ TYPE_DESCR + " = " + typeDescr;
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
TypeDBModel td = new TypeDBModel();
td.setId(c.getInt(c.getColumnIndex(TYPE_ID)));
td.setDescription((c.getString(c.getColumnIndex(TYPE_DESCR))));
return td;
}
private static boolean checkMovieUniqueness(String movieTitle, MovieDatabase db) {
SQLiteDatabase database = db.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE + " WHERE "
+ TITLE + " = " + "'"+ movieTitle + "'";
Log.e(LOG, selectQuery);
Cursor c = database.rawQuery(selectQuery, null);
if(c.moveToFirst()){
c.close();
return false;
}else{
c.close();
return true;
}
}
public List<MovieDBModel> getAllMovieByType(String typeDescr) throws ParseException {
List<MovieDBModel> movies = new ArrayList<MovieDBModel>();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE + " mv, "
+ TABLE_TYPE + " type, " + TABLE_MOVIE_TYPE + " tmt WHERE type."
+ TYPE_DESCR + " = '" + typeDescr + "'" + " AND type." + TYPE_ID
+ " = " + "tmt." + T_ID + " AND mv." + MOVIE_ID + " = "
+ "tmt." + M_ID;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
MovieDBModel td = new MovieDBModel();
td.setId(c.getInt((c.getColumnIndex(MOVIE_ID))));
td.setTitle((c.getString(c.getColumnIndex(TITLE))));
td.setOverview(c.getString(c.getColumnIndex(OVERVIEW)));
td.setPosterUrl(c.getString((c.getColumnIndex(POSTER_URL))));
td.setBackdropUrl((c.getString(c.getColumnIndex(BACKDROP_URL))));
td.setTrailerUrl(c.getString(c.getColumnIndex(TRAILER_URL)));
String dateString =c.getString((c.getColumnIndex(RELEASE_DATE)));
Date date = sdf3.parse(dateString);
td.setReleaseDate(date);
td.setRating((c.getFloat(c.getColumnIndex(RATING))));
int adult = c.getInt(c.getColumnIndex(ADULT));
if(adult == 0){
td.setAdult(true); //NOT sure if is the contrary
}else{
td.setAdult(false);
}
//nuovo codice
String datenotifyString = c.getString(c.getColumnIndex(notify_datetime));
if(datenotifyString != null)
{
Date datenotify = sdf3.parse(datenotifyString);
td.setNotifyDate(datenotify);
}
//fine nuovo codice
movies.add(td);
} while (c.moveToNext());
}
return movies;
}
public void deleteMovie(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MOVIE, MOVIE_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
public void deleteMovieType(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MOVIE_TYPE, M_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
public int updateMovieType(long id, long tag_id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(T_ID, tag_id);
// updating row
return db.update(TABLE_MOVIE_TYPE, values, M_ID + " = ?",
new String[] { String.valueOf(id) });
}
//da sistemare.
public int updateNotifyDate(long id, Date datetime ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notify_datetime,datetime.toString());
// updating row
return db.update(TABLE_MOVIE_TYPE, values, notify_datetime + " = ?",
new String[] { String.valueOf(id) });
}
public boolean isEmpty() throws ParseException {
boolean isEmpty = false;
List<MovieDBModel> movie1 = getAllMovieByType("NOTIFY");
List<MovieDBModel> movie2 = getAllMovieByType("WATCHED");
if(movie1.isEmpty() && movie2.isEmpty()){
isEmpty = true;
}
return isEmpty;
}
public static List<MovieDBModel> getAllMovies() throws ParseException {
List<MovieDBModel> movies = new ArrayList<MovieDBModel>();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE;
Log.e(LOG, selectQuery);
SQLiteDatabase db = database;
Cursor c = db.rawQuery(selectQuery, null);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
MovieDBModel td = new MovieDBModel();
td.setId(c.getInt((c.getColumnIndex(MOVIE_ID))));
td.setTitle((c.getString(c.getColumnIndex(TITLE))));
td.setOverview(c.getString(c.getColumnIndex(OVERVIEW)));
td.setPosterUrl(c.getString((c.getColumnIndex(POSTER_URL))));
td.setBackdropUrl((c.getString(c.getColumnIndex(BACKDROP_URL))));
td.setTrailerUrl(c.getString(c.getColumnIndex(TRAILER_URL)));
String dateString =c.getString((c.getColumnIndex(RELEASE_DATE)));
Date date = sdf3.parse(dateString);
td.setReleaseDate(date);
td.setRating((c.getFloat(c.getColumnIndex(RATING))));
int adult = c.getInt(c.getColumnIndex(ADULT));
if(adult == 0){
td.setAdult(true); //NOT sure if is the contrary
}else{
td.setAdult(false);
}
movies.add(td);
} while (c.moveToNext());
}
return movies;
}
}
In MoviesAdapter.java only piece that call updateNotifyDate:
MovieDatabase md = new MovieDatabase(context);
Log.i("IDMOVIE","ID:"+movies.get(position).getId());
md.updateNotifyDate(movies.get(position).getId(),datatime);
}
Why it doesn't work? What am I wrong?

You're attempting to update MovieTypeTable but your image suggests the notify_datetime is in MovieTable so it's throwing SQLiteException: no such column.

Related

Get specific row of SQLite android

I am new to Android and I want it when the user logs in by the email and password. Bring the rest of the information like the first name and the date of birth to the user via email. Is there any way to do that?
"Is there a function I can add that can not bring all user information after logging in by email"
this is my database Code :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "UserManager.db";
private static final String TABLE_USER = "user";
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_FIRST_NAME = "user_first_name";
private static final String COLUMN_USER_LAST_NAME = "user_last_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PHONE_NUMBER = "user_phone_number";
private static final String COLUMN_USER_BARTH_DAY = "user_barth_day";
private static final String COLUMN_USER_PASSWORD = "user_password";
private static final String COLUMN_USER_GENDER = "user_gender";
private String CREATE_USER_TABLE = "CREATE TABLE "+TABLE_USER + "("+
COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+
COLUMN_USER_FIRST_NAME + " TEXT,"+ COLUMN_USER_LAST_NAME + " TEXT,"+
COLUMN_USER_EMAIL + " TEXT PRIMARY KEY,"+COLUMN_USER_PHONE_NUMBER + " TEXT,"+
COLUMN_USER_BARTH_DAY+" TEXT,"+ COLUMN_USER_PASSWORD+" TEXT," +
COLUMN_USER_GENDER+" TEXT"+ ")";
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS "+ TABLE_USER ;
public DatabaseHelper(Context context) {
super(context , DATABASE_NAME, null , DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_USER_TABLE);
onCreate(db);
}
public void addUser(User user){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_FIRST_NAME , user.getFirstName());
values.put(COLUMN_USER_LAST_NAME , user.getLastName());
values.put(COLUMN_USER_EMAIL , user.getEmail());
values.put(COLUMN_USER_PHONE_NUMBER , user.getPhoneNumber());
values.put(COLUMN_USER_BARTH_DAY , user.getBarthDay());
values.put(COLUMN_USER_PASSWORD , user.getPassword());
values.put(COLUMN_USER_GENDER , user.getGender());
database.insert(TABLE_USER , null, values);
database.close();
}
public boolean checkUser (String email){
String [] columns = {
COLUMN_USER_ID
};
SQLiteDatabase database = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?";
String[] selectionArgs = {email};
Cursor cursor = database.query(TABLE_USER,
columns,selection , selectionArgs,null,null,null);
int cursorCount = cursor.getCount();
cursor.close();
database.close();
if (cursorCount > 0){
return true;
}else {
return false;
}
}
public boolean checkUser (String email , String password){
String [] columns = {
COLUMN_USER_ID
};
SQLiteDatabase database = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
String[] selectionArgs = {email , password};
Cursor cursor = database.query(TABLE_USER,
columns,selection , selectionArgs,null,null,null);
int cursorCount = cursor.getCount();
cursor.close();
database.close();
if (cursorCount > 0){
return true;
}else {
return false;
}
}
}
For your first question, you can add below function and use it.
public User getSingleUserInfo(String email){
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_USER + " WHERE " + COLUMN_USER_EMAIL + "=" + email);
cursor.moveToFirst();
//setting related user info in User Object
User user = new User();
user.setUserId(cursor.getInt(cursor.getColumnIndexCOLUMN_USER_ID ));
user.setFirstName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_FIRST_NAME));
user.setLastName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_LAST_NAME ));
user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL ));
user.setPhoneNumber(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PHONE_NUMBER ));
user.setBirthday(cursor.getString(cursor.getColumnIndex(COLUMN_USER_BARTH_DAY ));
user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD));
user.setGender(cursor.getString(cursor.getColumnIndex(COLUMN_USER_GENDER ));
//close cursor & database
cursor.close();
database.close();
return user;
}
Note : Becareful about your User object's setter functions which may be vary from my example and data types. Use c.getInt() if it is int and c.getString() if String.
You can use particular email address with password to query in database to get all the details.
public String getUserName(String email, String password) {
Cursor cursor = null;
String firstName = "";
try {
cursor = SQLiteDatabaseInstance_.rawQuery("SELECT * FROM " + TABLE_USER + " WHERE "+ COLUMN_USER_EMAIL +"?", new String[] {email+ ""}+ " AND "+COLUMN_USER_PASSWORD+"?", new String[] {password+ ""});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
firstName= cursor.getString(cursor.getColumnIndex(COLUMN_USER_FIRST_NAME));
}
return firstName;
}finally {
cursor.close();
}
}

SQLiteException: no such table Android Studio [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
Where I made mistake?
When I try to insert data into database, I get Toast message that I inserter,but in LOG file i see error:
no such table: reservation (code 1): , while compiling: INSERT INTO reservation(phone,address,surname,name,start,destination) VALUES (?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
DBHelper.java
package com.example.demir.carsharing;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.TextView;
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "carsharing.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
public static final String RES_TABLE="reservation";
public static final String COLUMN_NAME="name";
public static final String COLUMN_SURNAME="surname";
public static final String COLUMN_ADDRESS="address";
public static final String COLUMN_PHONE="phone";
public static final String COLUMN_START="start";
public static final String COLUMN_DESTINATION="destination";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public static final String CREATE_TABLE_RESERVATION = "CREATE TABLE " + RES_TABLE + "("
+ COLUMN_NAME + " TEXT,"
+ COLUMN_SURNAME + " TEXT,"
+ COLUMN_ADDRESS + " TEXT,"
+ COLUMN_PHONE + " TEXT,"
+ COLUMN_START + " TEXT,"
+ COLUMN_DESTINATION + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
db.execSQL(CREATE_TABLE_RESERVATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST" + USER_TABLE);
onCreate(db);
db.execSQL("DROP TABLE IF EXIST" + RES_TABLE);
onCreate(db);
}
public void addUser(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String email, String pass) {
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_EMAIL + " = " + "'" + email + "'" + " and " + COLUMN_PASS + " = " + "'" + pass + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
// method for inserting data from method reservation
public void addReservation(String name, String surname, String address, String phone, String start, String destination) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_SURNAME, surname);
values.put(COLUMN_ADDRESS, address);
values.put(COLUMN_PHONE, phone);
values.put(COLUMN_START, start);
values.put(COLUMN_DESTINATION, destination);
long a = db.insert(RES_TABLE, null, values);
db.close();
Log.e(TAG, "Data insetred" + a);
}
//Get data from Reservation
public boolean getData(String name, String surname, String address, String phone, String start, String destination) {
String query = "select * from " + RES_TABLE + " where " +
COLUMN_NAME + " = " + "'" + name + "'" + " , " + COLUMN_SURNAME + " = " + "'" + surname + "'" +
COLUMN_ADDRESS + " = " + "'" + address + "'" + " , " + COLUMN_PHONE + " = " + "'" + phone + "'" +
COLUMN_START + " = " + "'" + start + "'" + " , " + COLUMN_DESTINATION + " = " + "'" + destination + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
//insert data iinto Reservation
public boolean insertReservation(String name, String surname, String address, String phone, String start, String destination) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",name);
contentValues.put("surname",surname);
contentValues.put("address",address);
contentValues.put("phone",phone);
contentValues.put("start",start);
contentValues.put("destination",destination);
db.insert("reservation",null,contentValues);
return true;
}
}
Reservation.java
package com.example.demir.carsharing;
import android.content.Intent;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static com.example.demir.carsharing.R.id.etName;
public class ReservationActivity extends AppCompatActivity {
private Button save;
private EditText name, surname, address, phone, start, destination;
private DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
db = new DbHelper(this);
name = (EditText) findViewById(etName);
surname = (EditText) findViewById(R.id.etSurname);
address = (EditText) findViewById(R.id.etAddress);
phone = (EditText) findViewById(R.id.etPhone);
start = (EditText) findViewById(R.id.etStart);
destination = (EditText) findViewById(R.id.etDestination);
save = (Button) findViewById(R.id.btnSave);
AddData();
}
public void AddData(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = db.insertReservation(name.getText().toString(),
surname.getText().toString(),
address.getText().toString(),
phone.getText().toString(),
start.getText().toString(),
destination.getText().toString());
if(isInserted==true)
Toast.makeText(ReservationActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(ReservationActivity.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
});
}
}
You might have made changes to your helper class after creating the tables for the first time, in which case you must clear your app's data before you rerun, in your device/emulator go to App Info and the Clear Data "for >= Marshmallow go to App Info -> Storage -> Clear Data"
You don't have to delete and reinstall the whole app. that would be a waste of time.

Select query where day of week?

I have events table contains start time, end time,dayOfWeek ,location etc. I want to retrieve records based on dayOfweek. I am saving dayOfWeek as string.("Mon","Tue",etc..).
How can I retrieve record for each day?
This is my EventTableHelper.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
private static final String KEY_LOCATION = "location";
private static final String KEY_NOTIFICATION_TIME = "notification";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT,"
+ KEY_LOCATION + " TEXT,"
+ KEY_NOTIFICATION_TIME + "TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
values.put(KEY_NOTIFICATION_TIME,event.getNotificationTime());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE, KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5),cursor.getString(6));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setDayOfWeek(cursor.getString(4));
event.setLocation(cursor.getString(5));
event.setNotificationTime(cursor.getString(6));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
public int updateEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE,event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
values.put(KEY_NOTIFICATION_TIME,event.getNotificationTime());
// updating row
return db.update(TABLE, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.getId()) });
}
public void deleteEvent(EventData eventData) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE, KEY_ID + " = ?",
new String[]{String.valueOf(eventData.getId())});
db.close();
}
}
I tried to retrieve like this:
public List<EventData> getAllEvents(String day) {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE + " WHERE (" + KEY_DAY_OF_WEEK + " = " + day;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setDayOfWeek(cursor.getString(4));
event.setLocation(cursor.getString(5));
event.setNotificationTime(cursor.getString(6));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
But it's giving Syntax error :
android.database.sqlite.SQLiteException: near "Mon": syntax error (code 1): , while compiling: SELECT * FROM event WHERE (dayofweek = Mon)
I am retrieving events like this:
String day = "Mon"
mDb = new EventTableHelper(getActivity());
events = mDb.getAllEvents(day);
I am saving dayOfWeek in another activity. I want to retrieve records in fragment. I don't have idea how to pass day parameter in function.
Do like Pass value in single quote
String selectQuery = "SELECT * FROM " + TABLE + " WHERE " + KEY_DAY_OF_WEEK +" = '"+day+ "'";
Replace this
String selectQuery = "SELECT * FROM " + TABLE + " WHERE (" + KEY_DAY_OF_WEEK + " = " + day;
To
String selectQuery = "SELECT * FROM " + TABLE + " WHERE " + KEY_DAY_OF_WEEK + " = '" + day + "'";

Android SQLite helper - where should I close the connection?

I wrote a simple database helper class to make access to the DB from multiple activities more clean.
Here's the class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "name";
private static final String TABLE_SCORES = "scores";
private static final String KEY_ID = "id";
private static final String KEY_SCORE = "score";
private static final String KEY_DATE = "date";
SQLiteDatabase database;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
database = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase database) {
String CREATE_SCORES_TABLE = "CREATE TABLE " + TABLE_SCORES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_SCORE + " INTEGER,"
+ KEY_DATE + " TEXT" + ")";
database.execSQL(CREATE_SCORES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
onCreate(database);
}
void addScore(int score){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.US);
String currentDateandTime = dateFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(KEY_SCORE, score);
values.put(KEY_DATE, currentDateandTime);
database.insert(TABLE_SCORES, null, values);
//database.close();
}
void delete(){
database.delete(TABLE_SCORES, null, null);
}
public List<Score> getAllScores(){
List<Score> scoresList = new ArrayList<Score>();
String selectQuery = "SELECT * FROM " + TABLE_SCORES + " ORDER BY " + KEY_SCORE +" DESC LIMIT 10";
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Score score = new Score();
score.setId(Integer.parseInt(cursor.getString(0)));
score.setScore(Integer.parseInt(cursor.getString(1)));
score.setDate(cursor.getString(2));
scoresList.add(score);
} while (cursor.moveToNext());
}
return scoresList;
}
public int getHighscore() {
String selectQuery = "SELECT " + KEY_SCORE + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_SCORE +" DESC LIMIT 1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return 0;
}
public int getLastScoreID(){
String selectQuery = "SELECT " + KEY_ID + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_ID + " DESC LIMIT 1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return -1;
}
public int getLastScoreValue(){
String selectQuery = "SELECT " + KEY_SCORE + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return -1;
}
}
Here's the question:
where should I put database.close()? There's no such thing like destructor in Java (I really don't want to finalize() this one...).
Best regards.
Override the close() method of the SQLiteOpenHelper class
#Override
public synchronized void close() {
database.close();
super.close();
}

How to create multiple table?

Please help me, I'm newbie and I have problem. I try to create multiple table in this code but always error. this error say there is no table PENGINAPAN and i can't solve it.
this is DatabaseHelper class :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbwisata";
public static final String NAMA = "nama";
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS WISATA");
db.execSQL("CREATE TABLE if not exists WISATA (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
db.execSQL("DROP TABLE IF EXISTS PENGINAPAN");
db.execSQL("CREATE TABLE if not exists PENGINAPAN (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(NAMA, "Ancol");
db.insert("WISATA", NAMA, cv);
cv.put(NAMA, "Ragunan");
db.insert("WISATA", NAMA, cv);
cv.put(NAMA, "Taman Mini");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Melati");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Villa");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Bintang");
db.insert("PENGINAPAN", NAMA, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete("WISATA", null, null);
db.delete("WISATA", null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query("WISATA", new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
public Cursor fetchAllPenginapan(SQLiteDatabase db) {
return db.query("PENGINAPAN", new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
please help me.
I cleaned up your code. If it doesn't work, uninstall your app and install it again. Be sure you create the database before you try to write/read any data.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbwisata";
private static final String TABLE_WISATA = "WISATA";
private static final String TABLE_PENGINAPAN = "PENGINAPAN";
public static final String NAMA = "nama";
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WISATA);
db.execSQL("CREATE TABLE if not exists " + TABLE_WISATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
db.execSQL("DROP TABLE IF EXISTS PENGINAPAN");
db.execSQL("CREATE TABLE if not exists " + TABLE_PENGINAPAN + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAMA + " TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(NAMA, "Ancol");
db.insert(TABLE_WISATA, null, cv);
cv.put(NAMA, "Ragunan");
db.insert(TABLE_WISATA, null, cv);
cv.put(NAMA, "Taman Mini");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Melati");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Villa");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Bintang");
db.insert(TABLE_PENGINAPAN, null, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete(TABLE_WISATA, null, null);
db.delete(TABLE_WISATA, null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query(TABLE_WISATA, new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
public Cursor fetchAllPenginapan(SQLiteDatabase db) {
return db.query(TABLE_PENGINAPAN, new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Use this code and modify it as per your needs. i have added all comments so that you can understand where i am adding a table, where i am adding a column and where i am adding entries.
public class DatabaseHelper extends SQLiteOpenHelper {
//changing master
// Logcat tag
//add comment
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 3;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Table Names
private static final String TABLE_VIDEO = "video";
private static final String TABLE_PICTURE = "pictures";
private static final String TABLE_MUSIC = "music";
// Common column names
private static final String KEY_ID = "id";
private static final String KEY_FAV = "fav";
// MUSIC Table - column names
private static final String KEY_MUSIC_PATH = "path";
private static final String KEY_MUSIC_CAT_ID = "cat_id";
private static final String KEY_MUSIC_NAME = "music_name";
// PICTURE Table - column names
private static final String KEY_PICTURE_PATH = "path";
private static final String KEY_PICTURE_CAT_ID = "cat_id";
private static final String KEY_PICTURE_NAME = "picture_name";
// VIDEO Table - column names
private static final String KEY_VIDEO_PATH = "path";
private static final String KEY_VIDEO_CAT_ID = "cat_id";
private static final String KEY_VIDEO_SUBCAT_ID = "subcat_id";
private static final String KEY_VIDEO_NAME = "video_name";
// Table Create Statements
// Video table create statement
private static final String CREATE_TABLE_VIDEO = "CREATE TABLE "
+ TABLE_VIDEO + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_VIDEO_PATH + " TEXT,"
+ KEY_VIDEO_CAT_ID+ " INTEGER,"
+ KEY_VIDEO_SUBCAT_ID + " TEXT,"
+ KEY_VIDEO_NAME + " TEXT)";
// PICTURE table create statement
private static final String CREATE_TABLE_PICTURE = "CREATE TABLE "
+ TABLE_PICTURE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_PICTURE_PATH + " TEXT," + KEY_PICTURE_CAT_ID+ " INTEGER,"
+ KEY_PICTURE_NAME + " TEXT)";
// MUSIC table create statement
private static final String CREATE_TABLE_MUSIC = "CREATE TABLE "
+ TABLE_MUSIC + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_MUSIC_PATH + " TEXT," + KEY_MUSIC_CAT_ID+ " INTEGER,"
+ KEY_MUSIC_NAME + " TEXT)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// creating required tables
db.execSQL(CREATE_TABLE_PICTURE);
db.execSQL(CREATE_TABLE_MUSIC);
db.execSQL(CREATE_TABLE_VIDEO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VIDEO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PICTURE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MUSIC);
// create new tables
onCreate(db);
}
/*
* create videos
* */
/* public boolean addVideos(List<Video> video, int category_id){
SQLiteDatabase db = this.getWritableDatabase();
long id = 0;
for(int i = 0; i <video.size(); ++i){
ContentValues values = new ContentValues();
values.put(KEY_VIDEO_NAME, video.get(i).getName());
values.put(KEY_VIDEO_PATH, video.get(i).getPath());
values.put(KEY_VIDEO_CAT_ID, category_id);
// insert row
id = db.insert(TABLE_VIDEO, null, values);
}
if (id < 0)
return false;
return true;
}*/
// add videos
public void addvideos(Video item, int catid, String subcat) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (fav, path, cat_id, subcat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + subcat + "'," + "'" + item.getName() + "'" + ")");
}
// add pictures
public void addpictures(Picture item, int catid) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (path, cat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + item.getName() + "'" + ")");
}
// add music
public void addmusic(Music item, int catid) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (path, cat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + item.getName() + "'" + ")");
}
/*
* getting all videos
* */
public List<Video> getAllVideos() {
List<Video> lstVideo = new ArrayList<Video>();
String selectQuery = "SELECT * FROM " + TABLE_VIDEO;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Video video = new Video();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
video.setSubcategory(c.getString(c.getColumnIndex(KEY_VIDEO_SUBCAT_ID)));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
/*
* getting all videos by categories
* */
public List<Video> getAllVideosByCategory(String category) {
List<Video> lstVideo = new ArrayList<Video>();
String selectQuery = "SELECT * FROM " + TABLE_VIDEO +
" WHERE " + TABLE_VIDEO + "." + KEY_VIDEO_SUBCAT_ID +
" = " + category;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Video video = new Video();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
video.setSubcategory(c.getString(c.getColumnIndex(KEY_VIDEO_SUBCAT_ID)));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// getting all pictures
public List<Picture> getAllPictures() {
List<Picture> lstVideo = new ArrayList<Picture>();
String selectQuery = "SELECT * FROM " + TABLE_PICTURE;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Picture video = new Picture();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_PICTURE_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_PICTURE_PATH))));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// getting all music
public List<Music> getAllMusic() {
List<Music> lstVideo = new ArrayList<Music>();
String selectQuery = "SELECT * FROM " + TABLE_MUSIC;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Music video = new Music();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
}
Updated Answer: Picture class code is added
public class Picture {
public int id;
public String name;
public String path;
public int favourite;
public int getFavourite() {
return favourite;
}
public void setFavourite(int favourite) {
this.favourite = favourite;
}
public Picture(){
}
public Picture(int id, String name, String path){
this.id = id;
this.name = name;
this.path = path;
}
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 getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}

Categories