Android Studio can't insert data into sqlitedatabase - java

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.

Related

SQL Lite Data not being inserted (Android Studio in java)

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!

Receive data from database based on user input in EditText

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.

How to insert and retrieve data display button using sqlite

I cant't get all data to display in button when click on button get. please help me.
public class DBHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String DATABASE = "Test";
private static final String TABLE_NAME = "savedata";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_SEX = "sex";
public DBHelper(Context context) {
super(context, DATABASE, null,VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " +TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + " TEXT,"
+ KEY_SEX + " TEXT)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" +TABLE_NAME);
onCreate(db);
}
public void Insertdata(Data data){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, data.getName());
values.put(KEY_SEX, data.getSex());
db.insert(TABLE_NAME, null, values);
}
public List<Data> getAllData(){
List<Data> listData = new ArrayList<Data>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " +TABLE_NAME, null);
if (c.moveToFirst()){
do {
Data data = new Data();
data.setId(c.getInt(0));
data.setName(c.getString(1));
data.setSex(c.getString(2));
listData.add(data);
}while (c.moveToNext());
}
return listData;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.edit_name);
sex = (EditText)findViewById(R.id.edit_sex);
btn_get = (Button)findViewById(R.id.btn_get);
btn_name = (Button)findViewById(R.id.btn_name);
btn_sex = (Button)findViewById(R.id.btn_sex);
btn_id = (Button)findViewById(R.id.btn_id);
db = new DBHelper(this);
_name = name.getText().toString();
_sex = sex.getText().toString();
data = new Data(_name,_sex);
btn_save =( Button)findViewById(R.id.btn_save);
SaveData();
getData();
}
public void SaveData(){
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
db.Insertdata(data);
Toast.makeText(getApplicationContext(), "SuccessFull",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void getData(){
btn_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (currentData == null){
Toast.makeText(getApplicationContext(),"Null", Toast.LENGTH_SHORT).show();
}else {
currentData = db.getAllData();
btn_id.setText(String.valueOf(data.getId()));
btn_name.setText(data.getName());
btn_sex.setText(data.getSex());
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
You've messed up badly. That's all I can suggest-
1. Create a class (for example "MyClass") that will extend AppCompatActivity and contains the view.
2. You've already created a class named DBHelper for your Database manipulation. It extends SQLiteOpenHelper.
3. Create object of DBHelper class inside the onCreate method of MyClass and access your database. onCreate method in MyClass will be looking similar to this-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.edit_name);
sex = (EditText)findViewById(R.id.edit_sex);
btn_get = (Button)findViewById(R.id.btn_get);
btn_name = (Button)findViewById(R.id.btn_name);
btn_sex = (Button)findViewById(R.id.btn_sex);
btn_id = (Button)findViewById(R.id.btn_id);
db = new DBHelper(this);
_name = name.getText().toString();
_sex = sex.getText().toString();
data = new Data(_name,_sex);
btn_save =( Button)findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
db.Insertdata(data);
Toast.makeText(getApplicationContext(), "SuccessFull",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
btn_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (currentData == null){
Toast.makeText(getApplicationContext(),"Null", Toast.LENGTH_SHORT).show();
}else {
currentData = db.getAllData();
btn_id.setText(String.valueOf(data.getId()));
btn_name.setText(data.getName());
btn_sex.setText(data.getSex());
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
Hope that, this might help.

Change Password In SQLite Database in Android

I'm using SQLite Database for insert , create or update data in my application.I want to change the password in my SQLite database.I'm having problem for change the password in my app. When I run the demo and enter the whatever field is there and hit the Button for change the data in database it goes to else condition. Nothing to show any error or exceptions in log cat. Is there any way to do that? Here is my code.
This is my DBHelper class
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(DataBase_Adapter.DATABASE_CREATE_LOGIN);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to "+_newVersion + ", which will destroy all old data");
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
onCreate(_db);
}
}
This DataBaseAdapter Class Code
public static final String TABLE_NAME_LOGIN="LOGIN";
//Colum,n Names
public static final String KEY_LOGIN_ID="ID";
public static final String KEY_USERNAME="USERNAME";
public static final String KEY_EMAIL_ID="EMAILID";
public static final String KEY_PASSWORD="PASSWORD";
//Table Create Statement
public static final String DATABASE_CREATE_LOGIN = "CREATE TABLE "+TABLE_NAME_LOGIN+" ("+KEY_LOGIN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_USERNAME+" TEXT, "+KEY_EMAIL_ID+" TEXT, "+KEY_PASSWORD+" TEXT)";
//Insert Data in Database Login
public void insertEntry(String userName,String userEmail,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_USERNAME , userName);
newValues.put(KEY_EMAIL_ID , userEmail);
newValues.put(KEY_PASSWORD , password);
// Insert the row into your table
db.insert(TABLE_NAME_LOGIN, null, newValues);
}
//Update Query
public boolean change(String strEmailId , String strNewPin1 )
{
Cursor cur=db.rawQuery("UPDATE "+TABLE_NAME_LOGIN +" SET " + KEY_PASSWORD+ " = '"+strNewPin1+"' WHERE "+ KEY_EMAIL_ID +"=?", new String[]{strEmailId});
if (cur != null)
{
if(cur.getCount() > 0)
{
return true;
}
}
return false;
}
This is my Change Pin Activity
public class Change_Pin_Activity7 extends Activity
{
EditText editText_EmailId , editText_changePin1 , editText_changePin2;
Button buttonChangePin;
TextView textView_PasswordMatch;
String strEmailId , strNewPin1 , strNewPin2;
boolean storedNewData;
DataBase_Adapter dbAdapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.change_pin_activity7);
dbAdapter=new DataBase_Adapter(this);
dbAdapter=dbAdapter.open();
editText_EmailId=(EditText)findViewById(R.id.EditText_EmailId);
editText_changePin1=(EditText)findViewById(R.id.EditText_Pin1);
editText_changePin2=(EditText)findViewById(R.id.EditText_Pin2);
textView_PasswordMatch=(TextView)findViewById(R.id.TextView_PinProblem);
buttonChangePin=(Button)findViewById(R.id.button_ChangePin);
buttonChangePin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
strEmailId = editText_EmailId.getText().toString().trim();
strNewPin1 = editText_changePin1.getText().toString().trim();
strNewPin2 = editText_changePin2.getText().toString().trim();
storedNewData=dbAdapter.change(strEmailId , strNewPin1);
if (strNewPin1.equals(storedNewData))
{
textView_PasswordMatch.setText("Password Match !!!");
Toast.makeText(Change_Pin_Activity7.this,
"Pin Change Successfully", Toast.LENGTH_LONG).show();
}
// check if any of the fields are vaccant
if(strEmailId.equals("")||strNewPin1.equals("")||strNewPin2.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!strNewPin1.equals(strNewPin2))
{
Toast.makeText(getApplicationContext(), "Pin does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
Toast.makeText(getApplicationContext(),"Not Working ", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
dbAdapter.close();
}
}
When is if (strNewPin1.equals(storedNewData)) ever going to succeed, if strNewPin1 is a String, and storedNewData is a boolean.

cursor.moveToFirst seems to be skipped

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.

Categories

Resources