I have a quick question, I'm sure I'm just making a small mistake but I can't figure it out.I'm trying to get information from the database based on what the user inputs in an EditText. I'm getting error
"java.lang.IllegalStateException: Couldn't read row 0, col 1 from
CursorWindow. Make sure the Cursor is initialized correctly before
accessing data from it.".
Here's My Main Activity Class
public class MainActivity extends AppCompatActivity {
Button create;
Button retrieve;
Button save;
Button clear;
EditText listName;
EditText listDetails;
ToDoListDatabase myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new ToDoListDatabase(this);
create = (Button)findViewById(R.id.createButton);
retrieve = (Button)findViewById(R.id.retrieveButton);
save = (Button)findViewById(R.id.saveButton);
clear = (Button)findViewById(R.id.clearButton);
listName = (EditText)findViewById(R.id.listName);
listDetails = (EditText)findViewById(R.id.listDetails);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddList();
}
});
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(listName.getText().toString());
}
});
}
//Method Resets EditText back to default
public void resetEditText(){
listName.setText("");
listDetails.setText("");
}
//Method Adds List Entered By User To DataBase
public void AddList(){
boolean isInserted = myDb.insertData(listName.getText().toString(), listDetails.getText().toString());
if(isInserted == true){
Toast.makeText(MainActivity.this,"List " + listName.getText().toString() + " successfully created", Toast.LENGTH_LONG).show();
resetEditText();
}
else
Toast.makeText(MainActivity.this,"Error creating list", Toast.LENGTH_LONG).show();
}
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
return;
}
StringBuffer buffer = new StringBuffer();
buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}
}
Here's My DataBase Class
public class ToDoListDatabase extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "List_db";
public static final String TABLE_NAME = "List_Table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "LIST";
public ToDoListDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,LIST TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXITS" + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String list) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, list);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) { //returns -1 if not inserted
return false;
} else
return true;
}
public Cursor getList(String listName) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME = '" +listName+"'" , null);
return res;
}
}
Here's my Android Monitor
10-10 13:11:41.618 2643-2643/com.example.stephen.todolist E/AndroidRuntime: FATAL EXCEPTION: main
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.stephen.todolist.MainActivity.showList(MainActivity.java:79)
at com.example.stephen.todolist.MainActivity$2.onClick(MainActivity.java:47)
at android.view.View.performClick(View.java:4439)
at android.widget.Button.performClick(Button.java:139)
at android.view.View$PerformClick.run(View.java:18395)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Your ToDoListDatabase class does not contain any field with name listName on which you are calling getText(). Also you are not passing any parameter in your getList(). You should pass your EditText query in this getList() and then create query on this param.
Changes:
MainActivy.java
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(listName.getText().toString());
}
});
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
//return;
}
}
StringBuffer buffer = new StringBuffer();
buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}
ToDoListDatabase.java
public Cursor getList(String listName) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME ='" + listName+"'" , null);
return res;
}
Update
Change your showList as
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
return;
}
res.moveToFirst();
StringBuffer buffer = new StringBuffer();
while (!res.isAfterLast()) {
buffer.append(res.getString(0));
res.moveToNext();
}
res.close();
listDetails.setText(buffer); //Not working yet!!!!
}
You are using listName (Edidtext) in your SQLiteOpenHelper class so u r getting error kindly pass the value of listName from your activity to method like.
//call and pass value like this.
showList(listName.getText().toString());
//or like this
String mListname = listName.getText().toString();
if(!TextUtils().isEmpty(mListname))//check if not empty
{
showList(mListname);
}else{
//handle error
}
// your method
public void showList(String listName)
{
//your implementation
}
SQLiteOpenHelper doesnt extends View so u cannot use view there.
but u can pass it to method parameter to access it.
showList(EditText listName)
{
String val = listName.getText().toString();
}
//and pass your editText
showList(listName);
Good programming practice for database and databesehelper to wrap them around another class, open database when needed not on every query and making queries with strings not with views themselves. Check this thread for creating a singleton DatabaseManager and execute queries with it.
Related
I want to insert data from user input on the click of a button but it does not get added. In my addData function it is always returning false. I don't seem to understand why this is happening nor do I have any clue where the error is since my code isn't producing any.
Here is my Database Helper code:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "nutrition_table";
private static final String COL1 = "ID";
private static final String COL2 = "food";
private static final String COL3 = "calories";
DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 + " TEXT" + COL3 + " ,TEXT)" ;
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(DB);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
Log.d(TAG, "addData: Adding " + item + "to" + TABLE_NAME);
long res = db.insert(TABLE_NAME, null, contentValues);
if (res == -1) {
return false;
} else {
return true;
}
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
Here is my addActivity code:
DatabaseHelper mDbhelper;
TextView addFood, addCals;
Button addEntry, deleteEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
addFood = findViewById(R.id.addFoodItemTextView);
addCals = findViewById(R.id.addCaloriesTextView);
addEntry = findViewById(R.id.addBtn);
deleteEntry = findViewById(R.id.deleteBtn);
mDbhelper = new DatabaseHelper(this);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String foodEntry = addFood.getText().toString();
String calsEntry = addCals.getText().toString();
if (foodEntry.length() != 0) {
addData(foodEntry);
addFood.setText("");
} else {
toastMessage("You have to add data in the food/meal text field!");
}
if (calsEntry.length() != 0) {
addData(calsEntry);
addCals.setText("");
} else {
toastMessage("You have to add data in the calorie text field");
}
}
});
}
public void addData(String newEntry) {
boolean insertData = mDbhelper.addData(newEntry);
if (insertData) {
toastMessage("Added to entries");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Here is the code where the data is supposed to be displayed:
private final static String TAG = "listData";
DatabaseHelper dbHelper;
private ListView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_entries);
displayData = findViewById(R.id.listData);
dbHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = dbHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
listData.add(data.getString(1));
listData.add(data.getString(2));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
displayData.setAdapter(adapter);
}
}
Keep in mind that I am using an intent to view the entries (When the user clicks the button it brings him to the View entries page). I'm not sure where my code went wrong. Any help is greatly appreciated.
Thanks!
I'm doing a small project for my mobile app subject. I need to link it with sqlitedatabase.
I've been the tutorial at the Youtube, I followed the tutorial step by step. I didn't got any error from the code.
I need to insert the value into the db and display it back but the user input didn't inserted into db so I couldn't display the data from the DB.
I hope someone could help me. I've been stuck for 2 days because of this problem with no error display.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "STUDENT.DB";
//create table
public static final String TABLE_STUDENT = "STUDENT_TABLE";
public static final String COL_STD_ID = "STD_ID";
public static final String COL_STD_NAME = "STD_NAME";
public static final String COL_STD_EMAIL = "STD_EMAIL";
public static final String COL_STD_ADDRESS = "STD_ADDRESS";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME, null, 1);
Log.e("DATABASE OPERATION","Database created/opend...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_STUDENT +" (STD_ID INTEGER PRIMARY KEY AUTOINCREMENT,STD_NAME TEXT,STD_EMAIL TEXT, STD_ADDRESS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_STUDENT );
onCreate(db);
}
public boolean insertData(String STD_NAME, String STD_EMAIL, String STD_ADDRESS)
{
SQLiteDatabase db = this.getWritableDatabase();
//get the data from user into db
ContentValues contentValues = new ContentValues();
contentValues.put(COL_STD_NAME,STD_NAME);
contentValues.put(COL_STD_EMAIL,STD_EMAIL);
contentValues.put(COL_STD_ADDRESS,STD_ADDRESS);
//SEE WHETHER THE DATA INSERT INTO DB OR NOT
//IF RETURN -1, DATA NOT SUCCESSFUL INSERTED
long result = db.insert(TABLE_STUDENT,null,contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + TABLE_STUDENT,null);
return result;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText etstdName, etstdEmail, etstdAddress;
Button btnInsertData, btnViewData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
etstdName = (EditText)findViewById(R.id.etstdName);
etstdEmail = (EditText)findViewById(R.id.etstdEmail);
etstdAddress = (EditText)findViewById(R.id.etstdEmail);
btnViewData = (Button)findViewById(R.id.btnViewData);
btnInsertData = (Button)findViewById(R.id.btnInsertData);
InsertStdData();
}
// I think i get stuck at here but theres not error display at InsertStdData() methid
public void InsertStdData() {
btnInsertData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDB.insertData(etstdName.getText().toString(),
etstdEmail.getText().toString(),
etstdAddress.getText().toString());
if(isInserted = true)
Toast.makeText(MainActivity.this,"Data successfully inserted.",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not successfully inserted.",Toast.LENGTH_LONG).show();
}
});
}
public void viewStdData(View view) {
Cursor result = myDB.getAllData();
if(result.getCount() == 0) {
//showmessage method
showMessage("ERROR", "NO DATA FOUND");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()){
buffer.append("STD_ID : "+result.getString(0)+"\n");
buffer.append("STD_NAME : "+result.getString(1)+"\n");
buffer.append("STD_EMAIL : "+result.getString(2)+"\n");
buffer.append("STD_ADDRESS :"+result.getString(3)+"\n\n");
}
//show all data
showMessage("DATA",buffer.toString());
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
You called InsertStdData() but you didnt call viewStdData(View view) in your MainActivity.
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.
When I click on the button, it's supposed to store the typed data into the database, along with the longitude and latitude that has been collected from a separate activity. I'm unsure what I did wrong, my other database works fine. Any help would be appreciated. I'll post the code below:
This is the activity java.
public class NoteActivity extends Activity implements OnClickListener {
Button buttonLeaveNote;
private EditText mTitle;
private EditText mDesc;
protected NoteDBHelper noteDB = new NoteDBHelper(NoteActivity.this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
buttonLeaveNote = (Button) findViewById(R.id.buttonLeaveNote);
buttonLeaveNote.setOnClickListener(this);
mTitle = (EditText)findViewById(R.id.etitle);
mDesc = (EditText)findViewById(R.id.edesc);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.note, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonLeaveNote:
String title = mTitle.getText().toString();
String desc = mDesc.getText().toString();
Intent intent = getIntent();
String lati = intent.getExtras().getString("lati");
String lng = intent.getExtras().getString("lng");
boolean invalid = false;
if(title.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter a title", Toast.LENGTH_SHORT).show();
}
else
if(desc.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter description", Toast.LENGTH_SHORT).show();
}
else
if(invalid == false)
{
addEntry(title, desc, lati, lng);
Intent i_note = new Intent(NoteActivity.this, JustWanderingActivity.class);
startActivity(i_note);
//finish();
}
break;
}
}
public void onDestroy()
{
super.onDestroy();
noteDB.close();
}
private void addEntry(String title, String desc, String lati, String lng)
{
SQLiteDatabase notedb = noteDB.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", title);
values.put("desc", desc);
values.put("lati", lati);
values.put("lng", lng);
try
{
long newRowId;
newRowId = notedb.insert(NoteDBHelper.DATABASE_TABLE_NAME, null, values);
Toast.makeText(getApplicationContext(), "Note successfully added", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This is the SQLite DB Java
public class NoteDBHelper extends SQLiteOpenHelper
{
private SQLiteDatabase notedb;
public static final String NOTE_ID = "_nid";
public static final String NOTE_TITLE = "title";
public static final String NOTE_DESC = "desc";
public static final String NOTE_LAT = "lati";
public static final String NOTE_LONG = "lng";
NoteDBHelper noteDB = null;
private static final String DATABASE_NAME = "stepsaway.db";
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_TABLE_NAME = "notes";
private static final String DATABASE_TABLE_CREATE =
"CREATE TABLE" + DATABASE_TABLE_NAME + "(" +
"_nid INTEGER PRIMARY KEY AUTOINCREMENT," +
"title TEXT NOT NULL, desc LONGTEXT NOT NULL, lati TEXT NOT NULL, lng, TEXT NOT NULL);";
public NoteDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
#Override
public void onCreate(SQLiteDatabase notedb) {
try{
notedb.execSQL(DATABASE_TABLE_CREATE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase notedb, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public Cursor rawQuery(String string, String[] strings) {
// TODO Auto-generated method stub
return null;
}
public void open() {
getWritableDatabase();
}
public Cursor getDetails(String text) throws SQLException
{
Cursor mCursor =
notedb.query(true, DATABASE_TABLE_NAME,
new String[]{NOTE_ID, NOTE_TITLE, NOTE_DESC, NOTE_LAT, NOTE_LONG},
NOTE_TITLE + "=" + text,
null, null, null, null, null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
}
Here's the logcat
FATAL EXCEPTION: main
java.lang.NullPointerException
atcom.example.stepsaway.NoteActivity.onClick(NoteActivity.java:53)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Here's the putExtra() calls.
tvLatitude.setText("Latitude:" + location.getLatitude());
tvLongitude.setText("Longitude:" + location.getLongitude());
String lati = tvLatitude.getText().toString();
String lng = tvLongitude.getText().toString();
Intent i = new Intent(this, NoteActivity.class);
i.putExtra("lati", lati);
i.putExtra("lng", lng);
Without logcat its very difficult to help you... so also post logcat
One mistake is in your create table query inside your NoteDBHelper class...
you are forgetting to put space between keyword table and table name (DATABASE_TABLE_NAME)
So either change to:
private static final String DATABASE_TABLE_CREATE =
"CREATE TABLE " + DATABASE_TABLE_NAME + "(" +
"_nid INTEGER PRIMARY KEY AUTOINCREMENT," +
"title TEXT NOT NULL, desc LONGTEXT NOT NULL, lati TEXT NOT NULL, lng, TEXT NOT NULL);";
Or to:
public static final String DATABASE_TABLE_NAME = " notes";
PS.
NullPointerException
Check for null before using intent.getExtras() and also make sure you are passing String Not double in intent.putExtra()
intent.putExtra("lati","CheckHere it must be String not double");
intent.putExtra("lng","CheckHere it must be String not double");
And also following code would avoid the crash and will help you to debug properly
Intent intent = getIntent();
if(intent != null)
{
String lati = intent.getExtras().getString("lati");
String lng = intent.getExtras().getString("lng");
if(lati == null)
{
Log.e("Checking lati","Its Null");
lati="0";
}
if(lng == null)
{
Log.e("Checking lng","Its Null");
lng="0";
}
}
else
{
Log.e("Checking intent","Its Null");
}
The addentry method should be called as follows:
noteDB.addEntry(title, desc, lati, lng);
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.