In my code, the user supposed to add details of a product including name, image, category and other details. But after entering the data and saving it, it cannot view the data that they input. Instead it shows: unable to convert BLOB to String.
My coding for adding data.
items Item= new items();
db.getWritableDatabase();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte imageInByte[] = stream.toByteArray();
Bitmap bMap= BitmapFactory.decodeByteArray(imageInByte, 0, imageInByte.length);
ivThumbnailPhoto.setImageBitmap(bMap);
Item.setName(name.getText().toString());
Item.setCategory(SpCate.getSelectedItem().toString());
Item.setDetails(details.getText().toString());
Item.setImage(imageInByte);
db.addItemSpinner(new items());
// Save the Data in Database
MyDb entry= new MyDb(SellingItem.this);
entry.getWritableDatabase();
entry.addItemSpinner(Item);
entry.close();
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
Log.d("name", Item.getName());
Log.d("category", Item.getCategory());
Log.d("detailsL", Item.getDetails());
Intent i=new Intent(SellingItem.this,SearchItem.class);
startActivity(i);
My Database to input data.
public void addItemSpinner(items i) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, i.name); // Contact Name
values.put(COLUMN_IMAGE, i.image); // Contact Phone
values.put(COLUMN_CATE, i.category); // Contact Name
values.put(COLUMN_DETAILS, i.details); // Contact Phone
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
logcat shows this.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.projectonline/com.example.projectonline.SearchItem}: android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string
This is my items code.
package com.example.projectonline;
import android.graphics.Bitmap;
public class items {
int id;
String name, category, details;
byte[] image;
public items(){
}
public items(int id, String name, String category, byte[]image, String details)
{
this.id=id;
this.name= name;
this.category=category;
this.image= image;
this.details=details;
}
public items(String name, String category, byte[]image, String details){
this.name = name;
this.category = category;
this.image = image;
this.details = details;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
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 getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Bitmap getBitmap() {
// TODO Auto-generated method stub
return null;
}
}
And this is what my DB looks like
public static final String TAG = "MyDb";
public static final String TABLE_NAME="PRODUCT";
public static final String COLUMN_ID="id";
public static final String COLUMN_NAME="name";
public static final String COLUMN_CATE="category";
public static final String COLUMN_IMAGE="image";
public static final String COLUMN_DETAILS="details";
private static final String DATABASE_NAME="Spinner";
private static final int DATABASE_VERSION= 1;
private static final String SQL_CREATE_ITEM = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_NAME + " TEXT NOT NULL, "
+ COLUMN_CATE + " TEXT NOT NULL, "
+ COLUMN_IMAGE + " BLOB, "
+ COLUMN_DETAILS + " TEXT NOT NULL "
+")";
Use the following code
java.sql.Blob ablob = rs.getBlob(1);
String str = new String(ablob.getBytes(1l, (int) ablob.length()));
or
Try this (a2 is BLOB col)
PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();
It may work even without BLOB, driver will transform types automatically:
ps1.setBytes(1, str.getBytes);
ps1.setString(1, str);
Besides if you work with text CLOB seems to be a more natural col type.
Related
I have an Android App (written in Java) which retrieves a JSON object from the backend, parses it, and displays the data in the app. Everything is working fine (meaning that every field is being displayed correctly) except for one field. All the fields being displayed correctly are String whereas the one field which is causing the error is a string array!
Sample Object being retried from backend:
{
"attendance_type": "2",
"guest": [
"Test Guest",
"Test Guest 2"
],
"member_id": "1770428",
"attendance_time": "2020-04-27 04:42:22",
"name": "HENRY HHH",
"last_name": "",
"email": "henry#mailinator.com",
"onesignal_playerid": "",
"user_image": "311591.png",
"dateOfBirth": "06/22/1997",
"employeeID": "543210",
"socialSecurityNumber": "0000"
}
As I said, all the fields are being retrieved correctly except the "guest field"
This is the class in which everything is Serialized:
package com.lu.scanner.ui.attendance.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class AttendanceDetails {
String date;
#SerializedName("attendance_type")
private String attendance_type;
#SerializedName("member_id")
private String member_id;
#SerializedName("attendance_date")
private String attendance_date;
#SerializedName("name")
private String name;
#SerializedName("email")
private String email;
#SerializedName("onesignal_playerid")
private String onesignal_playerid;
#SerializedName("user_image")
private String user_image;
#SerializedName("dateOfBirth")
private String dateOfBirth;
#SerializedName("employeeID")
private String employeeID;
#SerializedName("socialSecurityNumber")
private String socialSecurityNumber;
#SerializedName("attendance_time")
private String attendance_time;
#SerializedName("guest")
private String[] guest;
public AttendanceDetails(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAttendance_type() {
return attendance_type;
}
public void setAttendance_type(String attendance_type) {
this.attendance_type = attendance_type;
}
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
public String getAttendance_date() {
return attendance_date;
}
public void setAttendance_date(String attendance_date) {
this.attendance_date = attendance_date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOnesignal_playerid() {
return onesignal_playerid;
}
public void setOnesignal_playerid(String onesignal_playerid) {
this.onesignal_playerid = onesignal_playerid;
}
public String getUser_image() {
return user_image;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmployeeID() {
return employeeID;
}
public void setEmployeeID(String employeeID) {
this.employeeID = employeeID;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public String getAttendance_time() {
return attendance_time;
}
public void setAttendance_time(String attendance_time) {
this.attendance_time = attendance_time;
}
public String[] getGuest(){
return guest;
}
public void setGuest(String[] guest){
this.guest=guest;
}
}
This is the SQLLite database:
private static final String CREATE_TABLE_ATTENDANCE_DETAILS = "CREATE TABLE IF NOT EXISTS " + TABLE_ATTENDANCE_DETAILS +
"( date TEXT , " +
"attendance_type TEXT, " +
"member_id TEXT, " +
"attendance_date TEXT, " +
"name TEXT, " +
"email TEXT, " +
"onesignal_playerid TEXT, " +
"user_image TEXT, " +
"dateOfBirth TEXT, " +
"employeeID TEXT, " +
"socialSecurityNumber TEXT, " +
"attendance_time TEXT, " +
"guest TEXT); ";
And finally, there is where the data is being retrieved:
public List<AttendanceDetails> getAllAttendanceDetails() {
List<AttendanceDetails> attendanceDetailsList = new ArrayList<AttendanceDetails>();
String selectQuery = "SELECT * FROM " + TABLE_ATTENDANCE_DETAILS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
AttendanceDetails attendanceDetails = new AttendanceDetails();
attendanceDetails.setDate(cursor.getString(0));
attendanceDetails.setAttendance_type(cursor.getString(1));
attendanceDetails.setMember_id(cursor.getString(2));
attendanceDetails.setAttendance_date(cursor.getString(3));
attendanceDetails.setName(cursor.getString(4));
attendanceDetails.setEmail(cursor.getString(5));
attendanceDetails.setOnesignal_playerid(cursor.getString(6));
attendanceDetails.setUser_image(cursor.getString(7));
attendanceDetails.setDateOfBirth(cursor.getString(8));
attendanceDetails.setEmployeeID(cursor.getString(9));
attendanceDetails.setSocialSecurityNumber(cursor.getString(10));
attendanceDetails.setAttendance_time(cursor.getString(11));
attendanceDetails.setGuest(cursor.getString(12));
attendanceDetailsList.add(attendanceDetails);
} while (cursor.moveToNext());
}
return attendanceDetailsList;
}
Therefore, the main problem, I think, is that the TEXT type in the table creation is not compatible with the String array. Plus I think the cursor.String() function is not working for the "guest" string array properly. What can I do to make all of this code compatible with the "guest" field?
NOTE: Everything is working perfectly fine except for the guest field...
A Database stores rows of data, divided into columns. Each column is a skalar. SQLite only supports (basically) numbers and Text for columns. A List of Texts (or array from strings) doesn't fit in there. You are trying to assign a single String to an array.
You have two options:
Model guest as its own table and use foreign keys and the appropriate JOIN to fetch the data.
Encode the data yourself. If you don't want to query the array, but always retrieve the whole thing, this is the easier way:
Gson gson;
String guestSerialized = gson.toJson(attendanceDetails.getGuest);
// Insert data like this
// Retrieve:
attendanceDetails.setGuest(gson.fromJson(cursor.getString(12), String[].class))
That is, if you are using GSON for JSON (de)serialization. You can choose a different format or library.
Maybe you could give some name in the fields of "guest", something like:
"guest": [
{
"guest" : "Test Guest",
},
{
"guest" : "Test Guest 2"
},
],
Then, in order to read these values, you can do that:
JSONArray ja = (JSONArray) jo.get("guest");
Map address = ((Map)jo.get("guest"))
Iterator itr = ja.iterator();
Iterator<Map.Entry> itr1;
while (itr.hasNext()) {
itr1 = ((Map) itr.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
Where:
pair.getKey is the name of the key ("guest")
pair.getValue is the value of the key ("Test Guest")
The source code is here.
Sorry if I have made any mistakes. Please ask for clarifications! :)
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.
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.