I am not able to find the db file where the database adapter is created a db and table. But i could see that the data is getting saved but i am not able to find my db file in my directories.
But i am able to save the entries and viewed on my screen.
Here is my DBAdapter class where i am creating the db..
public class DBAdapter {
private static final String DB_NAME = "clientList.db";
private static final int DB_VERSION = 1;
private static final String TABLE_CLIENT = "CLIENT";
private static final String COLUMN_CLIENT_ID = "CLIENT_ID";
private static final String COLUMN_CLIENT_NAME = "CLIENT_NAME";
private static final String query = "create table test_1 " + " (COLUMN_CLIENT_ID integer primary key, COLUMN_CLIENT_NAME text)";
private Context context;
private SQLiteDatabase sqliteDatabase;
private static DBAdapater dbAdapaterInstance;
private DBAdapater(Context context){
this.context = context;
sqliteDatabase = new DatabaseHelper(this.context,DB_NAME,null,DB_VERSION).getWritableDatabase();
}
public static DBAdapater getDbAdapaterInstance(Context context){
if(dbAdapaterInstance == null){
dbAdapaterInstance = new DBAdapater(context);
}
return dbAdapaterInstance;
}
public boolean insert(int clientId , String name ){
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_CLIENT_ID,clientId);
contentValues.put(COLUMN_CLIENT_NAME,name);
return sqliteDatabase.insert(TABLE_CLIENT,null,contentValues)>0;
}
public boolean delete(int ClientID){
return sqliteDatabase.delete(TABLE_CLIENT, COLUMN_CLIENT_ID + "=" + ClientID,null)>0;
}
public boolean modify(int ClientID , String newClient){
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_CLIENT_NAME,newClient);
return sqliteDatabase.update(TABLE_CLIENT,contentValues,COLUMN_CLIENT_ID + "=" + ClientID,null)>0;
}
public List<DataBean> getClient(){
List<DataBean> clientInfo = new ArrayList<DataBean>();
Cursor cursor = sqliteDatabase.query(TABLE_CLIENT , new String[]{COLUMN_CLIENT_ID,COLUMN_CLIENT_NAME},null,null,null,null,null,null);
if(cursor != null && cursor.getCount()>0){
while (cursor.moveToNext()) {
DataBean clientBean = new DataBean(cursor.getLong(0), cursor.getString(1));
clientInfo.add(clientBean);
}
}
return clientInfo;
}
//purpose of this class is to help outer class
public class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context , String databaseName , SQLiteDatabase.CursorFactory factory , int dbVersion){
super(context, databaseName , factory , dbVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
Here is my bean class
public class DataBean {
private long id;
private String clientName;
private String address;
public DataBean(){
super();
}
public DataBean(long id , String clientName){
this.id = id;
this.clientName = clientName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
}
If you don't specify any path, it will be stored in databases folder of your application directory.
Related
let's get straight. I want to build an movie app which have popular and kid, when data's liked, it store in SQLite. So in layout favorited, i make 2 layout, popular and kid. To distribute the data, i used clause category : movie and genre_ids : 16 / not. But when i test my app (previously i reinstall it, like suggestion in this site) and liked the movie, in logcat show something like this :
2019-10-11 09:24:05.941 5582-5582/com.example.apkfin5 E/SQLiteDatabase: Error inserting overview=blablabla. backdroppath=/n6bUvigpRFqSwmPp1m2YADdbRBc.jpg release_date=2019-10-02 [genre_ids]=null posterpath=/udDclJoHjfjb8Ekgsd4FDteOkCU.jpg id=475557 title=Joker category=movie
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: favorite.genre_ids (code 1299 SQLITE_CONSTRAINT_NOTNULL)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at com.example.apkfin5.db.FavHelper.insert(FavHelper.java:58)
at com.example.apkfin5.provider.FavProvider.insert(FavProvider.java:69)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:266)
at android.content.ContentResolver.insert(ContentResolver.java:1603)
at com.example.apkfin5.ui.activity.DetailFilmActivity.onOptionsItemSelected(DetailFilmActivity.java:170)
at android.app.Activity.onMenuItemSelected(Activity.java:3608)
You can see that the genre_ids is null, and i set my app, when data's null, data will not distribute to SQLite. So why i can't get the genre_ids ?
For support the diagnose, here's my dbHelper :
public class DbHelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "dbmovieapp";
private static final int DATABASE_VER = 1;
private static final String SQL_CREATE_FAVORITE = String.format(
"CREATE TABLE %s" + " (%s INTEGER PRIMARY KEY AUTOINCREMENT," +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s NULL)",
TABLE_FAVORITE,
DbContract.Columns._ID,
DbContract.Columns.FAVID,
DbContract.Columns.BACKDROPPATH,
DbContract.Columns.POSTERPATH,
DbContract.Columns.TITLE,
DbContract.Columns.RELEASE_DATE,
DbContract.Columns.OVERVIEW,
DbContract.Columns.CATEGORY,
DbContract.Columns.GENRE
);
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VER);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_FAVORITE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITE);
onCreate(sqLiteDatabase);
}
}
my favorite Helper :
public class FavHelper {
private static final String DATABASE_TABLE = TABLE_FAVORITE;
private static DbHelper dbHelper;
private static FavHelper INSTANCE;
private static SQLiteDatabase database;
public FavHelper(Context context) {dbHelper = new DbHelper(context);}
public static FavHelper getInstance(Context context) {
if(INSTANCE == null) {synchronized (SQLiteOpenHelper.class){
if(INSTANCE == null) {INSTANCE = new FavHelper(context);}
}}
return INSTANCE;
}
public void open() throws SQLException {database = dbHelper.getWritableDatabase();}
public void close() {dbHelper.close();
if (database.isOpen())
database.close();
}
public Cursor queryById(String id) {
return database.query(DATABASE_TABLE,null,_ID + " = ?"
,new String[]{id}, null, null, null, null);}
public Cursor query() {
return database.query(DATABASE_TABLE, null,null,null,null,null,_ID + " DESC");}
public long insert(ContentValues contentValues) {return database.insert(DATABASE_TABLE,null,contentValues); }
public int update(String id, ContentValues contentValues) {return database.update(DATABASE_TABLE,contentValues,_ID + " = ?", new String[] {id});}
public int delete(String id) {return database.delete(DATABASE_TABLE, _ID + " = ?", new String[]{id});}
public static ArrayList<Favorite> getFilmFavorite(Cursor cursor) {
ArrayList<Favorite> arrayList = new ArrayList<>();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(_ID));
int favId = cursor.getInt(cursor.getColumnIndexOrThrow(FAVID));
String backdrop = cursor.getString(cursor.getColumnIndexOrThrow(BACKDROPPATH));
String posterpath = cursor.getString(cursor.getColumnIndexOrThrow(POSTERPATH));
String title = cursor.getString(cursor.getColumnIndexOrThrow(TITLE));
String overview = cursor.getString(cursor.getColumnIndexOrThrow(OVERVIEW));
String release = cursor.getString(cursor.getColumnIndexOrThrow(RELEASE_DATE));
String category = cursor.getString(cursor.getColumnIndexOrThrow(CATEGORY));
List genre = Collections.singletonList(cursor.getString(cursor.getColumnIndexOrThrow(String.valueOf(GENRE))));
if(!genre.equals("16") && category.equals("movie")) {
arrayList.add(new Favorite(id, favId, title, backdrop, posterpath, overview, release, category, genre));
}}
return arrayList;
}
public static ArrayList<Favorite> getFilmKidFavorite(Cursor cursor) {
ArrayList<Favorite> arrayList = new ArrayList<>();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(_ID));
int favId = cursor.getInt(cursor.getColumnIndexOrThrow(FAVID));
String backdrop = cursor.getString(cursor.getColumnIndexOrThrow(BACKDROPPATH));
String posterpath = cursor.getString(cursor.getColumnIndexOrThrow(POSTERPATH));
String title = cursor.getString(cursor.getColumnIndexOrThrow(TITLE));
String overview = cursor.getString(cursor.getColumnIndexOrThrow(OVERVIEW));
String release = cursor.getString(cursor.getColumnIndexOrThrow(RELEASE_DATE));
String category = cursor.getString(cursor.getColumnIndexOrThrow(CATEGORY));
List genre = Collections.singletonList(cursor.getString(cursor.getColumnIndexOrThrow(String.valueOf(GENRE))));
if(genre.equals("16") && category.equals("movie")) {
arrayList.add(new Favorite(id, favId, title, backdrop, posterpath, overview, release, category, genre));
}
}
return arrayList;
}
my dbContract :
public class DbContract {
private static String SCHEME = "content";
public static String AUTHORITY = "com.example.apkfin5";
public static final class Columns implements BaseColumns {
public static String TABLE_FAVORITE = "favorite";
public static String FAVID = "id";
public static String BACKDROPPATH = "backdroppath";
public static String POSTERPATH = "posterpath";
public static String TITLE = "title";
public static String OVERVIEW = "overview";
public static String RELEASE_DATE = "release_date";
public static String CATEGORY = "category";
public static List GENRE = Collections.singletonList("genre_ids");
public static Uri C_URI = new Uri.Builder().scheme(SCHEME).authority(AUTHORITY)
.appendPath(TABLE_FAVORITE).build();
}
public static String getColumnString(Cursor cursor, String column) {return cursor.getString(cursor.getColumnIndex(column));}
public static int getColumnInt(Cursor cursor, String column) {return cursor.getInt(cursor.getColumnIndex(column));}
}
a half of my detail movie when it's being like and store it in Favorite model :
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(cekFav()) {
Uri uri = Uri.parse(C_URI + "/" + id);
getContentResolver().delete(uri,null,null);
item.setIcon(R.drawable.ic_favorite_border_24dp);
Toast.makeText(this,getString(R.string.unFav), Toast.LENGTH_LONG).show();}
else {
favorite.setId(Favid);
favorite.setTitle(tittle);
favorite.setPosterPath(poster);
favorite.setBackdropPath(backdrop);
favorite.setReleasedate(releasedate);
favorite.setOverView(overView);
favorite.setGenre(Collections.singletonList(genre));
favorite.setCategoty("movie");
ContentValues contentValues = new ContentValues();
contentValues.put(FAVID,Favid);
contentValues.put(TITLE,tittle);
contentValues.put(OVERVIEW,overView);
contentValues.put(BACKDROPPATH,backdrop);
contentValues.put(RELEASE_DATE,releasedate);
contentValues.put(POSTERPATH,poster);
contentValues.put(String.valueOf(GENRE), genre);
contentValues.put(CATEGORY,"movie");
if (getContentResolver().insert(C_URI,contentValues) != null) {
Toast.makeText(this,tittle + " " + getString(R.string.Fav), Toast.LENGTH_LONG).show();
item.setIcon(R.drawable.ic_favorite);
} else { Toast.makeText(this, tittle + " " + getString(R.string.favError), Toast.LENGTH_LONG).show();}
}
sendRefreshBroadcast(getApplicationContext());
return super.onOptionsItemSelected(item);
}
Model of movie to Store data from Api :
public class Film {
#SerializedName("id")
#Expose
private int id;
#SerializedName("backdrop_path")
#Expose
private String backdrop;
#SerializedName("title")
#Expose
private String title;
#SerializedName("poster_path")
#Expose
private String posterPath;
#SerializedName("release_date")
#Expose
private String releaseDate;
#SerializedName("vote_average")
#Expose
private float rating;
#SerializedName("genre_ids")
#Expose
private List<Integer> genreIds;
#SerializedName("overview")
#Expose
private String overView;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBackdrop() {return backdrop;}
public void setBackdrop(String backdrop) {this.backdrop = backdrop;}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public List<Integer> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Integer> genreIds) {
this.genreIds = genreIds;
}
public String getOverView() {return overView;}
public void setOverView(String overView) {this.overView = overView;}
}
Then Favorite Model, to storage data when's like :
public class Favorite implements Parcelable {
private int id;
private int mId;
private String backdropPath;
private String posterPath;
private String title;
private String overview;
private String releasedate;
private String category;
private List genre;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public int getmId() { return mId; }
public void setmId(int mId) { this.mId = mId; }
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOverView() {
return overview;
}
public void setOverView(String overview) {
this.overview = overview;
}
public String getReleasedate() { return releasedate; }
public void setReleasedate(String releasedate) { this.releasedate = releasedate; }
public String getCategory() {return category;}
public void setCategoty(String categoty) {
this.category = categoty;
}
public List getGenre() {return genre;}
public void setGenre(List genre) {this.genre = genre;}
public Favorite() {
}
public Favorite(int id, int mId, String title, String backdrop, String posterpath, String overview, String release, String category, List genre) {
this.id = id;
this.mId = mId;
this.backdropPath = backdrop;
this.posterPath = posterpath;
this.overview = overview;
this.title = title;
this.releasedate = release;
this.category = category;
this.genre = genre;
}
protected Favorite(Parcel in) {
id = in.readInt();
mId = in.readInt();
backdropPath = in.readString();
posterPath = in.readString();
title = in.readString();
overview = in.readString();
releasedate = in.readString();
category = in.readString();
if (in.readByte() == 0x01) {
genre = new ArrayList<>();
in.readList(genre, Parcelable.class.getClassLoader());
} else {
genre = null;
}
}
public Favorite(Cursor cursor) {
this.id = getColumnInt(cursor,_ID);
this.mId = getColumnInt(cursor,FAVID);
this.title = getColumnString(cursor,TITLE);
this.category = getColumnString(cursor,CATEGORY);
this.posterPath = getColumnString(cursor,POSTERPATH);
this.overview = getColumnString(cursor, OVERVIEW);
this.backdropPath = getColumnString(cursor, BACKDROPPATH);
this.genre = Collections.singletonList(getColumnString(cursor, String.valueOf(GENRE)));
}
public static final Creator<Favorite> CREATOR = new Creator<Favorite>() {
#Override
public Favorite createFromParcel(Parcel in) {
return new Favorite(in);
}
#Override
public Favorite[] newArray(int size) {
return new Favorite[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeInt(mId);
parcel.writeString(backdropPath);
parcel.writeString(posterPath);
parcel.writeString(title);
parcel.writeString(overview);
parcel.writeString(releasedate);
parcel.writeString(category);
if (genre == null) {
parcel.writeByte((byte) (0x00));
} else {
parcel.writeByte((byte) (0x01));
parcel.writeList(genre);
}
}
}
This's my first time assigment to build with two different view from 1 API. So ya, i got a little confused here. Thank for the answer.
i've been realized that i need to deserialized this list : genre_id, so guys, can you tell me how to deserialized "genre_ids": [
99,
10402
]
is it use Class List, then the value just Public int id ? or i need more id ? cause some genre_ids have more than one int.
So, i try to solve with deserialized, but i didn't understand how to implement with that data to the database.
And the best i can do was make another database for save data when it clicked. Before that, i build another request from the web so i can get data only from kid. Make sure that the other request didn't get data, set the request with "without_genres", i'm using tmdb btw. That need because you don't want duplicate kid's datas from reguler movie and kid show in tab favorite. Furthermore, i used that database to make widget. So you don't want your 2 widget (reguler and kid) have similiar movie kid in both of it.
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
public static final String Favourites = "Favourites";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL, " + Favourites + " Boolean NOT NULL);";
private static final String Show_Table = "Select * From " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void showData(SQLiteDatabase db){db.execSQL(Show_Table);}
public void insertData(String contactName, String phoneNumber,String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
values.put(DatabaseHelper.Favourites, favourites);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
public int addToFavourites(String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Favourites, favourites);
// updating row
return db.update(DatabaseHelper.TABLE_NAME, values, DatabaseHelper.Phone_Number + " = ?", new String[]{favourites});
}
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHelper.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Modal
public class FavouritesHelper {
public String Name;
public String PhoneNumber;
public boolean Favourites;
public FavouritesHelper() {
}
public FavouritesHelper(String Name, String PhoneNumber, Boolean Favourites) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
this.Favourites = Favourites;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public boolean getFavourites() {
return Favourites;
}
public void setFavourites(boolean Favourites) {
this.Favourites = Favourites;
}
}
This is my database helper and I'm trying to fetch the table in logcat but I don't know how to do that. I know the code is Select * from <tablename> but how do i implement that. I want to see all the data in my table.
Soltion:
Please follow the following steps:
First Step:
Make the below method in DatabaseHelper class:
public List<FavouritesHelper> getAllData() {
List<FavouritesHelper> data = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + FavouritesHelper.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FavouritesHelper alldata = new FavouritesHelper();
alldata.setName(cursor.getString(cursor.getColumnIndex(FavouritesHelper.Name)));
alldata.setPhoneNumber(cursor.getString(cursor.getColumnIndex(FavouritesHelper.PhoneNumber)));
alldata.setFavourites(cursor.getBoolean(cursor.getColumnIndex(FavouritesHelper.Favourites)));
data.add(alldata);
} while (cursor.moveToNext());
}
// close db connection
db.close();
// return notes list
return data;
}
Second Step:
In your activity:
declare a global object: List<FavouritesHelper> AllData inside your class.
Third Step:
then, add this AllData = new List<FavouritesHelper>(); in your onCreate()
Fourth Step:
write this in your activity after inserting data: AllData = database.getAllData();
Fifth Step:
Print it in log using below statement:
for(FavouritesHelper helper : AllData) {
Log.e("values : ", helper.getName() + ", " + helper.getPhoneNumber() + ", " + helper.getFavourites());
}
That's it.
Try it out. Hope it Helps.
As #pskink suggested you can use dumpCursor like this
create this method inside your DatabaseHelper class
public void dumpCursorInLogCat() {
//here first getting the readable database
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(Show_Table, null);
//here is how you can Dump cursor
DatabaseUtils.dumpCursor(cursor);
cursor.close();
}
and call this method in your activity whenever you want to show data in logcat
call it inside your activity like
new DatabaseHelper(your_activity_name.this).dumpCursorInLogCat();
I am trying to create a simple SQLite database in android. I am following this tutorial. But the code gives this error "Cannot resolve constructor Contact()". Below is the code for DatabaseHandler.java. I have pointed out the line where the error occurs so it's easy to understand.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Usama on 10/7/2017.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "favouritesmanager";
// Contacts table name
private static final String TABLE_CONTACTS = "favourites";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_ADRESS = "adress";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_ADRESS + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
values.put(KEY_ADRESS, contact.getAdress()); //address
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact(); <<<< HERE IS THE ERROR
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contact.setAdress(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
and here is the contact.java class
public class Contact {
int _id;
String _name;
String _phone_number;
String _adress;
// constructor
public Contact(int id, String name, String _phone_number, String adress){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
this._adress = adress;
}
// constructor
public Contact(String name, String _phone_number, String adress){
this._name = name;
this._phone_number = _phone_number;
this._adress = adress;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
//getting adress
public String getAdress(){
return this._adress;
}
//setting adress
public void setAdress(String adresstowrite){
this._adress = adresstowrite;
}
}
Any fixes for this error please?
Create empty constructor.
// Empty constructor
public Contact(){
}
I am trying to read data from SQLite in android using three parameters, id, name and date. For example, id="number" and name="something" and date between ("first date", "second date"). the problem is that, i cannot figure out what to do with the last function. There are two more parameters left and i dont know what to do or where to place it. So does anyone have any experience and familiar with this code style and can share or help me? (I take this code from book too and there was not any solution for related to this at all in the book.)
//Table person; It contain the same attribute as Person class
public static final class PersonTable
{
public static final String NAME = "Persons";
public static final class Cols
{
static final String ID = "id";
static final String NAME = "name";
static final String DATE = "date";
}
}
public class PersonCursorWrapper extends CursorWrapper
{
public PersonCursorWrapper(Cursor cursor)
{
super(cursor);
}
public Person getPerson()
{
int id = geIntI(getColumnIndex(PersonTable.Cols.ID));
String name = getString(getColumnIndex(PersonTable.Cols.NAME));
long date = getLong(getColumnIndex(PersonTable.Cols.DATE));
Person Person = new Person();
Person.id(id);
Person.setDate(new Date(date));
Person.setName(name);
return Person;
}
}
}
private PersonCursorWrapper queryPersons(String whereClause, String[] whereArgs)
{
Cursor cursor = mDatabase.query
(
PersonTable.NAME,
null,
whereClause,
whereArgs,
null,
null,
null
);
return new PersonCursorWrapper(cursor);
}
public Person getPerson(int id, String name, String date)
{
PersonCursorWrapper cursor = queryPersons(
PersonTable.Cols.ID + " = ?"+" "+
PersonTable.Cols.NAME + " = ?"+" "+
PersonTable.Cols.DATE + " = ?",
new String[] { id.toString() }
);
try
{
if (cursor.getCount() == 0)
{
return null;
}
cursor.moveToFirst();
return cursor.getPerson();
}
finally
{
cursor.close();
}
}
You have three parameter markers (?), so you have to give it three parameters:
cursor = queryPersons(
...,
new String[] { id.toString(), name, date }
);
For android sqlite database operations you can simply use SQLiteOpenHelper class provided with android.
This is a complete implementation for your case with SQLiteOpenHelper.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler2 extends SQLiteOpenHelper {
// Database details
private static final int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "dbname.db";
// Table names
private static String TABLE_PERSON = "person";
// Table Columns name
private static final String COLUMN_ID = "workout_id";
private static final String COLUMN_NAME = "exercise_id";
// Create queries
private static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_PERSON + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT NOT NULL)";
public DatabaseHandler2(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PERSON);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_PERSON);
}
public Person getPerson(int id) {
Person person = new Person();
String selectQuery = "SELECT * FROM " + TABLE_PERSON + " WHERE " + COLUMN_ID + "=" + id;
SQLiteDatabase rdb;
rdb = this.getReadableDatabase();
Cursor cursor = rdb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
rdb.close();
return person;
}
public List<Person> getAllPersons() {
List<Person> personList = new ArrayList<Person>();
String selectQuery = "SELECT * FROM " + TABLE_PERSON;
SQLiteDatabase rdb;
rdb = this.getReadableDatabase();
Cursor cursor = rdb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Person person = new Person();
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
personList.add(person);
} while (cursor.moveToNext());
}
cursor.close();
rdb.close();
return personList;
}
public void savePerson(Person person) {
SQLiteDatabase wdb;
ContentValues values = new ContentValues();
values.put(COLUMN_ID, person.getId());
values.put(COLUMN_NAME, person.getName());
wdb = this.getWritableDatabase();
long rowId = wdb.insert(TABLE_PERSON, null, values);
wdb.close();
}
public void deletePerson(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PERSON, COLUMN_ID + "='" + id + "'", null);
db.close();
}
public boolean renamePerson(int id, String newName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, newName);
int numOfRowsEffected = db.update(TABLE_PERSON, values, COLUMN_ID + "='" + id + "'", null);
db.close();
return numOfRowsEffected > 0 ? true : false;
}
}
Here is the Person class
public class Person {
private int id;
private String name;
public Person() {
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I've been trying to store doctor details in SQLite database using signup activity but my app crashes everytime i click on signup button.It shows no error. I've followed many online videos but it just doesn't work for my application
what is the error? Why does the app crash?
dsignup.java
DatabaseHelper1 helper1 = new DatabaseHelper1(this);
public void OnButton_regclick(View v)
{
if(v.getId()== R.id.button_reg)
{
EditText dname = (EditText)findViewById(R.id.dname);
EditText username = (EditText)findViewById(R.id.username);
EditText docemail = (EditText)findViewById(R.id.docemail);
EditText password = (EditText)findViewById(R.id.password);
EditText reg_num = (EditText)findViewById(R.id.reg_num);
EditText dcontact = (EditText)findViewById(R.id.dcontact);
EditText wcontact = (EditText)findViewById(R.id.wcontact);
RadioGroup gender = (RadioGroup) findViewById(R.id.gender);
int selectedid = gender.getCheckedRadioButtonId();
EditText address = (EditText)findViewById(R.id.address);
EditText pincode = (EditText)findViewById(R.id.pincode);
EditText specialization =(EditText)findViewById(R.id.specialization);
EditText experience = (EditText)findViewById(R.id.experience);
EditText category = (EditText)findViewById(R.id.category);
RadioButton rb = (RadioButton)findViewById(selectedid);
String dnamestr = dname.getText().toString();
String docemailstr = docemail.getText().toString();
String usernamestr = username.getText().toString();
String passwordstr = password.getText().toString();
String dcontactstr = dcontact.getText().toString();
String reg_numstr = reg_num.getText().toString();
String specializationstr = specialization.getText().toString();
String experiencestr = experience.getText().toString();
String categorystr = category.getText().toString();
String genderstr = rb.getText().toString();
String pincodestr = pincode.getText().toString();
String addressstr = address.getText().toString();
String wcontactstr = wcontact.getText().toString();
Contact c = new Contact();
c.setDname(dnamestr);
c.setDocemail(docemailstr);
c.setUsername(usernamestr);
c.setPassword(passwordstr);
c.setDcontact(dcontactstr);
c.setReg_num(reg_numstr);
c.setSpecialization(specializationstr);
c.setExperience(experiencestr);
c.setCategory(categorystr);
c.setGender(genderstr);
c.setPincode(pincodestr);
c.setAddress(addressstr);
c.setWcontact(wcontactstr);
helper1.insertContact(c);
}
DatabaseHelper1.java
public class DatabaseHelper1 extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME1 = "doctors";
private static final String COLUMN_ID1 = "id1";
private static final String COLUMN_DNAME ="dname";
private static final String COLUMN_DCONTACT ="dcontact";
private static final String COLUMN_REG_NUM ="reg_num";
private static final String COLUMN_SPECIALIZATION ="specialization";
private static final String COLUMN_EXPERIENCE ="experience";
private static final String COLUMN_CATEGORY ="category";
private static final String COLUMN_AVAILABLEFROM ="availablefrom";
private static final String COLUMN_PASSWORD ="password";
private static final String COLUMN_USERNAME ="username";
private static final String COLUMN_AVAILABLETO ="availableto";
private static final String COLUMN_GENDER ="gender";
private static final String COLUMN_DOCEMAIL ="docemail";
private static final String COLUMN_PINCODE ="pincode";
private static final String COLUMN_ADDRESS ="address";
private static final String COLUMN_WCONTACT ="wcontact";
private static final String COLUMN_TIMETO ="timeto";
private static final String COLUMN_TIMEFROM ="timefrom";
private static final String COLUMN_LATITUDE ="latitude";
private static final String COLUMN_LONGITUDE ="longitude";
SQLiteDatabase db1;
private static final String TABLE_CREATE1 = "create table doctors (id integer primary key not null, dname text not null,reg_num integer not null , specialization text not null, experience text not null, category text not null," +
"available from text not null, username text not null, availableto text not null, gender text not null, email text not null, pincode integer not null, address text not null " +
" wcontact integer not null, timeto time, timefrom time, latitude float(10,6), longitude float(10,6));";
public DatabaseHelper1(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db1) {
db1.execSQL(TABLE_CREATE1);
this.db1 = db1;
}
public void insertContact(Contact c) {
db1 = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from doctors";
Cursor cursor = db1.rawQuery(query , null);
int count = cursor.getCount();
values.put(COLUMN_ID1 , count);
values.put(COLUMN_DNAME, c.getDname());
values.put(COLUMN_DCONTACT, c.getDcontact());
values.put(COLUMN_REG_NUM, c.getReg_num());
values.put(COLUMN_SPECIALIZATION, c.getSpecialization());
values.put(COLUMN_EXPERIENCE, c.getExperience());
values.put(COLUMN_CATEGORY, c.getCategory());
values.put(COLUMN_AVAILABLEFROM, c.getAvailablefrom());
values.put(COLUMN_PASSWORD, c.getPassword());
values.put(COLUMN_USERNAME, c.getUsername());
values.put(COLUMN_AVAILABLETO, c.getAvailableto());
values.put(COLUMN_GENDER, c.getGender());
values.put(COLUMN_DOCEMAIL, c.getDocemail());
values.put(COLUMN_PINCODE, c.getPincode());
values.put(COLUMN_ADDRESS, c.getAddress());
values.put(COLUMN_WCONTACT, c.getWcontact());
//values.put(COLUMN_TIMETO, c.getTimeto());
// values.put(COLUMN_TIMEFROM, c.getTimefrom());
// values.put(COLUMN_LATITUDE, c.getLatitude());
//values.put(COLUMN_LONGITUDE, c.getLongitude());
db1.insert(TABLE_NAME1, null, values);
db1.close();
}
public String searchPass(String username)
{
db1 = this.getReadableDatabase();
String query = "select uname, pass from "+TABLE_NAME1;
Cursor cursor = db1.rawQuery(query , null);
String a, b;
b = "not found";
if(cursor.moveToFirst())
{
do{
a = cursor.getString(0);
if(a.equals(username))
{
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
#Override
public void onUpgrade(SQLiteDatabase db1, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME1;
db1.execSQL(query);
this.onCreate(db1);
}
}
Contact.java
public class Contact {
String name ,email,uname,pass,gender1,dname,dcontact,reg_num,specialization, experience, category, availablefrom, password, username, availableto,gender,docemail,pincode,address,wcontact;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEmail()
{
return this.email;
}
public void setUname(String uname)
{
this.uname = uname;
}
public String getUname()
{
return this.uname;
}
public void setPass(String pass)
{
this.pass = pass;
}
public String getPass()
{
return this.pass;
}
public void setGender1(String gender)
{
this.gender1 = gender;
}
public String getGender1()
{
return this.gender1;
}
public void setDname(String dname)
{
this.dname = dname;
}
public String getDname()
{
return this.dname;
}
public void setReg_num(String reg_num)
{
this.reg_num = reg_num;
}
public String getReg_num()
{
return this.reg_num;
}
public void setDcontact(String dcontact)
{
this.name = dcontact;
}
public String getDcontact()
{
return this.dcontact;
}
public void setSpecialization(String specialization)
{
this.specialization = specialization;
}
public String getSpecialization()
{
return this.specialization;
}
public void setExperience(String experience)
{
this.experience = experience;
}
public String getExperience()
{
return this.experience;
}
public void setCategory(String category)
{
this.category = category;
}
public String getCategory()
{
return this.category;
}
public void setAvailablefrom(String availablefrom)
{
this.availablefrom = availablefrom;
}
public String getAvailablefrom()
{
return this.availablefrom;
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return this.password;
}
public void setUsername(String username)
{
this.username = username;
}
public String getUsername()
{
return this.username;
}
public void setAvailableto(String availableto)
{
this.availableto = availableto;
}
public String getAvailableto()
{
return this.availableto;
}
public void setGender(String gender)
{
this.gender = gender;
}
public String getGender()
{
return this.gender;
}
public void setDocemail(String docemail)
{
this.docemail = docemail;
}
public String getDocemail()
{
return this.docemail;
}
public void setPincode(String pincode) {this.pincode = pincode;}
public String getPincode()
{
return this.pincode;
}
public void setAddress(String address)
{
this.address = address;
}
public String getAddress()
{
return this.address;
}
public void setWcontact(String wcontact)
{
this.wcontact = wcontact;
}
public String getWcontact()
{
return this.wcontact;
}
public void setTimeto(String timeto)
{
this.timeto = timeto;
}
public String getTimeto() {return this.timeto;}
public void setTimefrom(String timefrom)
{
this.timefrom = timefrom;
}
public String getTimefrom()
{
return this.timefrom;
}
}
Try to put some order on your code because is not easy read it. Also, create a method where you can inicialite your widgets, something like this:
public static void startCom(){
text1 = (textView) findById....
.
.
.
}
Only on the method onCreate you invoke startComp, just to save the order of the code.