I'm new to android programming. I'm still practicing and making this simple app.
I want to get 2 rows per refresh from SQLite Database and display on a listview.
But what I am getting now is the first 2 rows again and again.
My database already has data with 6 rows.
What I don't know is how to pass offset to the Database Operation and how to get the next 2 rows.
Thank you so much for your time. I hope someone can help me.
Pls see my code below:
DisplayItem.java
public class DisplayItem extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private String TAG = DisplayItem.class.getSimpleName();
private SwipeRefreshLayout swipeRefreshLayout;
private ListView list_view;
private SwipeAdapter adapter;
private List<Item> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_item);
list_view = (ListView) findViewById(R.id.lvDisplay);
itemList = new ArrayList<>();
adapter = new SwipeAdapter(this, itemList);
list_view.setAdapter(adapter);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
fetchItems();
}
});
}
#Override
public void onRefresh() {
fetchItems();
}
public void fetchItems() {
swipeRefreshLayout.setRefreshing(true);
DatabaseOperations db_op_sw = new DatabaseOperations(this);
SQLiteDatabase db = db_op_sw.getReadableDatabase();
Cursor display_cursor_swipe = db_op_sw.displaySwipeInfo(db);
String name;
int id, qty, price;
int offSet = 0;
if (display_cursor_swipe.moveToFirst()) {
do {
id = display_cursor_swipe.getInt(display_cursor_swipe.getColumnIndex(ItemContract.ItemEntry.ID));
name = display_cursor_swipe.getString(display_cursor_swipe.getColumnIndex(ItemContract.ItemEntry.NAME));
qty = display_cursor_swipe.getInt(display_cursor_swipe.getColumnIndex(ItemContract.ItemEntry.QTY));
price = display_cursor_swipe.getInt(display_cursor_swipe.getColumnIndex(ItemContract.ItemEntry.PRICE));
Item item = new Item(id, name, qty, price);
itemList.add(item);
offSet = offSet + id;
} while (display_cursor_swipe.moveToNext());
adapter.notifyDataSetChanged();
}
swipeRefreshLayout.setRefreshing(false);
}
}
DatabaseOperations.java
public class DatabaseOperations extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "item_info.db";
private static final String CREATE_QUERY = "create table " + ItemContract.ItemEntry.TABLE_NAME +
"(" + ItemContract.ItemEntry.ID + " text,"
+ ItemContract.ItemEntry.NAME + " text,"
+ ItemContract.ItemEntry.QTY + " integer,"
+ ItemContract.ItemEntry.PRICE + " integer);";
public DatabaseOperations(Context context) {
super(context, DB_NAME, null, DB_VERSION);
Log.d("Database Operations", "Database successfully created");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Table successfully created");
}
public Cursor displaySwipeInfo(SQLiteDatabase db) {
String[] projections = {ItemContract.ItemEntry.ID, ItemContract.ItemEntry.NAME,
ItemContract.ItemEntry.QTY, ItemContract.ItemEntry.PRICE};
Cursor display_cursor_swipe = db.query(ItemContract.ItemEntry.TABLE_NAME, projections, null, null, null, null, null, null, "2");
Log.d("Database Operations", "Viewed row");
return display_cursor_swipe;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
You are on the right track :)
So the 2 is the limit which is set on the query. You can also set offset,query in that place. You can keep a counter for refresh count and use it to create the offset.
Cursor display_cursor_swipe = db.query(ItemContract.ItemEntry.TABLE_NAME, projections, null, null, null, null, null, null, offset+",2"); //offset,limit
or
Cursor display_cursor_swipe = db.query(ItemContract.ItemEntry.TABLE_NAME, projections, null, null, null, null, null, null, "limit "+2+",offset "+offset);// limit 2 offset 3
or
you could resort to db.rawQuery(SQLSTATEMENT); // SQLSTATEMENT is select statement in string which has LIMIT,OFFSET set on it.
Related
I am a beginner at programming, I want to make a delete button on every items list on recyclerView. I got some references from stack overflow, and its work for the deleted item only at the activity (layout), but when i run the activity again the The selected item showed again.
I found some related articles on stackoverflow and make the method to delete from the SQLite. But my app crushed "unfortunetly app has stopped" every time I call the delete function.
I hope someone can help me to figure it out.
here is my databasehelper class
public class DatabaseHelperClass extends SQLiteOpenHelper {
Log cat Database
public static String log = "DatabaseHelper";
//Databse version
public static final int DATABASE_VERSION = 1;
//Database name
public static final String DATABSE_NAME = "dbPig";
//Tables Name
public static final String TABLE_PIGINFO = "tb_pigInfo";
//Common and PigInfo Column Names
public static final String KEY_ID = "id";
public static final String KEY_NAMA = "nama";
public static final String KEY_TANGGAL_PENDAFTARAN = "tanggal_pendaftaran";
//table create statement
//table pig Info
public static final String CREATE_TABLE_PIGINFO = "CREATE TABLE "
+ TABLE_PIGINFO + "(" + KEY_ID + " INTEGER," + KEY_NAMA
+ " TEXT," + KEY_TANGGAL_PENDAFTARAN
+ " TEXT" + ")";
public DatabaseHelperClass(Context context) {
super(context, DATABSE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//creating requaired table
db.execSQL(CREATE_TABLE_PIGINFO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PIGINFO);
// create new tables
onCreate(db);
}
public void insertdata(String nama, String tanggal_pendaftaran) {
System.out.print("Tersimpan" + TABLE_PIGINFO);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAMA, nama);
contentValues.put(KEY_TANGGAL_PENDAFTARAN, tanggal_pendaftaran);
db.insert(TABLE_PIGINFO, null, contentValues);
}
public List<PigInfoTable> getdata() {
List<PigInfoTable> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_PIGINFO + " ;", null);
StringBuffer stringBuffer = new StringBuffer();
PigInfoTable pigInfoTable = null;
while (cursor.moveToNext()) {
pigInfoTable = new PigInfoTable();
String nama = cursor.getString(cursor.getColumnIndexOrThrow("nama"));
String tanggal_pendaftaran = cursor.getString(cursor.getColumnIndexOrThrow("tanggal_pendaftaran"));
pigInfoTable.setNama(nama);
pigInfoTable.setTanggal_pendaftaran(tanggal_pendaftaran);
stringBuffer.append(pigInfoTable);
data.add(0, pigInfoTable);
}
for (PigInfoTable mo : data) {
Log.i("Hellomo", "" + mo.getNama());
}
return data;
}
public void delete(int position) {
SQLiteDatabase db = this.getWritableDatabase();
String table = TABLE_PIGINFO;
String whereClause = KEY_ID;
String [] whereArgs = new String[] {String.valueOf(position)};
db.delete (table, whereClause, whereArgs);
}
and here my adapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.Myholder> {
DatabaseHelperClass databaseHelper;
List <PigInfoTable> pigInfoTablesArrayList;
public RecycleAdapter(List <PigInfoTable> pigInfoTablesArrayList) {
this.pigInfoTablesArrayList = pigInfoTablesArrayList;
}
class Myholder extends RecyclerView.ViewHolder{
private TextView nama, tanggal_pendaftaran;
private Button delete;
public Myholder(View itemView) {
super(itemView);
nama = (TextView) itemView.findViewById(R.id.nama1);
tanggal_pendaftaran = (TextView) itemView.findViewById(R.id.tanggal1);
delete = (Button) itemView.findViewById(R.id.delete);
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_itempigview,null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, final int position) {
PigInfoTable pigInfoTable= pigInfoTablesArrayList.get(position);
holder.nama.setText(pigInfoTable.getNama());
holder.tanggal_pendaftaran.setText(pigInfoTable.getTanggal_pendaftaran());
holder.itemView.setClickable(true);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return pigInfoTablesArrayList.size();
}
I am trying some other solution but the same error occurred which's
null object references on
Position
error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
at com.example.newbreedy.RecycleAdapter$1.onClick(RecycleAdapter.java:66)
thank you
com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
because you have not initialized the reference of
DatabaseHelperClass databaseHelper;
So Add.
databaseHelper =new DatabaseHelperClass (context);
in your recycler adapter
In your code you are sending adapter position so in place of position send KEY_ID.
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyDataSetChanged();
First you have to initialize your DatabaseHelperClass in your adapter like this,
databaseHelper =new DatabaseHelperClass (context);
Than you need to call the delete function and inform the adapter about the removed item like this,
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());
I am trying to create a bill template by populating data stored in SQLite. I know there is a way to do this using ListView as well. The app crashes when I run this Activity.
public class Ticket_generator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ticket_table);
Context context;
context=this;
TableHelper datahelper= new TableHelper(context);
datahelper.insertData("Home foods","Veg Resturant","New Municipal Blog","abc compound","mumbai 400007","01/07/17","COUNTER","BILL NO.-123","Perticulars","Quantity","Rate","gst","06.56AM");
Cursor cr;
cr=datahelper.getInformation();
TextView tv;
tv=(TextView)findViewById(R.id._s1t1);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(16);
tv.setPadding(5, 5, 5, 5);
tv.setText(cr.getString(1));
}
}
This is the TableHelper.java
public class TableHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Ticketdb";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_TICKET = "tblticketdata";
public static final String CREATE_TABLE_TICKET = "CREATE TABLE IF NOT EXISTS " + TABLE_TICKET + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, s1t1 TEXT NULL,s1t2 TEXT NULL,s1t3 TEXT NULL,s1t4 TEXT NULL,s1t5 TEXT NULL,s2t1 TEXT NULL,s2t2 TEXT NULL,s2t3 TEXT NULL, s3t1 TEXT NULL,s3t2 TEXT NULL,s3t3 TEXT NULL,ft1 TEXT NULL,ft2 TEXT NULL)";
public static final String DELETE_TABLE_SERVICES = "DROP TABLE IF EXISTS " + TABLE_TICKET;
public TableHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TICKET);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DELETE_TABLE_SERVICES);
//Create tables again
onCreate(db);
}
public void insertData(String s1t1, String _s1t2, String _s1t3, String _s1t4, String _s1t5, String _s2t1, String _s2t2,
String _s2t3, String _s3t1, String _s3t2, String _s3t3, String _ft1, String _ft2) {
// Open the database for writing
SQLiteDatabase db = this.getWritableDatabase();
// Start the transaction.
db.beginTransaction();
ContentValues values;
try {
values = new ContentValues();
values.put("s1t1", s1t1);
values.put("s1t2", _s1t2);
values.put("s1t3", _s1t3);
values.put("s1t4", _s1t4);
values.put("s1t5", _s1t5);
values.put("s2t1", _s2t1);
values.put("s2t2", _s2t3);
values.put("s2t3", _s2t3);
values.put("s3t1", _s3t1);
values.put("s3t2", _s3t2);
values.put("s3t3", _s3t3);
values.put("ft1", _ft1);
values.put("ft2", _ft2);
// Insert Row
long i = db.insert(TABLE_TICKET, null, values);
Log.i("Insert", i + "");
// Insert into database successfully.
db.setTransactionSuccessful();
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}
public Cursor getInformation() {
SQLiteDatabase sq = this.getReadableDatabase();
String[] columns = {"s1t1", "s1t2", "s1t3", "s1t4", "s1t5", "s2t1", "s2t2", "s2t3", "s3t1", "s3t2", "s3t3", "ft1", "ft2"};
Cursor cr = sq.query(TABLE_TICKET, columns, null, null, null, null, null);
return cr;
}
}
You need to move your cursor for the first position, like this example:
public String getFirstResult(){
String firstResult;
TableHelper datahelper = new TableHelper(context);
Cursor cursor = datahelper.getInformation();
cursor.moveToFirst();
firstResult = cursor.getString(0);
return firstResult;
}
I am quite new Android Development and figured I should start by trying to create a simple ToDo List App using SQLite. I have all of the basic functionality in place: adding, updating, and deleting tasks. However, I am adding, updating, and deleting by the title of the task, rather than by the ID. This creates problems with duplicate tasks (e.g. tasks of the same name are deleted simultaneously). After much internet search, I still cannot find a way to do this. I would appreciate any help offered!
Here's my code:
public class TaskDbHelper extends SQLiteOpenHelper {
public TaskDbHelper(Context context) {
super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " ( " +
TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TaskContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL, " +
TaskContract.TaskEntry.COL_TASK_DATE + " DATE);";
sqLiteDatabase.execSQL(createTable);
}
}
Activity where tasks are shown
public class ShowTaskActivity extends AppCompatActivity {
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
mHelper = new TaskDbHelper(this);
mTaskListView = (ListView) findViewById(R.id.list_todo);
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase sqLiteDatabase = mHelper.getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(
TaskContract.TaskEntry.TABLE, // Name of the table to be queried
new String[]{ // Which columns are returned
TaskContract.TaskEntry._ID,
TaskContract.TaskEntry.COL_TASK_TITLE,
TaskContract.TaskEntry.COL_TASK_DATE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int index = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(index));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
task, // What view to use for the items
R.id.task_title, // Where to put the string of data
taskList); // Where to get the data
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
sqLiteDatabase.close();
}
// TODO: Change to delete by ID, not name
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = taskTextView.getText().toString();
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
TaskContract.TaskEntry.TABLE, // Where to delete
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?", // Boolean check
new String[]{task}); // What to delete
sqLiteDatabase.close();
updateUI();
}
}
Task adding Code
public void addTask(String task, String date) {
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
contentValues.put(TaskContract.TaskEntry.COL_TASK_DATE, date);
sqLiteDatabase.insertWithOnConflict(
TaskContract.TaskEntry.TABLE,
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE);
sqLiteDatabase.close();
}
String rowId; //Set your row id here
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
TaskContract.TaskEntry.TABLE, // Where to delete
KEY_ID+" = ?",
new String[]{rowId}); // What to delete
sqLiteDatabase.close();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",new String[]{Long.toString(id)} );
db.close();
You can try this method to delete By id
public void deleteData(String tableName, Integer id) {
try {
if (mWritableDB != null) {
mWritableDB.execSQL("delete from " + tableName + " Where id = " + id);
}
} catch (Exception _exception) {
_exception.printStackTrace();
}
}
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 7 years ago.
I cannot find the problem in my (Android) Java code.
The problem (according the logcat) is that there is no such column as reminder_date.
This is the error:
09-19 21:27:24.440 23689-23689/com.example.sanne.reminderovapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.sanne.reminderovapplication, PID: 23689
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sanne.reminderovapplication/com.example.sanne.reminderovapplication.MainActivity}: android.database.sqlite.SQLiteException: no such column: reminder_date (code 1): , while compiling: SELECT reminder_id AS _id , reminder_title , reminder_description , reminder_date FROM reminder
I checked for the commas and spaces.
I hope there is a solution for this problem.
This is my code of the MySQLiteHelper:
public class MySQLiteHelper extends SQLiteOpenHelper{
// Database info
private static final String DATABASE_NAME = "reminderOVApp.db";
private static final int DATABASE_VERSION = 8;
// Assignments
public static final String TABLE_REMINDER = "reminder";
public static final String COLUMN_REMINDER_ID = "reminder_id";
public static final String COLUMN_REMINDER_TITLE = "reminder_title";
public static final String COLUMN_REMINDER_DESCRIPTION = "reminder_description";
public static final String COLUMN_REMINDER_DATE = "reminder_date";
// Creating the table
private static final String DATABASE_CREATE_REMINDERS =
"CREATE TABLE " + TABLE_REMINDER +
"(" +
COLUMN_REMINDER_ID + " integer primary key autoincrement , " +
COLUMN_REMINDER_TITLE + " text not null , " +
COLUMN_REMINDER_DESCRIPTION + " text not null , " +
COLUMN_REMINDER_DATE + " text not null " +
");";
// Mandatory constructor which passes the context, database name and database version and passes it to the parent
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database)
{
// Execute the sql to create the table assignments
database.execSQL(DATABASE_CREATE_REMINDERS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// When the database gets upgraded you should handle the update to make sure there is no data loss.
// This is the default code you put in the upgrade method, to delete the table and call the oncreate again.
if(oldVersion == 8)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDER);
onCreate(db);
}
}
And this is the code of the DataSource Class:
public class DataSource {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] assignmentAllColumns = {MySQLiteHelper.COLUMN_REMINDER_ID, MySQLiteHelper.COLUMN_REMINDER_TITLE, MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION, MySQLiteHelper.COLUMN_REMINDER_DATE};
public DataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
database = dbHelper.getWritableDatabase();
dbHelper.close();
}
// Opens the database to use it
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
// Closes the database when you no longer need it
public void close() {
dbHelper.close();
}
//Add a reminder to the database
public long createReminder(String reminder_title, String reminder_description, String reminder_date) {
// If the database is not open yet, open it
if (!database.isOpen()) {
open();
}
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_REMINDER_TITLE, reminder_title);
values.put(MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION, reminder_description);
values.put(MySQLiteHelper.COLUMN_REMINDER_DATE, reminder_date);
// values.put(MySQLiteHelper.COLUMN_REMINDER_TIME, reminder_time);
long insertId = database.insert(MySQLiteHelper.TABLE_REMINDER, null, values);
// If the database is open, close it
if (database.isOpen()) {
close();
}
return insertId;
}
//Change data of the specific reminder
public void updateReminder(Reminder reminder) {
if (!database.isOpen()) {
open();
}
ContentValues args = new ContentValues();
args.put(MySQLiteHelper.COLUMN_REMINDER_TITLE, reminder.getTitle());
args.put(MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION, reminder.getDescription());
args.put(MySQLiteHelper.COLUMN_REMINDER_DATE, reminder.getDate());
database.update(MySQLiteHelper.TABLE_REMINDER, args, MySQLiteHelper.COLUMN_REMINDER_ID + "=?", new String[] { Long.toString(reminder.getId()) });
if (database.isOpen()) {
close();
}
}
//Delete a reminder from the database
public void deleteReminder(long id) {
if (!database.isOpen()) {
open();
}
database.delete(MySQLiteHelper.TABLE_REMINDER, MySQLiteHelper.COLUMN_REMINDER_ID + " =?", new String[]{Long.toString(id)});
if (database.isOpen()) {
close();
}
}
//Delete all reminders
public void deleteReminders() {
if (!database.isOpen()) {
open();
}
database.delete(MySQLiteHelper.TABLE_REMINDER, null, null);
if (database.isOpen()) {
close();
}
}
//This way you can get the id and the reminder from the cursor.
private Reminder cursorToReminder(Cursor cursor) {
try {
Reminder reminder = new Reminder();
reminder.setId(cursor.getLong(cursor.getColumnIndexOrThrow(MySQLiteHelper.COLUMN_REMINDER_ID)));
reminder.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteHelper.COLUMN_REMINDER_TITLE)));
reminder.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION)));
reminder.setDate(cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteHelper.COLUMN_REMINDER_DATE)));
return reminder;
}catch(CursorIndexOutOfBoundsException exception) {
exception.printStackTrace();
return null;
}
}
//Get all the reminders to populate the listView --> ArrayList
public List<Reminder> getAllReminders() {
if (!database.isOpen()) {
open();
}
List<Reminder> reminders = new ArrayList<Reminder>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_REMINDER, assignmentAllColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Reminder assignment = cursorToReminder(cursor);
reminders.add(assignment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
if (database.isOpen()) {
close();
}
return reminders;
}
//A SimpleCursorAdapter requires a Cursor to get the data from the database instead of an ArrayList.
public Cursor getAllAssignmentsCursor()
{
if (!database.isOpen()) {
open();
}
Cursor cursor = database.rawQuery(
"SELECT " +
MySQLiteHelper.COLUMN_REMINDER_ID + " AS _id , " +
MySQLiteHelper.COLUMN_REMINDER_TITLE + " , " +
MySQLiteHelper.COLUMN_REMINDER_DESCRIPTION + " , " +
MySQLiteHelper.COLUMN_REMINDER_DATE +
" FROM " + MySQLiteHelper.TABLE_REMINDER, null);
if (cursor != null) {
cursor.moveToFirst();
}
if (database.isOpen()) {
close();
}
return cursor;
}
//Get one reminder
public Reminder getReminder(long columnId) {
if (!database.isOpen()) {
open();
}
Cursor cursor = database.query(MySQLiteHelper.TABLE_REMINDER, assignmentAllColumns, MySQLiteHelper.COLUMN_REMINDER_ID + "=?", new String[] { Long.toString(columnId)}, null, null, null);
cursor.moveToFirst();
Reminder assignment = cursorToReminder(cursor);
cursor.close();
if (database.isOpen()) {
close();
}
return assignment;
}}
And my MainActivity Class:
public class AddActivity extends AppCompatActivity {
private DataSource datasource;
private EditText addReminderEditText;
private EditText descriptionEditText;
private EditText dateEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
datasource = new DataSource(this);
addReminderEditText = (EditText) findViewById(R.id.add_reminder_editText);
descriptionEditText = (EditText) findViewById(R.id.description_reminder_editText);
dateEditText = (EditText) findViewById(R.id.date_reminder_editText);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.add_assignment_menu_save) {
//Sending the data back to MainActivity
long reminderId = datasource.createReminder(addReminderEditText.getText().toString(), descriptionEditText.getText().toString(), dateEditText.getText().toString());
Intent resultIntent = new Intent();
resultIntent.putExtra(MainActivity.EXTRA_REMINDER_ID, reminderId);
setResult(Activity.RESULT_OK, resultIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}}
Well, it seems like reminder_date has been added after the first code execution.
Simply uninstall and reinstall your app.
I'm new to Java and just tried to make a database. I managed to make a DB and all but when I want to read the values it seems to get an error.
This is my code for my settings activity (which asks for setting values and add them in the DB on a specific ID)
public class Settings extends Activity{
Button Save;
static Switch SwitchCalculations;
public static String bool;
public static List<Integer> list_id = new ArrayList<Integer>();
public static List<String> list_idname = new ArrayList<String>();
public static List<String> list_kind = new ArrayList<String>();
public static List<String> list_value = new ArrayList<String>();
static Integer[] arr_id;
static String[] arr_idname;
static String[] arr_kind;
static String[] arr_value;
public static final String TAG = "Settings";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Save = (Button) findViewById(R.id.btnSave);
SwitchCalculations = (Switch) findViewById(R.id.switchCalcOnOff);
readData();
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
writeData();
//Toast.makeText(this, "Data has been saved.", Toast.LENGTH_SHORT).show();
readData();
Save.setText("Opgeslagen");
}
});
}
public void writeData() {
int id = 1;
String idname = "switchCalcOnOff";
String kind = "switch";
boolean val = SwitchCalculations.isChecked();
String value = new Boolean(val).toString();
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(dbh.C_ID, id);
cv.put(dbh.C_IDNAME, idname);
cv.put(dbh.C_KIND, kind);
cv.put(dbh.C_VALUE, value);
if (dbh.C_ID.isEmpty() == true) {
db.insert(dbh.TABLE, null, cv);
Log.d(TAG, "Insert: Data has been saved.");
} else if (dbh.C_ID.isEmpty() == false) {
db.update(dbh.TABLE, cv, "n_id='1'", null);
Log.d(TAG, "Update: Data has been saved.");
} else {
Log.d(TAG, "gefaald");
}
db.close();
}
public void readData() {
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
List<String> list_value = new ArrayList<String>();
String[] arr_value;
list_value.clear();
Cursor cursor = db.rawQuery("SELECT " + dbh.C_VALUE + " FROM " + dbh.TABLE + ";", null);
if (cursor.moveToFirst()) {
do {
list_value.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()){
cursor.close();
}
db.close();
arr_value = new String[list_value.size()];
for (int i = 0; i < list_value.size(); i++){
arr_value[i] = list_value.get(i);
}
}
}
Then I have my dbHelper activity see below:
package com.amd.nutrixilium;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class dbHelper_Settings extends SQLiteOpenHelper{
private static final String TAG="dbHelper_Settings";
public static final String DB_NAME = "settings.db";
public static final int DB_VERSION = 10;
public final String TABLE = "settings";
public final String C_ID = "n_id"; // Special for id
public final String C_IDNAME = "n_idname";
public final String C_KIND = "n_kind";
public final String C_VALUE = "n_value";
Context context;
public dbHelper_Settings(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
// oncreate wordt maar 1malig uitgevoerd per user voor aanmaken van database
#Override
public void onCreate(SQLiteDatabase db) {
String sql = String.format("create table %s (%s int primary key, %s TEXT, %s TEXT, %s TEXT)", TABLE, C_ID, C_IDNAME, C_KIND, C_VALUE);
Log.d(TAG, "onCreate sql: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE); // wist een oudere database versie
Log.d(TAG, "onUpgrate dropped table " + TABLE);
this.onCreate(db);
}
}
And the weird thing is I don't get any error messages here.
But I used Log.d(TAG, text) to check where the script is being skipped and that is at cursor.moveToFirst().
So can anyone help me with this problem?
Here, contrary to what you seem to expect, you actually check that a text constant is not empty:
if (dbh.C_ID.isEmpty() == true) {
It isn't : it always contains "n_id"
I think your intent was to find a record with that id and, depending on the result, either insert or update.
You should do just that: attempt a select via the helper, then insert or update as in the code above.
Edit:
Add to your helper something like this:
public boolean someRowsExist(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("select EXISTS ( select 1 from " + TABLE + " )", new String[] {});
cursor.moveToFirst();
boolean exists = (cursor.getInt(0) == 1);
cursor.close();
return exists;
}
And use it to check if you have any rows in the DB:
if (dbh.someRowsExist(db)) { // instead of (dbh.C_ID.isEmpty() == true) {
Looks like you're having trouble debugging your query. Android provides a handy method DatabaseUtils.dumpCursorToString() that formats the entire Cursor into a String. You can then output the dump to LogCat and see if any rows were actually skipped.