How to enter information in SQLite database? (App Crashes) [duplicate] - java

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.

Related

How you save an Array from TMDB to SQLite

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.

SQLite db file not found on Android

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.

Return more that one ArrayList

I'm trying to deal with this baking JSON:
in android app so this is the class to bring the JSON data from link:
OpenBakingJsonUtils.java:
public final class OpenBakingJsonUtils {
public static ArrayList<ArraysLists> getSimpleBakingStringsFromJson(Context context, String bakingJsonString)
throws JSONException {
final String ID = "id";
final String NAME = "name";
final String SERVINGS = "servings";
final String INGREDIENTS = "ingredients";
final String STEPS = "steps";
final String QUANTITY = "quantity";
final String MEASURE = "measure";
final String INGREDIENT = "ingredient";
final String IDSTEPS = "id";
final String SHORTDESCRIPTION = "shortDescription";
final String DESCRIPTION = "description";
final String VIDEOURL = "videoURL";
final String THUMBNAILURL = "thumbnailURL";
ArrayList<ArraysLists> parsedRecipeData = new ArrayList<ArraysLists>();
ArrayList<BakingItem> Baking = new ArrayList<BakingItem>();
JSONArray recipeArray = new JSONArray(bakingJsonString);
for (int i = 0; i < recipeArray.length(); i++) {
int id;
String name;
int servings;
double quantity;
String measure;
String ingredient;
int idSteps;
String shortDescription;
String description;
String videoURL;
String thumbnailURL;
JSONObject recipeObject = recipeArray.getJSONObject(i);
id = recipeObject.getInt(ID);
name = recipeObject.getString(NAME);
servings = recipeObject.getInt(SERVINGS);
ArrayList<IngredientsItem> Ingredients = new ArrayList<IngredientsItem>();
JSONArray ingredientsArray = recipeObject.getJSONArray(INGREDIENTS);
for(int j = 0 ; j< ingredientsArray.length(); j++) {
JSONObject ingredientsObject = ingredientsArray.getJSONObject(j);
quantity = ingredientsObject.getDouble(QUANTITY);
measure = ingredientsObject.getString(MEASURE);
ingredient = ingredientsObject.getString(INGREDIENT);
Ingredients.add(new IngredientsItem(quantity, measure, ingredient));
}
ArrayList<StepsItem> Steps = new ArrayList<StepsItem>();
JSONArray stepsArray = recipeObject.getJSONArray(STEPS);
for(int j = 0 ; j< stepsArray.length(); j++) {
JSONObject stepsObject = stepsArray.getJSONObject(j);
idSteps = recipeObject.getInt(IDSTEPS);
shortDescription = stepsObject.getString(SHORTDESCRIPTION);
description = stepsObject.getString(DESCRIPTION);
videoURL = stepsObject.getString(VIDEOURL);
thumbnailURL = stepsObject.getString(THUMBNAILURL);
Steps.add(new StepsItem(idSteps, shortDescription, description, videoURL, thumbnailURL));
}
Baking.add(new BakingItem(id, name, servings, Ingredients, Steps));
parsedRecipeData.add(new ArraysLists(Baking, Ingredients, Steps));
}
return parsedRecipeData;
}
}
as you see there are 3 ArrayList classes:
ArrayList<BakingItem>
ArrayList<IngredientsItem>
ArrayList<StepsItem>
and this is the code for each one:
BakingItem.java:
public class BakingItem implements Parcelable {
private int id;
private String name;
private int servings;
private ArrayList<IngredientsItem> ingredients = new ArrayList<IngredientsItem>();
private ArrayList<StepsItem> steps = new ArrayList<StepsItem>();
public BakingItem(int id, String name, int servings, ArrayList<IngredientsItem> ingredients, ArrayList<StepsItem> steps) {
this.id = id;
this.name = name;
this.servings = servings;
this.ingredients = ingredients;
this.steps = steps;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(name);
out.writeInt(servings);
out.writeTypedList(ingredients);
out.writeTypedList(steps);
}
private BakingItem(Parcel in) {
this.id = in.readInt();
this.name = in.readString();
this.servings = in.readInt();
ingredients = new ArrayList<IngredientsItem>();
in.readTypedList(ingredients, IngredientsItem.CREATOR);
}
public BakingItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<BakingItem> CREATOR = new Parcelable.Creator<BakingItem>() {
#Override
public BakingItem createFromParcel(Parcel in) {
return new BakingItem(in);
}
#Override
public BakingItem[] newArray(int i) {
return new BakingItem[i];
}
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getServings() {
return servings;
}
}
IngredientsItem.java:
public class IngredientsItem implements Parcelable {
private double quantity;
private String measure;
private String ingredient;
public IngredientsItem(double quantity, String measure, String ingredient) {
this.quantity = quantity;
this.measure = measure;
this.ingredient = ingredient;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeDouble(quantity);
out.writeString(measure);
out.writeString(ingredient);
}
private IngredientsItem(Parcel in) {
this.quantity = in.readDouble();
this.measure = in.readString();
this.ingredient = in.readString();
}
public IngredientsItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<IngredientsItem> CREATOR = new Parcelable.Creator<IngredientsItem>() {
#Override
public IngredientsItem createFromParcel(Parcel in) {
return new IngredientsItem(in);
}
#Override
public IngredientsItem[] newArray(int i) {
return new IngredientsItem[i];
}
};
public double getQuantity() {
return quantity;
}
public String getMeasure() {
return measure;
}
public String getIngredient() {
return ingredient;
}
}
as well as the StepsItem class
and the forth is the ArraysLists.java which contain all the 3 arrays above and returned by the OpenBakingJsonUtils.java:
Then I'm trying to call these JSON data in different activities
so in MainActivity.java in loadInBackground:
Override
public ArrayList<BakingItem> loadInBackground() {
URL recipeRequestUrl = NetworkUtils.buildUrl();
try {
String jsonBakingResponse = NetworkUtils.getResponseFromHttpUrl(recipeRequestUrl);
ArrayList<ArraysLists> simpleJsonBakingData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(MainActivity.this, jsonBakingResponse);
return simpleJsonBakingData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I call the returned ArrayList from OpenBakingJsonUtils.java which is in this case the ArraysLists,
then in DetailActivity.java in doInBackground:
#Override
protected ArrayList<ArraysLists> doInBackground(Object... params) {
if (params.length == 0) {
return null;
}
URL reviewsRequestUrl = NetworkUtils.buildUrl();
try {
String jsonReviewResponse = NetworkUtils.getResponseFromHttpUrl(reviewsRequestUrl);
ArrayList<ArraysLists> simpleJsonReviewData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(DetailsActivity.this, jsonReviewResponse);
return simpleJsonReviewData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
here I call the ArrayList of ArraysLists too but the problem in adapters of MainActivity.java and DetailsActivity.java in onBindViewHolder:
holder.CommentContent.setText(String.valueOf(mCommentsItems.get(position).getQuantity()));
it just says that cannot resolve method getQuantity() which is in IngredientsItem.java while I used the ArraysLists.java that returned by OpenBakingJsonUtils.java
so what should I do to call methods from BakingItem.java and IngredientsItem.java while I use the returned ArraysLists.java ?

How can I create a instance of a class with an array of Strings as the only instance variable?

I have written a class Form. An array of 10 Strings is the only parameter in the constructor. How can I create an instance of the class? I'm sure there are other problems in my setters and getters but I cant test them until I fix this.
public class FormLab {
public static void main(String[]args){
Form f1 = new Form(String webForm);
System.out.println(print(String[] webForm));
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}
}
public class Form {
String[] webForm = new String[10];
private String userID;
private String pw;
private String pw2;
private String email;
private String name;
private String address;
private String city;
private String state;
private String zip;
private String telephone;
//constructor
public Form(String[] webForm){
//filling array with field values
webForm[0] = "0123456789";
webForm[1] = "java123";
webForm[2] = "java123";
webForm[3] = "luke.skywalker#jedi.com";
webForm[4] = "Luke Skywalker";
webForm[5] = "1234 The Force Way";
webForm[6] = "Rome";
webForm[7] = "GA";
webForm[8] = "30161";
webForm[9] = "7065551234";
}
public boolean getEmptyFields() {
//boolean empty = false;
for(int i = 0; i < webForm.length; i++){
if(webForm[i]!= null){
return true;
}
}
return false;
}
public String getUserID(){
return userID;
}
public void setUserId(String userID){
this.userID = userID;
}
public String getPw(){
return pw;
}
public void setPw(String pw){
this.pw = pw;
}
public String getPw2(){
return pw2;
}
public void setPw2(String pw2){
this.pw2 = pw2;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return state;
}
public void setState(String state){
this.state = state;
}
public String getZip(){
return userID;
}
public void setZip(String zip){
this.zip = zip;
}
public String getTelephone(){
return telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public int getCharNum(String userID) {
int userLength = 0;
//userID.length();
return userLength;
}
public boolean getPwCheck() {
boolean check = pw.equalsIgnoreCase(pw2);
// pw.equalsIgnoreCase(pw2);
return check;
}
public boolean getEmailCheck(String email) {
if(email.contains("#") && email.contains(".")){
return true;
}
return false;
}
public static void getPrint(String[] webForm) {
System.out.println(webForm.toString());
}
}
Use method arraycopy.
public Form(String[] webForm){
System.arraycopy(webForm, 0, this.webForm, 0, webForm.length);
}
The constructor takes a string array as argument, but you are passing it a string, try:
myList = new String[];
myForm = new Form(myList);
You need to declare your array before putting it as a parameter as follow:
public class FormLab {
public static void main(String[]args){
String webForm = new String[10];
Form f1 = new Form(webForm);
/*System.out.println(print(String[] webForm)); THIS IS WRONG*/
/*TO PRINT THE VALUES IN THE ARRAY YOU NEED TO WRITE A METHOD IN UR
FORM CLASS THAT WILL LOOP THRU UR VARIABLE AND PRINT*/
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}

Can't get ComboboxTableCell in javafx app

I am trying to show a combobox for each record that is fetched from database,but unfortunatley i can't get any combobox in expected column.
Here is code for my model class:
public class Employee {
private final int id;
private final SimpleStringProperty ename;
private final SimpleStringProperty ecnic;
private final SimpleDoubleProperty ebalance;
private final SimpleDoubleProperty etotalpaid;
private SimpleStringProperty estatus;
public Employee(int id, String ename, String ecnic, Double ebalance,
Double etotalpaid, String estatus) {
super();
this.id = id;
this.ename = new SimpleStringProperty(ename);
this.ecnic = new SimpleStringProperty(ecnic);
this.ebalance = new SimpleDoubleProperty(ebalance);
this.etotalpaid = new SimpleDoubleProperty(etotalpaid);
this.estatus = new SimpleStringProperty(estatus);
}
public String getEstatusproperty() {
return estatus.get();
}
public String getEstatus() {
return estatus.get();
}
public void setEstatus(String estatus) {
this.estatus = new SimpleStringProperty(estatus);
}
public int getId() {
return id;
}
public String getEname() {
return ename.get();
}
public String getEcnic() {
return ecnic.get();
}
public Double getEbalance() {
return ebalance.get();
}
public Double getEtotalpaid() {
return etotalpaid.get();
}
}
Here is code for my method that i call to fetch data from database..
public void attendence() throws SQLException{
employeelist = FXCollections.observableArrayList();
ename.setCellValueFactory(new PropertyValueFactory<Employee,String>("ename"));
ecnic.setCellValueFactory(new PropertyValueFactory<Employee,String>("ecnic"));
ebalance.setCellValueFactory(new PropertyValueFactory<Employee,Double>("ebalance"));
etotalpaid.setCellValueFactory(new PropertyValueFactory<Employee,Double>("etotalpaid"));
estatus.setCellValueFactory(new PropertyValueFactory<Employee,String>("estatus"));
estatus.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), attendenceoptions));
estatus.setOnEditCommit(
new EventHandler<CellEditEvent<Employee, String>>() {
#Override
public void handle(CellEditEvent<Employee, String> t) {
((Employee) t.getTableView().getItems().get(t.getTablePosition().getRow())).setEstatus(t.getNewValue());
};
});
estatus.setEditable(true);
stmt = conn.createStatement();
sql = "select * from employe";
rs = stmt.executeQuery(sql);
while(rs.next()){
employeelist.add(new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getDouble(5),rs.getDouble(6),"Present"));
employeetable.setItems(employeelist);
}
stmt.close();
rs.close();
}
}
Added this in method to solve issue.
employeetable.setEditable(true);

Categories