How to iterate rows in turn in SQLite on android - java

EDIT ____________________________________________
How my code currently looks, with the same cannot find symbol error.
CompleteSurveyActivity.java
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import android.app.Dialog;
public class CompleteSurveyActivity extends DashBoardAppActivity
{
Button btnAnswer1, btnAnswer2, btnAnswer3;
LoginDataBaseAdapter DataBaseLink;
EditText editNameComplete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
DataBaseLink = new LoginDataBaseAdapter(CompleteSurveyActivity.this);
DataBaseLink.open();
TextView tv = (TextView) findViewById(R.id.questionnn);
tv.setText(DataBaseLink.getAllQuestions.get(index));
editNameComplete = (EditText) findViewById(R.id.editTextQuestion);
//tv.setText(LoginDataBaseAdapter.getQuestion());
//get refs of buttons
btnAnswer1 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer1.setText(DataBaseLink.getAnswer1());
btnAnswer2 = (Button) findViewById(R.id.buttonAnswer2);
btnAnswer2.setText(DataBaseLink.getAnswer2());
btnAnswer3 = (Button) findViewById(R.id.buttonAnswer3);
btnAnswer3.setText(DataBaseLink.getAnswer3());
}
public void answer1(View V) {
final EditText editNameComplete=(EditText)findViewById(R.id.editNameComplete);
// Set On ClickListener
Button btnAnswer1 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stud
String name = editNameComplete.getText().toString();
DataBaseLink.insertResponse(DataBaseLink.getQuestion(), name, DataBaseLink.getAnswer1());
Toast.makeText(getApplicationContext(), "Response Logged ", Toast.LENGTH_LONG).show();
index++;
}
});
}
public void answer2(View V) {
// Set On ClickListener
Button btnAnswer2 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stud
String name = editNameComplete.getText().toString();
DataBaseLink.insertResponse(DataBaseLink.getQuestion(), name, DataBaseLink.getAnswer2 ());
Toast.makeText(getApplicationContext(), "Response Logged ", Toast.LENGTH_LONG).show();
index++;
}
});
}
public void answer3(View V) {
// Set On ClickListener
Button btnAnswer3 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stud
String name = editNameComplete.getText().toString();
DataBaseLink.insertResponse(DataBaseLink.getQuestion(), name, DataBaseLink.getAnswer3());
Toast.makeText(getApplicationContext(), "Response Logged ", Toast.LENGTH_LONG).show();
index++;
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
DataBaseLink.close();
}
}
And my database adapter
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class LoginDataBaseAdapter
{
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE1 = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); ";
static final String DATABASE_CREATE2 = "create table "+"QUESTIONS"+
"( " +"ID"+" integer primary key autoincrement," + "QUESTION text,ANSWER1 text,ANSWER2 text,ANSWER3 text); ";
static final String DATABASE_CREATE3 = "create table "+"RESPONSE"+
"( " +"ID"+" integer primary key autoincrement," + "QUESTION text,USER text, ANSWER int); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
//new try
public void insertQuestion(String question, String answerOne, String answerTwo, String answerThree) {
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("QUESTION", question);
newValues.put("ANSWER1", answerOne);
newValues.put("ANSWER2", answerTwo);
newValues.put("ANSWER3", answerThree);
// Insert the row into your table
db.insert("QUESTIONS", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public void insertResponse(String question, String user, String answer) {
ContentValues newValues = new ContentValues();
//assign values for each row
newValues.put("QUESTION", question);
newValues.put("USER", user);
newValues.put("ANSWER", answer);
//insert
db.insert("RESPONSE", null, newValues);
}
/** public String getResponse()
{
Cursor cursor=db.query("RESPONSE", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question not exist
{
cursor.close();
return "NO RESPONSES";
}
cursor.moveToFirst();
String response= cursor.getString(cursor.getColumnIndex("QUESTION","USER","ANSWER"));
cursor.close();
return response;
}
*/
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public String getQuestion()
{
Cursor cursor=db.query("QUESTIONS", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question not exist
{
cursor.close();
return "NO QUESTIONS";
}
cursor.moveToFirst();
String question= cursor.getString(cursor.getColumnIndex("QUESTION"));
cursor.close();
return question;
}
public List<String> getAllQuestions(){
List<String> questions = new ArrayList<>();
String query = "SELECT QUESTION FROM QUESTIONS ";
Cursor cursor=db.rawQuery(query, null);
while(cursor.moveToNext()) {
questions.add(cursor.getString(0));
}
cursor.close();
return questions;
}
public String getAnswer1()
{
Cursor cursor=db.query("QUESTIONS", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question doesnt exist
{
cursor.close();
return "NO QUESTIONS";
}
cursor.moveToFirst();
String answer1= cursor.getString(cursor.getColumnIndex("ANSWER1"));
cursor.close();
return answer1;
}
public String getAnswer2()
{
Cursor cursor=db.query("QUESTIONS", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question doesnt exist
{
cursor.close();
return "NO QUESTIONS";
}
cursor.moveToFirst();
String answer2= cursor.getString(cursor.getColumnIndex("ANSWER2"));
cursor.close();
return answer2;
}
public String getAnswer3()
{
Cursor cursor=db.query("QUESTIONS", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question doesnt exist
{
cursor.close();
return "NO QUESTIONS";
}
cursor.moveToFirst();
String answer3= cursor.getString(cursor.getColumnIndex("ANSWER3"));
cursor.close();
return answer3;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
I still do not understand why the code is not recognising the mothod within the database class.

To get all questions from your database you should use this code:
public List<String> getAllQuestions(){
List<String> questions = new ArrayList<>();
String query = "SELECT questions FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
String question;
question = cursor.getString(0);
// Adding question to list
questions.add(question);
}while (cursor.moveToNext());
}
return questions;
}
EDIT:
Your final code in CompleteSurveyActivity.java will be:
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import android.app.Dialog;
import java.util.ArrayList;
import java.util.List;
public class CompleteSurveyActivity extends DashBoardAppActivity
{
Button btnAnswer1, btnAnswer2, btnAnswer3;
LoginDataBaseAdapter db;
EditText editNameComplete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
db = new LoginDataBaseAdapter(CompleteSurveyActivity.this);
db.open();
editNameComplete = (EditText) findViewById(R.id.editTextQuestion);
TextView tv = (TextView) findViewById(R.id.questionnn);
tv.setText(db.getAllQuestions.get(index));
//get refs of buttons
btnAnswer1 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer1.setText(db.getAnswer1());
btnAnswer2 = (Button) findViewById(R.id.buttonAnswer2);
btnAnswer2.setText(db.getAnswer2());
btnAnswer3 = (Button) findViewById(R.id.buttonAnswer3);
btnAnswer3.setText(db.getAnswer3());
}

Related

I don't know how to verify if the phone number already exist. I'm just a newbie and i don't know what to do now

I an newbie to android studio and sq lite database, i am developing a login page for an application like the login in gmail. Here i am taking user phone number as primary key.when the user enter his phone number it will redirect to password screen if already exist. I don't know how to checked whether the phone number is already exist or not.
This my code.
PhoneNumber.java
package com.hernaezchristophergmail.projectitrack;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class PhoneNumber extends AppCompatActivity {
EditText Pnum;
Button Con;
UserDBHelper userDBHelper;
SQLiteDatabase sqLiteDatabase;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_number);
Pnum = (EditText) findViewById(R.id.tbPnumber);
Con = (Button) findViewById(R.id.btbCon);
Con.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String pnumber = Pnum.getText().toString().trim();
String storedPassword = UserDBHelper.getSingleEntry(pnumber,sqLiteDatabase);
/* if(pnumber.equals("")||pnumber1.equals("")){
Toast.makeText(PhoneNumber.this, "Please", Toast.LENGTH_LONG).show();
return;
}*/
if(!pnumber.equals(storedPassword)){
Toast.makeText(PhoneNumber.this, "Invalid Login details", Toast.LENGTH_LONG).show();
return;
}
else{
Intent intent = new Intent(PhoneNumber.this,PasswordScreen.class);
startActivity(intent);
}
}
});
}
/* public void add(View view){
String pnumber = Pnum.getText().toString();
Intent intent = new Intent(PhoneNumber.this, PasswordScreen.class);
startActivity(intent);
}
*/
public void create(View view) {
Intent intent = new Intent(PhoneNumber.this, SignUp.class);
startActivity(intent);
}
#Override
public void onBackPressed(){
}
}
UserDBHelper.java
package com.hernaezchristophergmail.projectitrack;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Christopher on 4/26/2016.
*/
public class UserDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ITRACK_USER.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATEINFO_QUERY=
"CREATE TABLE "+ UserContact.UserInformation.TABLE_NAME+"("+ UserContact.UserInformation.User_Password+" TEXT," +
UserContact.UserInformation.User_PhoneNumber+" TEXT," + UserContact.UserInformation.User_Firstame+" TEXT," + UserContact.UserInformation.User_LastName+" TEXT);";
public UserDBHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATIONS","DATABASE CREATED / OPENED ...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATEINFO_QUERY);
Log.e("DATABASE OPERATION", "TABLE CREATED ...");
}
public void saveInfo(String first,String last,String pnum, String pass, SQLiteDatabase db){
ContentValues contentvalues = new ContentValues();
contentvalues.put(UserContact.UserInformation.User_Firstame,first);
contentvalues.put(UserContact.UserInformation.User_LastName,last);
contentvalues.put(UserContact.UserInformation.User_PhoneNumber,pnum);
contentvalues.put(UserContact.UserInformation.User_Password,pass);
db.insert(UserContact.UserInformation.TABLE_NAME, null, contentvalues);
Log.e ("Database Operation", "one row inserted . . .");
}
public static String getSingleEntry(String pnum, SQLiteDatabase sqLiteDatabase) {
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, " User_PhoneNumber=?",
new String[] { pnum }, null, null, null);
if (cursor.getCount() < 1) {
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String phonenum = cursor.getString(cursor.getColumnIndex("password"));
cursor.close();
return phonenum;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
UserContact.java
public class UserContact {
public static abstract class UserInformation{
public static final String TABLE_NAME = "info";
public static final String User_Password= "password";
public static final String User_LastName = "last_name";
public static final String User_Firstame = "first_name";
public static final String User_PhoneNumber = "phone_number";
public static final String PHOTOID = "photo_id";
}
}
What is the Error?
Also, please look into this.
public static String getSingleEntry(String pnum, SQLiteDatabase sqLiteDatabase) {
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, " User_PhoneNumber=?",
new String[] { pnum }, null, null, null);
if (cursor.getCount() < 1) {
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String phonenum = cursor.getString(cursor.getColumnIndex("password"));
cursor.close();
return phonenum; //RETURN YES / NO if exist not the actual password for security purpose.
}
if(!pnumber.equals(storedPassword)){ //ALSO HERE, return YES/NO if exist or new, not the actual password.
Toast.makeText(PhoneNumber.this, "Invalid Login details", Toast.LENGTH_LONG).show();
return;
}
The below method will return the name for the given number. By this way you can trigger whether the number is available or not. Returns true if the number is there else false.
public Boolean numberExists(Context context, String phoneNumber) {
String contactName = null;
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);
try {
if (cursor != null) {
if (cursor.moveToFirst()) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return false;
}
Errors in query
1. Wrong column name User_PhoneNumber never exists in your table. Write query as below
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, UserContact.UserInformation.User_PhoneNumber+"=?",
new String[] { pnum }, null, null, null);
and
2. Wrong column name :) you are reading password instead of phone number.. write
String phonenum = cursor.getString(cursor.getColumnIndex(UserContact.UserInformation.User_PhoneNumber));
instead of
String phonenum = cursor.getString(cursor.getColumnIndex("password"));

cursor Error : Make sure the Cursor is initialized correctly before accessing data from it

I am getting this Error when i enter the existing RegId in Database..
**DatabaseHandler.java**
package com.example.aaqib.scoolbag;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper {
//Creating a Database ScoolBag
SQLiteDatabase mDb;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ScoolBag";
public static final String KEY_NAME = "Name";
public static final String KEY_MOBILENO = "Contact";
public static final String KEY_REGID = "Registration";
public static final String KEY_EMAIL = "Email";
public static final String KEY_PASSWORD = "Password";
// Table name
public static final String tblReg="tblReg";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String vQuery = "Create Table " + tblReg + "(Registration Text primary key,Name Text not null,Password Text not null,Email Text not null,Contact Text not null)";
Log.d("StudentData", "onCreate: " + vQuery);
db.execSQL(vQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS tblReg");
onCreate(db);
}
//using to insert
public void InsertRecord(String vInsertRecord) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(vInsertRecord);
db.close();
}
public void close()
{
mDb.close();
}
/*public Cursor login(String regid)throws SQLiteException
{
String where =(KEY_REGID + "=?");
Cursor m = mDb.query(true, tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{regid}, null, null, null, null);
if (m != null) {
// m.moveToFirst();
}
return m;
}*/
//fetching a emailid
public Cursor getEmailid(String email)throws SQLiteException
{
String where =(KEY_EMAIL + "=?");
Cursor m = mDb.query(true,tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{email}, null, null, null, null);
if (m != null) {
}
return m;
}
//fetching cursor id
public Cursor getRegid(String reg)throws SQLiteException
{
String where =(KEY_REGID + "=?");
Cursor j = mDb.query(true, tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{reg}, null, null, null, null);
if (j!= null) {
//j.moveToFirst();
}
return j;
}
public DatabaseHandler open() throws SQLiteException {
mDb = getWritableDatabase();
return this;
}
}
acitivity_registration.java
package com.example.aaqib.scoolbag;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.view.View.OnClickListener;
public class activity_registration extends Activity {
EditText reg, Name, Pas1, Pas2, Email, Contact;
String regid,emailid;
SQLiteDatabase db;
DatabaseHandler dbh = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_registration);
reg = (EditText) findViewById(R.id.editText);
Name = (EditText) findViewById(R.id.editText2);
Pas1 = (EditText) findViewById(R.id.editText3);
Pas2 = (EditText) findViewById(R.id.editText4);
Email = (EditText) findViewById(R.id.editText5);
Contact = (EditText) findViewById(R.id.editText6);
Button btnReg = (Button) findViewById(R.id.btnRegister);
//button used to register
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbh.open();
try {
//get the id from database
dbh.open();
Cursor c=dbh.getRegid(reg.getText().toString().trim());
if((c != null) && c.moveToFirst())
{
regid = c.getString(c.getColumnIndex("RegId"));
c.close();
}
//get the email id from database
Cursor email = dbh.getEmailid(Email.getText().toString().trim());
if (email != null && email.moveToFirst()) {
emailid = email.getString(email.getColumnIndex("Email"));
email.close();
}
if (reg.getText().toString().equals("") || Name.getText().toString().equals("") || Pas1.getText().toString().equals("") || Pas2.getText().toString().equals("") || Email.getText().toString().equals("") || Contact.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Fill All Mandatory Fields", Toast.LENGTH_SHORT).show();
}
else if (!Email.getText().toString().trim().matches("[a-zA-Z0-9._-]+#[a-z]+.[a-z]+"))
{
Email.setError("Invalid Email Address");
Email.requestFocus();
}
else if (Email.getText().toString().equals(emailid))
{
Toast.makeText(getApplicationContext(), "Email is already registered", Toast.LENGTH_SHORT).show();
}
else if (Email.getText().toString().equals(regid))
{
Toast.makeText(getApplicationContext(), "Registration Id already exist", Toast.LENGTH_SHORT).show();
}
else if (!Contact.getText().toString().trim().matches("^[0-9]{10}$")) {
Contact.setError("Invalid Contact Number");
Contact.requestFocus();
}
else if (!Name.getText().toString().trim().matches("([a-zA-Z ]+)$")) {
Name.setError("Invalid Name");
Name.requestFocus();
}
else if (!Pas1.getText().toString().trim().matches(Pas2.getText().toString().trim())) {
Pas2.setError("Password Not Matched");
Pas2.requestFocus();
}
else {
InsertRecord();
Refresh();
Intent i = new Intent(activity_registration.this, activity_home.class);
startActivity(i);
finish();
}
}
catch (Exception e)
{
String ex=e.toString();
Toast.makeText(getApplicationContext(), ex, Toast.LENGTH_SHORT).show();
}
}
});
}
public void InsertRecord()
{
String vQuery = "insert into tblReg (Registration,Name,Password,Email,Contact)values('" + reg.getText().toString().trim() + "','" + Name.getText().toString().trim() + "','"+ Pas2.getText().toString().trim()+"','"+ Email.getText().toString().trim()+"','"+ Contact.getText().toString().trim() +"')";
DatabaseHandler db = new DatabaseHandler(this);
db.InsertRecord(vQuery);
Toast.makeText(getApplicationContext(), "Inserted successful", Toast.LENGTH_SHORT).show();
}
public void Refresh()
{
reg.setText("");
Name.setText("");
Pas1.setText("");
Pas2.setText("");
Email.setText("");
Contact.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_registration, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Any help would be appreciated.
In your table there is no column as RegId so change following line
regid = c.getString(c.getColumnIndex("RegId"));
to
regid = c.getString(c.getColumnIndex("Registration"));
Hope this will helps you.

Android Deleting Row from SQLITE

I'm currently having trouble deleting one row when user long presses on an item in listview. I am able to only delete one row at a time which is what I want, but when I delete the first few items it is successful and when I attempt to delete an item with a later id. The id does not get deleted and stays. I need help to consistently delete items when ever an item is to be deleted. Thanks.
this is my database helper class
package com.example.health.adapter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.health.dao.ExerciseDAO;
import com.example.health.dao.RecipeDAO;
import java.util.ArrayList;
import java.util.List;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "HealthDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE recipe ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, " +
"description TEXT )";
db.execSQL(CREATE_RECIPE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS recipe");
this.onCreate(db);
}
//START OF CRUD FOR RECIPE
private static final String TABLE_RECIPE = "recipe";
//column names
private static final String KEY_RID = "id";
private static final String KEY_RTITLE = "title";
private static final String KEY_RDESCRIPTION = "description";
private static final String[] RCOLUMNS = {KEY_RID,KEY_RTITLE,KEY_RDESCRIPTION};
public void addRecipe(RecipeDAO r) {
Log.d("addRecipe", r.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RTITLE, r.getTitle());
values.put(KEY_RDESCRIPTION, r.getDescription());
db.insert(TABLE_RECIPE, null, values);
Log.d("Data Added", r.toString());
db.close();
}
public RecipeDAO getRecipe(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(TABLE_RECIPE, // a. table
RCOLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null);
if (cursor != null)
cursor.moveToFirst();
RecipeDAO r = new RecipeDAO();
r.setRecipeID(Integer.parseInt(cursor.getString(0)));
r.setTitle(cursor.getString(1));
r.setDescription(cursor.getString(2));
Log.d("getRecipe("+id+")", r.toString());
return r;
}
public List<RecipeDAO> getAllRecipe() {
List<RecipeDAO> recipe = new ArrayList<RecipeDAO>();
String query = "SELECT * FROM " + TABLE_RECIPE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
RecipeDAO r = null;
if (cursor.moveToFirst()) {
do {
r = new RecipeDAO();
r.setRecipeID(Integer.parseInt(cursor.getString(0)));
r.setTitle(cursor.getString(1));
r.setDescription(cursor.getString(2));
recipe.add(r);
} while (cursor.moveToNext());
}
Log.d("getAllRecipe()", recipe.toString());
return recipe;
}
public int updateRecipe(RecipeDAO r) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", r.getTitle());
values.put("description", r.getDescription());
int i = db.update(TABLE_RECIPE, //table
values, // column/value
KEY_RID+" = ?", // selections
new String[] { String.valueOf(r.getRecipeID()) });
db.close();
return i;
}
public void deleteAllRecipe() {
RecipeDAO r = new RecipeDAO();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECIPE,null,null);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_RECIPE + "'");
db.close();
Log.d("deleteRecipe", r.toString());
}
/*
public void deleteRecipe(RecipeDAO r) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECIPE, KEY_RID+ " = ? ", new String[] { String.valueOf(r.getRecipeID()) });
db.close();
}*/
public boolean deleteRecipe(long id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_RECIPE, KEY_RID + "=" + id, null) > 0;
}
//END OF CRUD FOR RECIPE
}
Class for database CRUD operations
package com.example.health.recipe;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.example.health.adapter.MySQLiteHelper;
import com.example.health.dao.RecipeDAO;
import com.example.health.healthplanner.R;
import java.util.List;
public class Recipes extends Fragment {
MySQLiteHelper db;
Button deleteButton;
ListView lv;
List<RecipeDAO> data;
RecipeDAO r = new RecipeDAO();
public Recipes() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.recipe_fragment, container, false);
db = new MySQLiteHelper(getActivity());
/*
db.addRecipe(new RecipeDAO("Windows", "Bill Gates"));//hardcode test
db.addRecipe(new RecipeDAO("IOS", "Steve Jobs"));//same
db.addRecipe(new RecipeDAO("Android", "Andy Rubin"));//same*/
data = db.getAllRecipe();
final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, data);
lv = (ListView) v.findViewById(R.id.listView2);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
data.remove(position);
db.deleteRecipe(id + 1);
adapter.notifyDataSetChanged();
return false;
// db.deleteRecipeRow(r.getRecipeID());
//Toast.makeText(getActivity(),"ID = " + r.getRecipeID(), Toast.LENGTH_LONG).show();
}
});
deleteButton = (Button) v.findViewById(R.id.deletebutton);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete");
alertDialog.setMessage("Are you sure you want to delete all data?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.deleteAllRecipe();
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "All data delete", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setNegativeButton("No", null);
alertDialog.show();
/* data = db.getAllRecipe();
for(RecipeDAO re : data) { testing to see if data is in database
String log = "Id: " + re.getRecipeID() + ", Title: " + re.getTitle();
Log.d("Data", log);
}*/
}
});
return v;
}
}
try this
public void delete(String name) {
db.delete(your_table_name, "name= ?", new String[] { name });
}
Please revise this method,
//change code in setOnItemLongClickListener
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
data.remove(position);
db.deleteRecipe(id + 1);
data = db.getAllRecipe();
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, data);
//and call change adapter in listview
adapter.notifyDataSetChanged();
return false;
// db.deleteRecipeRow(r.getRecipeID());
//Toast.makeText(getActivity(),"ID = " + r.getRecipeID(), Toast.LENGTH_LONG).show();
}
});
//this method for delete in sqlite database
public boolean deleteRecipe(long id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_RECIPE, KEY_RID + " =?" , new String[]{id}) > 0;
}

how to update integer value in sqlite android

i am having problem with the updation part of the below code. insertion is working properly. when i added the update method for addition/subtraction of the integer stored in the database, the code is no longer working. it says the app has closed unfortunately. the app is not even opening. please check the update method and make sufficient changes.
first i used this code to accept name and email. then this code was changed to accept a number and email. variable name and column name has not been changed. please dont get confused with these.
thank you.
MainActivity.java
package com.sqltut;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save,load,updatebtn;
EditText name,email,update;
DataHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save=(Button) findViewById(R.id.save);
load=(Button) findViewById(R.id.load);
name=(EditText) findViewById(R.id.name);
email=(EditText) findViewById(R.id.email);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getName=name.getText().toString();
String getEmail=email.getText().toString();
int number = Integer.parseInt(getName);
handler=new DataHandler(getBaseContext());
handler.open();
long id=handler.insertData(number, getEmail);
Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getEmail;
Integer getName;
getName=0;
getEmail="";
handler=new DataHandler(getBaseContext());
handler.open();
Cursor C=handler.returnData();
if(C.moveToFirst())
{
do
{
getName=C.getInt(0);
getEmail=C.getString(1);
}while(C.moveToNext());
}
handler.close();
Toast.makeText(getBaseContext(), "Name:"+getName+" And Email:"+getEmail,Toast.LENGTH_LONG).show();
}
});
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int number,flag=0; //flag to check for addition or subtraction
String getupdate=update.getText().toString();
number=Integer.parseInt(getupdate);
handler=new DataHandler(getBaseContext());
handler.open();
handler.updateData(number,flag);
//subtraction: flag=0, addition: flag=1
handler.close();
}
});
//to call next activity
/* Button createAppointment = (Button)findViewById(R.id.Next);
createAppointment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, Page2.class);
MainActivity.this.startActivity(myIntent);
}
});
*/ }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
DataHandler.java
package com.sqltut;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataHandler {
public static final String NAME="name";
public static final String EMAIL="email";
public static final String TABLE_NAME="mytable";
public static final String DATA_BASE_NAME="mydatabase";
public static final int DATABASE_VERSION=1;
public static final String TABLE_CREATE="create table mytable(name text not null, email text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx)
{
this.ctx = ctx;
dbhelper=new DataBaseHelper(ctx);
}
private static class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context ctx)
{
super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS mytable ");
onCreate(db);
}
}
public DataHandler open()
{
db=dbhelper.getWritableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public long insertData(Integer name, String email)
{
ContentValues content=new ContentValues();
content.put(NAME, name);
content.put(EMAIL,email);
return db.insert(TABLE_NAME, null, content);
}
public void updateData(Integer number,Integer flag)
{
db = dbhelper.getReadableDatabase();
String select = "select name from " + TABLE_NAME ;
Cursor c = db.rawQuery(select, null);
int current=0;
if (c.moveToFirst()) {
current= Integer.parseInt(c.getString(0));
}
if(flag==0)//subtraction
{
current=current-number;
}
else//addition
{
current=current+number;
}
c.close();
db.close();
db = dbhelper.getReadableDatabase();
ContentValues content=new ContentValues();
content.put(NAME, current);
db.update(TABLE_NAME, content,null,null);
}
public Cursor returnData()
{
return db.query(TABLE_NAME, new String[] {NAME,EMAIL}, null, null, null, null, null);
}
}
Edited updateData()
public void updateData(Integer value,Integer flag)
{
db = dbhelper.getReadableDatabase();
String selectQuery = "select balance from " + TABLE_NAME ;
Cursor cursor = db.rawQuery(selectQuery, null);
int current = 0;
if (cursor.moveToFirst()) {
current= Integer.parseInt(cursor.getString(0));
}
if(flag==0){
current = current-value;
}else {
current = current+value ;
}
cursor.close();
db.close();
try{
db = dbhelper.getWritableDatabase();
String rawQuery = "update mytable set balance="+current;
db.rawQuery(rawQuery, null);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Code worked. db.rawQuery(rawQuery, null); changed to db.execSQL(rawQuery);
You can update any value in your table by below method:
public void updateInteger(Integer newID)
{
try{
sqliteDb = appDb.getWritableDatabase();
String rawQuery = "update <table_name> set id="+newID;
sqliteDb.rawQuery(rawQuery, null);
Log.v(TAG, "ID updated");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

trying to get coords from database but nothing happens

as you can see from the code below im just trying to get the coords pushed out to the logcat. however i never see the message or the coords. it shows me the sql string then finishes. so i believe the try is failing but even the catch statement doesnt return anything.
Button ButtonMap = (Button) findViewById(R.id.ButMap);
ButtonMap.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
/* Query for some results with Selection and Projection. */
String sql = "SELECT _id,Longitude,Latitude FROM " + MY_DATABASE_TABLE + " WHERE _id = "+ID;
Cursor c = db.rawQuery(sql,null);
//db.query(MY_DATABASE_TABLE, new String[] {"_id", "Longitude", "Latitude"},
// "_id = " + "'%"+ID+"%'", null, null, null, null);
Log.e("SQL Select", sql);
/* Get the indices of the Columns we will need */
int longitude, latitude ;
longitude = c.getColumnIndex("Longitude");
latitude = c.getColumnIndex("Latitude");
/* Check if our result was valid. */
if (c.moveToFirst()) {
int i = 0;
/* Loop through all Results */
do {
i++;
/* Retrieve the values of the Entry
* the Cursor is pointing to. */
double lat = c.getDouble(latitude);
double lon = c.getDouble(longitude);
Log.e("GPS", "location for this record is: lat="+lat+", lon="+lon);
} while (c.moveToNext());
}
} catch (Throwable t) {
Log.e("GPS", t.toString());
}
finally {
if (db != null)
db.close();
}
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
been to long to know exactly what fixed it but here is the answer code:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SqlLiteFishLoggerDao extends SQLiteOpenHelper implements
FishLoggerDao {
private static final String DB_NAME = "fishingLog";
private static final String TABLE_NAME = "LogEntries";
private static final String DELETE_LOG_ENTRY_SQL = "DELETE FROM LogEntries WHERE _id = ?;";
private static final String FIND_LOG_ENTRY_SQL = "SELECT * FROM LogEntries WHERE _id = ?";
private static final String FIND_ALL_ENTRIES_SQL = "SELECT * FROM LogEntries";
private static final String[] NO_ARGS = {};
private Context context;
private SQLiteDatabase DB;
public SqlLiteFishLoggerDao(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
#Override
public void deleteLogEntry(String id) {
DB = getWritableDatabase();
DB.execSQL(DELETE_LOG_ENTRY_SQL, new Object[] { id });
DB.close();
}
#Override
public LogEntry findEntry(String id) {
DB = getReadableDatabase();
Cursor cursor = DB.rawQuery(FIND_LOG_ENTRY_SQL,
new String[] { id });
if (!cursor.moveToFirst()) {
return null;
}
LogEntry entry = new LogEntry();
entry.setId(cursor.getString(cursor.getColumnIndex("_id")));
entry.setEntryDate(cursor.getString(cursor.getColumnIndex("CreateDate")));
entry.setSpecies(cursor.getString(cursor.getColumnIndex("Species")));
entry.setSizeOrWeight(cursor.getString(cursor.getColumnIndex("SizeOrWeight")));
entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
entry.setLongitude(cursor.getDouble(cursor.getColumnIndex("Longitude")));
entry.setPictureUrl(cursor.getString(cursor.getColumnIndex("PictureURL")));
cursor.close();
DB.close();
return entry;
}
#Override
public void insertLogEntry(LogEntry entry) {
DB = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Latitude", entry.getLatitude());
values.put("Longitude", entry.getLongitude());
values.put("PictureURL", entry.getPictureUrl());
values.put("SizeOrWeight", entry.getSizeOrWeight());
values.put("CreateDate", entry.getEntryDate());
values.put("Species", entry.getSpecies());
DB.insertOrThrow("LogEntries", null, values);
DB.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
String s;
try {
InputStream in = context.getResources().openRawResource(R.raw.sql);
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(in, null);
NodeList statements = doc.getElementsByTagName("statement");
for (int i = 0; i < statements.getLength(); i++) {
s = statements.item(i).getChildNodes().item(0).getNodeValue();
db.execSQL(s);
}
Log.e("DB", "DB Created Successfully");
} catch (Throwable t) {
Log.e("DB error: ",t.toString());
}
}
#Override
public List<LogEntry> findAllEntries() {
DB = getReadableDatabase();
List<LogEntry> entries = new ArrayList<LogEntry>();
Cursor cursor = DB.rawQuery(FIND_ALL_ENTRIES_SQL,
NO_ARGS);
if (cursor.moveToFirst()) {
do {
LogEntry entry = new LogEntry();
entry.setId(cursor.getString(cursor.getColumnIndex("_id")));
entry.setEntryDate(cursor.getString(cursor.getColumnIndex("CreateDate")));
entry.setSpecies(cursor.getString(cursor.getColumnIndex("Species")));
entry.setSizeOrWeight(cursor.getString(cursor.getColumnIndex("SizeOrWeight")));
entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
entry.setLongitude(cursor.getDouble(cursor.getColumnIndex("Longitude")));
entry.setPictureUrl(cursor.getString(cursor.getColumnIndex("PictureURL")));
if (entry.getSpecies() == null) {
entry.setSpecies("Not Entered");
}
if (entry.getSizeOrWeight() == null) {
entry.setSizeOrWeight("Not entered");
}
entries.add(entry);
} while (cursor.moveToNext());
}
cursor.close();
DB.close();
return entries;
}
#Override
public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
DB = getWritableDatabase();
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(getWritableDatabase());
DB.close();
}
}

Categories

Resources