Related
I created an app to set reminders. For that I use two fragments: one to show the list of reminders and another one to create and edit a specific reminder.
When I edit the reminder, I have issues showing the already saved data from the SQLite Database (saving seems to work fine). I managed to show the title of the reminder by sending it from the list of reminders using arguments. However, I think it would make more sense to directly access the database from the edit fragment. I already tried different methods, but I think I am not accessing the ReminderProvider class correctly. I tried to create a method getTitel in the ReminderProvider classe which is used to handle the database, but I would then need to create an instance of the class and this is where I get lost since I don't instantiate it correctly (I get an NPE).
I would also like to access the db to show the date and time that have been saved before (I haven't been able to solve that with the arguments yet).
I have the same issue with the notification: I get a notification at the indicated time, but the notification does not show the title of the reminder. I can then access the reminder into the edit fragment, but then also I don't see the already saved data - another reason why I would like to load it directly from the database.
I have searched a lot here but didn't not find the answer (or couldn't transfer it to my case). I am still a beginner so I would appreciate any help. Thanks! (And sorry if this is a really stupid question...)
My code for the classes ReminderEditFragment and ReminderProvider is below (I also have the following classes: ReminderListFragment to show all reminders, ReminderListActivity to handle the ListFragment, ReminderEditActivity, ReminderManager, OnAlarmReceiver, OnBootReceiver, ReminderService, als well as fragments for the date- and timepicker)
ReminderEditFragment:
public class ReminderEditFragment extends Fragment implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:mm";
private Calendar mCalendar;
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateButtons();
}
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hour);
mCalendar.set(Calendar.MINUTE, minute);
updateButtons();
}
private void updateButtons() {
//Text des TimeButtons setzen
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String timeForButton = null;
timeForButton = timeFormat.format(mCalendar.getTime());
mTimeButton.setText(timeForButton);
//Text des DateButtons setzen
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = null;
dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
public static final String DEFAULT_EDIT_FRAGMENT_TAG = "editFragmentTag";
private EditText mReminderTitle;
private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private Button mDeleteButton;
private long mRowID;
private TextView mTextOldDate;
private TextView mOldDate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
if (arguments != null) {
mRowID = arguments.getLong(ReminderProvider.COLUMN_ID);
}
if (savedInstanceState != null && savedInstanceState.containsKey(CALENDAR)) {
mCalendar = (Calendar) savedInstanceState.getSerializable(CALENDAR);
} else{
mCalendar = Calendar.getInstance();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.reminder_edit, container, false);
mReminderTitle = v.findViewById(R.id.editText_reminder);
mDateButton = v.findViewById(R.id.button_reminder_date);
mTimeButton = v.findViewById(R.id.button_reminder_time);
if (mRowID != 0) {
Bundle arguments = getArguments();
String reminderTitle = arguments.getString(ReminderProvider.COLUMN_TITLE);
//I have also tried different versions of the following, but here I get the NPE
//Cursor c = (Cursor) new ReminderProvider().getTitle(mRowID);
//String reminderTitle = new ReminderProvider().getTitle(mRowID);
mReminderTitle.setText(reminderTitle);
}
mConfirmButton = v.findViewById(R.id.button_confirm);
mDeleteButton = v.findViewById(R.id.button_delete);
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePicker();
}
});
mTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
showTimePicker();
}
});
mConfirmButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View view) {
ContentValues values = new ContentValues();
values.put(ReminderProvider.COLUMN_ID, mRowID);
values.put(ReminderProvider.COLUMN_TITLE, mReminderTitle.getText().toString());
values.put(ReminderProvider.COLUMN_DATE_TIME, mCalendar.getTimeInMillis());
if (mRowID == 0) {
Uri itemUri = getActivity().getContentResolver().insert(ReminderProvider.CONTENT_URI, values);
mRowID = ContentUris.parseId(itemUri);
} else {
int count = getActivity().getContentResolver().update(ContentUris.withAppendedId(ReminderProvider.CONTENT_URI, mRowID),
values, null, null);
if (count != 1)
throw new IllegalStateException(mRowID + " konnte nicht aktualisiert werden.");
}
Toast.makeText(getActivity(), getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
getActivity().finish();
new ReminderManager(getActivity()).setReminder(mRowID, mCalendar);
}
});
mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRowID != 0) {
getActivity().getContentResolver().delete(ContentUris.withAppendedId(ReminderProvider.CONTENT_URI, mRowID), null, null);
Toast.makeText(getActivity(), getString(R.string.task_deleted_message), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
});
return v;
}
//Dialogkonstanten
static final String YEAR = "year";
static final String MONTH = "month";
static final String DAY = "day";
static final String HOUR = "hour";
static final String MINS = "mins";
static final String CALENDAR = "calendar";
private void showDatePicker() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
DialogFragment newFragment = new DatePickerDialogFragment();
Bundle args = new Bundle();
args.putInt(YEAR, mCalendar.get(Calendar.YEAR));
args.putInt(MONTH, mCalendar.get(Calendar.MONTH));
args.putInt(DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
newFragment.setArguments(args);
newFragment.show(ft, "datePicker");
}
private void showTimePicker() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
DialogFragment newFragment = new TimePickerDialogFragment();
Bundle args = new Bundle();
args.putInt(HOUR, mCalendar.get(Calendar.HOUR_OF_DAY));
args.putInt(MINS, mCalendar.get(Calendar.MINUTE));
newFragment.setArguments(args);
newFragment.show(ft, "timePicker");
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Calendar-Instanz speichern, falls Aenderungen vorgenommen wurden
outState.putSerializable(CALENDAR, mCalendar);
}
}
ReminderProvider:
public class ReminderProvider extends ContentProvider {
//ContentProvider URI und Quelle
public static String AUTHORITY = "com.example.mareike.remindme2.ReminderProvider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/reminder");
//Fuer Begriffe oder Suche nach Definitionen verwendete MIME Typen
public static final String REMINDERS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.com.example.mareike.remindme2.reminder";
public static final String REMINDER_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.com.example.mareike.remindme2.reminder";
//Datenbank Konstanten
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "reminder";
//Datenbanken Spalten
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATE_TIME = "reminder_date_time";
public static final String COLUMN_TITLE = "title";
//SQL Anweisung zusammensetzen
private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE +
" (" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE +
" text not null, " + COLUMN_DATE_TIME + " integer not null);";
//UriMatcher-Zeug
private static final int LIST_REMINDER = 0;
private static final int ITEM_REMINDER = 1;
private static final UriMatcher sURIMatcher = buildUriMatcher();
private SQLiteDatabase mDb;
//Erstellt ein UriMatcher-Objekt fuer Suchvorschlaege und Kurzabfragen
private static UriMatcher buildUriMatcher() {
UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(AUTHORITY, "reminder", LIST_REMINDER);
matcher.addURI(AUTHORITY, "reminder/#", ITEM_REMINDER);
return matcher;
}
#Override
public boolean onCreate() {
mDb = new DatabaseHelper(getContext()).getWritableDatabase();
return true;
}
#Override
public Cursor query(Uri uri, String[] ignored1, String ignored2, String[] ignored3, String ignored4) {
String[] projection = new String[]{ReminderProvider.COLUMN_ID, ReminderProvider.COLUMN_TITLE, ReminderProvider.COLUMN_DATE_TIME};
//UriMatcher verwenden, um den Abfragetyp festzustellen und die Datenbankanfrage entsprechend zu formatieren
Cursor c;
switch(sURIMatcher.match(uri)) {
case LIST_REMINDER:
c = mDb.query(ReminderProvider.DATABASE_TABLE, projection, null, null, null, null, null);
break;
case ITEM_REMINDER:
c = mDb.query(ReminderProvider.DATABASE_TABLE, projection, ReminderProvider.COLUMN_ID + "=?", new String[]{Long.toString(ContentUris.parseId(uri))},
null, null, null, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
}
break;
default:
throw new IllegalArgumentException("Unbekannte URI: " + uri);
}
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
#Override
public Uri insert (Uri uri, ContentValues values) {
values.remove(ReminderProvider.COLUMN_ID);
long id = mDb.insertOrThrow(ReminderProvider.DATABASE_TABLE, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
}
#Override
public int delete(Uri uri, String ignored1, String[] ignored2) {
int count = mDb.delete(ReminderProvider.DATABASE_TABLE, ReminderProvider.COLUMN_ID + "=?", new String[]{Long.toString(ContentUris.parseId(uri))});
if (count > 0)
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public int update(Uri uri, ContentValues values, String ignored1, String[] ignored2) {
int count = mDb.update(ReminderProvider.DATABASE_TABLE, values, COLUMN_ID + "=?", new String[]{Long.toString(ContentUris.parseId(uri))});
if (count > 0)
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
//Methode zur Abfrage der unterstuetzten Typen. Sie wird auch in der Methode query() genutzt, um den Typ der empfangenen Uri festzustellen
#Override
public String getType(Uri uri) {
switch (sURIMatcher.match(uri)) {
case LIST_REMINDER:
return REMINDERS_MIME_TYPE;
case ITEM_REMINDER:
return REMINDER_MIME_TYPE;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
//I also tried the following method(s) to be accessed from ReminderEditFragment
//Methode, um mit ID Titel abzufragen
//public Cursor fetchTitle (int id) {
// return mDb.rawQuery("SELECT title FROM data WHERE _id = " +id, null);
//}
public String getTitle(long id) {
String stringTitle = "kein Titel vorhanden";
int intId = (int)id;
Cursor cursor = mDb.rawQuery ("SELECT title FROM data WHERE _id = " +id, null);
if (cursor.moveToFirst()) {
do {
stringTitle = cursor.getString(cursor.getColumnIndex("title"));
}
while(cursor.moveToNext());
}
cursor.close();
return stringTitle;
}
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
throw new UnsupportedOperationException();
}
}
}
I managed to to solve the issue not by using a constructur, but by adding query method for each of the three fields using the content_uri to the ReminderEditFragment class:
public String savedDate (long id) {
//Abfrage
String[] projection = {
ReminderProvider.COLUMN_ID,
ReminderProvider.COLUMN_TITLE,
ReminderProvider.COLUMN_DATE_TIME
};
Uri singleUri = ContentUris.withAppendedId(ReminderProvider.CONTENT_URI, mRowID);
Cursor cursor = getActivity().getContentResolver().query(
singleUri,
projection,
null,
null,
null);
cursor.moveToFirst();
//Date und Time setzen
String dateS = cursor.getString(2);
long dateJavaTimestamp = Long.parseLong(dateS);
Date date = new Date(dateJavaTimestamp);
String savedDate = new SimpleDateFormat(DATE_FORMAT).format(date);
cursor.close();
return savedDate;
}
public String savedTime (long id) {
//Abfrage
String[] projection = {
ReminderProvider.COLUMN_ID,
ReminderProvider.COLUMN_TITLE,
ReminderProvider.COLUMN_DATE_TIME
};
Uri singleUri = ContentUris.withAppendedId(ReminderProvider.CONTENT_URI, mRowID);
Cursor cursor = getActivity().getContentResolver().query(
singleUri,
projection,
null,
null,
null);
cursor.moveToFirst();
//Date und Time setzen
String dateS = cursor.getString(2);
long dateJavaTimestamp = Long.parseLong(dateS);
Date date = new Date(dateJavaTimestamp);
String savedTime = new SimpleDateFormat(TIME_FORMAT).format(date);
cursor.close();
return savedTime;
}
Maybe this helps someone with a similar issue.
Could someone help me? my records are not updating.
I guess the edittext stay the same but not too sure.
How to change the view values that is being put in the edittext to change to the values in updating edittexts.
Would appreciate some help with this
Thank you.
DatabaseManager
public Cursor selectRow(String ID) {
String query = "Select * from " + TABLE_NAME + " where studentID = " + ID;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public boolean updateData(String id, String fn, String ln, String ge, String cs, String a, String loc) {
ContentValues contentValues = new ContentValues();
contentValues.put("studentID", id);
contentValues.put("first_name", fn);
contentValues.put("last_name", ln);
contentValues.put("gender", ge);
contentValues.put("course_study", cs);
contentValues.put("age", a);
contentValues.put("location", loc);
db.update(TABLE_NAME, contentValues, "studentID = ?", new String[]{id});
return true;
}
The above is parts of my database that I use in this activity.
activity main.java
private void UpdateData() {
u.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.VISIBLE);
again.setVisibility(View.VISIBLE);
Cursor res = mydManager.selectRow(text);
if (res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(0));
String nme = res.getString(1);
String lnme = res.getString(2);
String gen = res.getString(3);
String corse = res.getString(4);
String ag = Integer.toString(res.getInt(5));
String lo = res.getString(6);
studid.setText(id);
fname.setText(nme);
lname.setText(lnme);
gender.setText(gen);
course.setText(corse);
age.setText(ag);
loc.setText(lo);
}
}
}
);
}
public void UpdateData1() {
again.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.GONE);
String id = studid.getText().toString();
String nme = fname.getText().toString();
String lnme = lname.getText().toString();
String gen = gender.getText().toString();
String corse = course.getText().toString();
String ag = age.getText().toString();
String lo = loc.getText().toString();
boolean isUpdated = mydManager.updateData(id, nme , lnme, gen, corse ,ag , lo);
if (isUpdated == true)
Toast.makeText(Main4Activity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(Main4Activity.this, "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
I tried having a button to set the data but it still stays the same.
Sorry din't read the code, take the sample if it helps
Just the logic..
public long updateNote(NoteModel noteModel) {
if (LOG_DEBUG) UtilLogger.showLogUpdate(TAG, noteModel, noteModel.getRow_pos());
long updatedRow = 0;
try {
ContentValues contentValues = new ContentValues();
contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());
updatedRow = mSqLiteDatabase.updateWithOnConflict(
DBSchema.DB_TABLE_NAME,
contentValues,
DBSchema.DB_ROW_ID + " =?", new String[]{String.valueOf(noteModel.get_id())}, mSqLiteDatabase.CONFLICT_REPLACE);
return updatedRow;
} catch (SQLException e) {
e.printStackTrace();
}
return updatedRow;
}
then take the cursor
public Cursor getCursorForAlarmScheduled(String passAlarmScheduledStatus) {
if (LOG_DEBUG)
Log.w(TAG, " pick all record with alarmScheduled 1 : " + passAlarmScheduledStatus);
return mSqLiteDatabase.rawQuery(DBSchema.DB_SELECT_ALL +
" WHERE " + DBSchema.DB_IS_ALARM_SCHEDULED + " = " + passAlarmScheduledStatus, null);
}
and then extract
//common operation for all,
public static List<NoteModel> extractCommonData(Cursor cursor, List<NoteModel> noteModelList) {
noteModelList = new ArrayList<>();
if (LOG_DEBUG) Log.i(TAG, "inside extractCommonData()");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
NoteModel noteModel = new NoteModel();
noteModel.set_id(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_ROW_ID)));
noteModel.setTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_TITLE)));
noteModel.setImgUriPath(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IMAGE_PATH)));
noteModel.setSub_text(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SUB_TEXT)));
noteModel.setCreateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_CREATE_DATE)));
noteModel.setUpdateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_UPDATE_DATE)));
noteModel.setScheduleTimeLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_LONG)));
noteModel.setScheduledWhenLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_WHEN)));
noteModel.setScheduledTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TITLE)));
noteModel.setIsAlarmScheduled(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ALARM_SCHEDULED)));
noteModel.setIsTaskDone(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_TASK_DONE)));
noteModel.setIsArchived(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ARCHIVED)));
noteModelList.add(noteModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return noteModelList;
}
Again, I din't read,just copied from my old samples
Please do find the needful, cheers
so I've been trying to make a sqlite database in Android Studio with pre-existing data. I'm also trying to display that data to the user, although every time I launch the application it crashes when I search for the items in the database, so I am not sure if I am creating the database correctly. Anything helps, and many Thanks.
here is my database helper
public class MyDBHandler {
myDbHelper myhelper;
public MyDBHandler(Context context)
{
myhelper = new myDbHelper(context);
}
public void addBear(Bears bear)
{
SQLiteDatabase dbb = myhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(myhelper.COLUMN_ID, bear.getID());
values.put(myhelper.COLUMN_BEARNAME, bear.getbearname());
values.put(myhelper.COLUMN_STUFFING, bear.getstuffing());
values.put(myhelper.COLUMN_BEARHEALTH, bear.getbearhealth());
values.put(myhelper.COLUMN_HEALTHCOST, bear.gethpcost());
values.put(myhelper.COLUMN_HEALTHCOUNT, bear.gethpcount());
values.put(myhelper.COLUMN_BEARATTACK, bear.getbearattack());
dbb.insert(myDbHelper.TABLE_BEARS, null , values);
}
public Bears findBear(int bearID)
{
SQLiteDatabase db = myhelper.getWritableDatabase();
Bears bear = new Bears();
String[] columns =
{myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING,
myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST,
myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK,};
String query = myDbHelper.COLUMN_ID + " = ?";
String[] selections = {String.valueOf(bearID)};
Cursor cursor =
db.query(myDbHelper.TABLE_BEARS,columns,query,
selections,null,null,null,null);
if(null != cursor) {
bear.setID(Integer.parseInt(cursor.getString(0)));
bear.setbearname(cursor.getString(1));
bear.setstuffing(Integer.parseInt(cursor.getString(2)));
bear.setbearhealth(Integer.parseInt(cursor.getString(3)));
bear.sethpcost(Integer.parseInt(cursor.getString(4)));
bear.sethpcount(Integer.parseInt(cursor.getString(5)));
bear.setbearattack(Integer.parseInt(cursor.getString(6)));
}
db.close();
return bear;
}
static class myDbHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME = "bearDB.db"; // Database
private static final String TABLE_BEARS = "bears"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String COLUMN_ID="_id"; // Column I (Primary Key)
public static final String COLUMN_BEARNAME = "bearname";
public static final String COLUMN_STUFFING = "stuffing";
public static final String COLUMN_BEARHEALTH = "bearhealth";
public static final String COLUMN_HEALTHCOST = "healthcost";
public static final String COLUMN_HEALTHCOUNT = "healthcount";
public static final String COLUMN_BEARATTACK = "bearattack"; // Column III
String CREATE_BEARS_TABLE = "CREATE TABLE " +
TABLE_BEARS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_BEARNAME + " TEXT," +
COLUMN_STUFFING + " INTEGER," +
COLUMN_BEARHEALTH + " INTEGER," +
COLUMN_HEALTHCOST + " INTEGER, " +
COLUMN_HEALTHCOUNT + " INTEGER, "+
COLUMN_BEARATTACK + " INTEGER" +
")";
private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_BEARS;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_BEARS_TABLE);
ContentValues beary = new ContentValues();
beary.put(COLUMN_ID, 1 );
beary.put(COLUMN_BEARNAME, "Beary");
beary.put(COLUMN_STUFFING, 5);
beary.put(COLUMN_BEARHEALTH, 10);
beary.put(COLUMN_HEALTHCOST, 1);
beary.put(COLUMN_HEALTHCOUNT, 0);
beary.put(COLUMN_BEARATTACK,4);
db.insert(TABLE_BEARS, null, beary);
ContentValues honey = new ContentValues();
honey.put(COLUMN_ID, 2 );
honey.put(COLUMN_BEARNAME, "Honey");
honey.put(COLUMN_STUFFING, 5);
honey.put(COLUMN_BEARHEALTH, 8);
honey.put(COLUMN_HEALTHCOST, 1);
honey.put(COLUMN_HEALTHCOUNT, 0);
honey.put(COLUMN_BEARATTACK, 3);
db.insert(TABLE_BEARS, null, honey);
ContentValues baobao = new ContentValues();
baobao.put(COLUMN_ID, 3 );
baobao.put(COLUMN_BEARNAME, "BaoBao");
baobao.put(COLUMN_STUFFING, 5);
baobao.put(COLUMN_BEARHEALTH,11);
baobao.put(COLUMN_HEALTHCOST, 1);
baobao.put(COLUMN_HEALTHCOUNT, 0);
baobao.put(COLUMN_BEARATTACK, 3);
db.insert(TABLE_BEARS, null, baobao);
} catch (Exception e) {
// do nothing
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
// do nothing
}
}
}
and here is my activity page,
public class BearSelectActivity extends AppCompatActivity {
TextView idBear, healthBear, hpcost, attackBear, abilityBear, stuffingBear;
public int hpcount;
EditText nameBear;
public int beartype = 1;
public String Fighter = "Fighter";
public String Healer = "Healer";
public String Tank = "Tank";
MyDBHandler helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bear_select);
helper = new MyDBHandler(this);
Button changeBear = (Button)findViewById(R.id.bearChange);
idBear = (TextView) findViewById(R.id.bearID);
nameBear = (EditText) findViewById(R.id.bearName);
stuffingBear = (TextView) findViewById(R.id.bearStuffing);
healthBear = (TextView) findViewById(R.id.bearHealth);
hpcost = (TextView)findViewById(R.id.HPCOST);
Button plushp = (Button)findViewById(R.id.plusbearhp);
Button minushp = (Button)findViewById(R.id.minusbearhp);
attackBear = (TextView) findViewById(R.id.bearAttack);
abilityBear = (TextView) findViewById(R.id.bearAbility);
abilityBear.setText(Fighter);
Bears bear = helper.findBear(beartype);
idBear.setText(String.valueOf(bear.getID()));
nameBear.setText(String.valueOf(bear.getbearname()));
healthBear.setText(String.valueOf(bear.getbearhealth()));
attackBear.setText(String.valueOf(bear.getbearattack()));
stuffingBear.setText(String.valueOf(bear.getstuffing()));
}
public void changeBearClick (View view){
//MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
ImageView image = (ImageView) findViewById(R.id.bearimage);
//Bears bear;
beartype++;
beartype = bearmod(beartype, 3);
if(beartype == 2) {
image.setImageResource(R.drawable.bear2);
abilityBear.setText(Healer);
}
else if(beartype == 3){
image.setImageResource(R.drawable.bear3);
abilityBear.setText(Tank);
}
else if(beartype == 1){
image.setImageResource(R.drawable.bear1);
abilityBear.setText(Fighter);
}
lookupBear(view);
}
public int bearmod(int a, int b){
if (a < b && a > 0){
return a;
}
else if(a == b){
return a;
}
else if(a == 0 || a > b){
a = 1;
}
return a;
}
public void lookupBear (View view) {
Bears bear = helper.findBear(beartype);
if(bear == null) {
if (beartype == 1) {
bear = new Bears(1, "Beary", 5, 10, 1, 0, 4);
helper.addBear(bear);
} else if (beartype == 2) {
bear = new Bears(2, "Honey", 5, 8, 1, 0, 3);
helper.addBear(bear);
} else if (beartype == 3) {
bear = new Bears(3, "Baobao", 5, 11, 1, 0, 2);
helper.addBear(bear);
}
}
if(bear != null) {
idBear.setText(String.valueOf(bear.getID()));
nameBear.setText(String.valueOf(bear.getbearname()));
stuffingBear.setText(String.valueOf(bear.getstuffing()));
healthBear.setText(String.valueOf(bear.getbearhealth()));
hpcost.setText(String.valueOf(bear.gethpcost()));
hpcount = bear.gethpcount();
attackBear.setText(String.valueOf(bear.getbearattack()));
}
}
}
You have a number of issues that I have spotted.
The following line, defining the columns has an extra trailing comma so :-
String[] columns =
{myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING,
myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST,
myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK,};
Should be :-
String[] columns =
{myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING,
myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST,
myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK};
When a Cursor is returned it is positioned at before the first row (-1). To access data from the cursor you need to move to a row within the Cursor. You are not doing this.
Additionally a returned Cursor will not be null. So checking for a null Cursor is useless.
Furthermore, using hard coded offsets may well be problematic and inflexible. A Cursor has a getColumnIndex method that will return the offset according to the column name.
A Cursor also has methods other than getString for directly extracting data as other types e.g. getInt, getLong, getBlob ...... Cursor
I'd suggest changing :-
if(null != cursor) {
bear.setID(Integer.parseInt(cursor.getString(0)));
bear.setbearname(cursor.getString(1));
bear.setstuffing(Integer.parseInt(cursor.getString(2)));
bear.setbearhealth(Integer.parseInt(cursor.getString(3)));
bear.sethpcost(Integer.parseInt(cursor.getString(4)));
bear.sethpcount(Integer.parseInt(cursor.getString(5)));
bear.setbearattack(Integer.parseInt(cursor.getString(6)));
}
db.close();
return bear;
to be :-
if(cursor.moveToFirst) {
bear.setID(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_ID)));
bear.setbearname(cursor.getString(cursor.getColumnIndex(myDbHelper.COLUMN_BEARNAME)));
bear.setstuffing(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_STUFFING)));
bear.setbearhealth(cursor.getInt(cursor.getColumnIndex(myhelper.COLUMN_BEARHEALTH)));
bear.sethpcost(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_HEALTHCOST)));
bear.sethpcount(cursor.getInt(cursor.getColumnIndex(myhelper.COLUMN_HEALTHCOUNT))));
bear.setbearattack(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_BEARATTACK))));
}
cursor.close(); //<<< ADDED SHOULD ALWAYS CLOSE CURSORS WHEN DONE WITH THEM
db.close();
return bear;
so I am not sure if I am creating the database correctly.
The class here at :- Are there any methods that assist with resolving common SQLite issues?
, that you can add, includes some methods that can assist with knowing what the database contains.
All you have to do is add the class by copying and pasting the code (from the second answer) and to then use add the following after the line helper = new MyDBHandler(this); :-
CommonSQLiteUtilities.logDatabaseInfo(helper.getWitableDatabase());
When you run the App, check the Log and it will display DatabaseInformation in the log.
Note the code above is in-principle code and has not been tested, so it may contain simple errors.
I have some sort of an issue and I'd really appreciate it, if
you could help me.
Problem: I want to take Data from a SQLite Database and display it in
a Listview or a Gridview, either way.
I watched a tutorial and tried to follow the rules and the idea behind it,
with copying the source code and changing the code piece by piece for my
own purpose. Strangely, the code I'm having issues with works in the tutorial
code, and also in another class in my project, but refuses to work in the
recent file..
So, this is the oncreate of the working file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_list);
mem_op = new Member_Operations(this);
mem_op.open();
List values = mem_op.getAllMembers();
et = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
gv = (GridView) findViewById(R.id.gv);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
gv.setAdapter(adapter);
} // oncreate
and this is the related super-class:
public class Member_Operations {
public DBHelper_Members db_helper;
private SQLiteDatabase database;
private String [] MEMBER_TABLE_COLUMNS = { db_helper.MEMBERS_COLUMN_ID,db_helper.MEMBERS_COLUMN_NAME,db_helper.MEMBERS_COLUMN_PERMISSION};
public Member_Operations(Context context)
{
db_helper = new DBHelper_Members(context);
}
public void open() throws SQLException{
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Member addMember(String name, String permission){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.MEMBERS_COLUMN_NAME, name);
contentValues.put(db_helper.MEMBERS_COLUMN_PERMISSION,permission);
long MemID = database.insert(db_helper.MEMBER_TABLE, null, contentValues);
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,db_helper.MEMBERS_COLUMN_ID + " = " +
+ MemID, null,null,null,null);
cursor.moveToFirst();
Member newComment = parseMember(cursor);
cursor.close();
return newComment;
}
public void deleteMember(Member mem){
long id = mem.getID();
SQLiteDatabase db = db_helper.getWritableDatabase();
db.delete(db_helper.MEMBER_TABLE, db_helper.MEMBERS_COLUMN_ID + " = " + id,
null);
}
public List getAllMembers(){
List members = new ArrayList();
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,null,null,null,null,null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Member member = parseMember(cursor);
members.add(member);
cursor.moveToNext();
}
cursor.close();
return members;
}
private Member parseMember(Cursor cursor){
Member member = new Member();
member.setID(cursor.getInt(0));
member.setName(cursor.getString(1));
member.setPermission(cursor.getString(2));
return member;
}
This is the one refusing to work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kal_op = new Kalender_Operations(this);
kal_op.open();
List values = kal_op.getAllDays();
ArrayAdapter<Date> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
// here i tried, unlike the first one, to add the Type(Date).
// But either way it doesn't work.
GridView gv = (GridView) findViewById(R.id.gv);
ListActivity la = new ListActivity();
la.setListAdapter(adapter);
}
And its super-class:
public class Kalender_Operations {
SQLiteDatabase database;
DBHelper db_helper;
String [] DATES_TABLE_COLUMNS = { db_helper.JANUARY_COLUMN_ID,
db_helper.JANUARY_COLUMN_DAY,db_helper.JANUARY_COLUMN_EVENT};
public Kalender_Operations(Context context)
{
db_helper = new DBHelper(context);
}
public void open() throws SQLException {
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Date addDate (String day, String event){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.JANUARY_COLUMN_DAY, day);
contentValues.put(db_helper.JANUARY_COLUMN_EVENT, event);
long DateID = database.insert(db_helper.JANUARY_TABLE,null,contentValues);
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, db_helper.JANUARY_COLUMN_ID
+ " = " + DateID,null,null,null,null);
cursor.moveToFirst();
Date newComment = parseDate(cursor);
cursor.close();
return newComment;
}
public void showDetails(int i, Context context){
Intent intent = new Intent(context, Test_Intent.class);
intent.putExtra("Position", i);
intent.putExtra("Month", db_helper.JANUARY_TABLE);
intent.putExtra("Year", db_helper.JANUARY_YEAR);
context.startActivity(intent);
}
public List getAllDays(){
List Dates = new ArrayList();
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Date date = parseDate(cursor);
Dates.add(date);
cursor.moveToNext();
}
cursor.close();
return Dates;
}
public Date parseDate(Cursor cursor){
Date date = new Date();
date.setID(cursor.getInt(0));
date.setDay(cursor.getString(1));
date.setEvent(cursor.getString(2));
return date;
}
}
Please help me. I really want to continue learning, but I spent a lot of time now trying to figure out why one works, the other one doesn't..
Hey I'm trying to insert data in the SQLite database, but everytime I try to insert the logcat shows the error. THe error ir shown on a service that gets the calllog data and insert in the DB.
Error:
02-15 17:07:51.658: ERROR/AndroidRuntime(25392): java.lang.IllegalStateException: database not open
And the error is in this line of the Service class:
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
Here is the service:
public class TheService extends Service {
private static final String TAG = "TheService";
private static final String LOG_TAG = "TheService";
private Handler handler = new Handler();
private SQLiteDatabase db;
class TheContentObserver extends ContentObserver {
public TheContentObserver(Handler h) {
super(h);
OpenHelper helper = new OpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
searchInsert();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
db = DataHandlerDB.createDB(this);
registerContentObservers();
}
#Override
public void onDestroy(){
db.close();
}
#Override
public void onStart(Intent intent, int startid) {
}
private void searchInsert() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
int numberColumnId = cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int durationId = cursor
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int contactNameId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
int callTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.TYPE);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
SimpleDateFormat dateFormat = new SimpleDateFormat("M/d/yyyy");
Date date = new Date();
cursor.moveToFirst();
String contactNumber = cursor.getString(numberColumnId);
String contactName = (null == cursor.getString(contactNameId) ? ""
: cursor.getString(contactNameId));
String duration = cursor.getString(durationId);
String numType = cursor.getString(numTypeId);
String callType = cursor.getString(callTypeId);
ContentValues values = new ContentValues();
values.put("contact_id", 1);
values.put("contact_name", contactName);
values.put("number_type", numType);
values.put("contact_number", contactNumber);
values.put("duration", duration);
values.put("date", dateFormat.format(date));
values.put("current_time", currTime);
values.put("cont", 1);
values.put("type", callType);
if (!db.isOpen()) {
getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
cursor.close();
}
public void registerContentObservers() {
this.getApplicationContext()
.getContentResolver()
.registerContentObserver(
android.provider.CallLog.Calls.CONTENT_URI, true,
new TheContentObserver(handler));
}
}
And here is the DataHandlerDB Class:
public class DataHandlerDB {
private static final String DATABASE_NAME = "mydb.db";
private static final int DATABASE_VERSION = 1;
protected static final String TABLE_NAME = "table1";
protected static final String TABLE_NAME_2 = "table2";
protected String TAG = "DataHandlerDB";
//create the DB
public static SQLiteDatabase createDB(Context ctx) {
OpenHelper helper = new OpenHelper(ctx);
SQLiteDatabase db = helper.getWritableDatabase();
helper.onOpen(db);
db.close();
return db;
}
public static class OpenHelper extends SQLiteOpenHelper {
private final Context mContext;
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String[] sql = mContext.getString(R.string.ApplicationDatabase_OnCreate).split("\n");
db.beginTransaction();
try{
execMultipleSQL(db, sql);
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e("Error creating tables and debug data", e.toString());
throw e;
} finally {
db.endTransaction();
}
}
private void execMultipleSQL(SQLiteDatabase db, String[] sql) {
for(String s : sql){
if(s.trim().length() > 0){
db.execSQL(s);
}
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/*Log.w("Application Database",
"Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);*/
}
#Override
public void onOpen(SQLiteDatabase db){
super.onOpen(db);
}
}
}
Don't you want this code
if (!db.isOpen()) {
getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
to be:
if (!db.isOpen()) {
db = getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
?
Also, in the function
public TheContentObserver(Handler h) {
super(h);
OpenHelper helper = new OpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
}
helper and db are local variables, not class members. This means that the database that you open here is not used for anything, anywhere.