how to update integer value in sqlite android - java

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();
}
}

Related

How to read and display user's rank which is set as default in the beginning

I added a new column COL_5 to my SQLite database and it's called "rank". Every user registered starts with rank set as "Australopithecus afarensis" which should be displayed in UserPanelActivity.java. What I did is I managed to display nickname of user (SignInActivity) but I have trouble with checking current rank and then display it on the screen.
Code looks like this:
DatabaseHelper:
package com.pracainzynierska.inzynierka;
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;
import android.widget.TextView;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="register.db";
public static final String TABLE_NAME="registeruser";
public static final String COL_1 ="ID";
public static final String COL_2 ="username";
public static final String COL_3 ="mail_address";
public static final String COL_4 ="password";
public static final String COL_5 = "rank";
//public static final String COL_6 = "dailytip";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME,null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT, mail_address TEXT, password TEXT, rank TEXT DEFAULT 'Australopithecus afarensis')");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long addUser(String user, String password, String mail_address) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", user);
contentValues.put("password", password);
contentValues.put("mail_address", mail_address);
long res = db.insert("registeruser", null, contentValues);
db.close();
return res;
}
public boolean checkUser(String username, String password)
{
String[] columns = {COL_1};
SQLiteDatabase db = getReadableDatabase();
String selection = COL_2 + "=?" + " and " + COL_4 + "=?";
String[] selectionArgs = {username, password};
Cursor cursor = db.query(TABLE_NAME, columns,selection,selectionArgs,null,null,null);
int count = cursor.getCount();
cursor.close();
db.close();
if(count>0)
return true;
else
return false;
}
}
SignInActivity:
package com.pracainzynierska.inzynierka;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
public class SignInActivity extends AppCompatActivity {
private TextView register_text;
public static CallbackManager callbackManager;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
db = new DatabaseHelper(this);
callbackManager = CallbackManager.Factory.create();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login);
final ProgressBar loadingProgressBar = findViewById(R.id.loading);
usernameEditText.requestFocus();
register_text = findViewById(R.id.register_text);
register_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(SignInActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = usernameEditText.getText().toString().trim();
String pwd = passwordEditText.getText().toString().trim();
Boolean res = db.checkUser(user,pwd);
if(res == true)
{
Intent intent = new Intent(SignInActivity.this,UserPanelActivity.class);
Intent intentPopUp = new Intent(SignInActivity.this, PopUpActivity.class);
intent.putExtra("username",user);
startActivity(intent);
startActivity(intentPopUp);
Toast.makeText(SignInActivity.this,"Welcome " + user + "!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this,"There is a problem with singing in!", Toast.LENGTH_SHORT).show();
usernameEditText.setText("");
passwordEditText.setText("");
usernameEditText.requestFocus();
}
}
});
}
}
UserPanelActivity:
package com.pracainzynierska.inzynierka;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class UserPanelActivity extends AppCompatActivity {
private Button settings_btn, progress_btn, dailychallenge_btn, premium_btn, logout_btn, training_btn;
private TextView NickNameText, rankText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_panel);
String username = getIntent().getStringExtra("username");
//String rank = getIntent().getStringExtra("rank");
NickNameText = findViewById(R.id.nickname);
NickNameText.setText(username);
//here I'd like to display rank
rankText = findViewById(R.id.rank);
rankText.setText(rank);
settings_btn = findViewById(R.id.settings_user_panel_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Settings();
}
});
progress_btn = findViewById(R.id.progress_button);
progress_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyProgress();
}
});
dailychallenge_btn = findViewById(R.id.challenge_button);
dailychallenge_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DailyChallenge();
}
});
premium_btn = findViewById(R.id.premium_button);
premium_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Premium();
}
});
logout_btn = findViewById(R.id.logout_button);
logout_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackToMenu();
finish();
}
});
training_btn = findViewById(R.id.start_freetraining_button);
training_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Training();
}
});
}
private void Training() {
Intent intent = new Intent(this, FillTheTextActivity.class);
startActivity(intent);
}
private void BackToMenu() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void Premium() {
Intent intent = new Intent(this,PremiumActivity.class);
startActivity(intent);
}
private void DailyChallenge() {
Intent intent = new Intent(this,DailyChallengeActivity.class);
startActivity(intent);
}
private void MyProgress() {
Intent intent = new Intent(this,MyProgressActivity.class);
startActivity(intent);
}
private void Settings() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
Every help is kindly seen, thanks in advance :)
Create a method like this in your DatabaseHelper class:
public String getRank(int id) {
String query = "SELECT rank from " + TABLE_NAME + " where ID = " + id;
SQLiteDatabase db = getReadableDatabase();
try {
return db.rawQuery(query, null).getString(cursor.getColumnIndex(rank));
} catch (Exception e) {
return "";
}
}
Source

How to iterate rows in turn in SQLite on android

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());
}

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.

Getting an error while creating new instance SQLITE

i have an error while making a creating a new instance for writing data to my database SQLlite
this is the code of my database class
package com.example.tttt;
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 info {
public static final String key_nom = "nom_personne";
public static final String key_id = "id_personne";
public static final String key_prenom = "prenom_personne";
private static final String DATABASE_NAME = "infodb";
private static final String DATABASE_TABLE = "infotable";
private static final int DATABASE_VERSION = 1 ;
private DbHelper ourHelper;
private Context ourContext ;
private SQLiteDatabase ourDatabase ;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME,null , DATABASE_VERSION );
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
key_id + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
key_nom + " TEXT NOT NULL, " +
key_prenom + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public info open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String prenom) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(key_nom, name);
cv.put(key_prenom, prenom);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
in my class activity i wrote
info entry = new info(this);
entry.open();
entry.createEntry(name , prenom );
entry.close();
i had a error on info entry = new info(this);
the message error : " The constructor info(new View.OnClickListener(){}) is undefined "
when i change to info entry = new info(intro.this);
i got: "The constructor info(intro) is undefined"
the full intro activity where i try get information from the user and send them to the database
package com.example.tttt;
import com.example.tttt.R.layout;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.DropBoxManager.Entry;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class intro extends Activity {
Button sqlupdate,sqlview,sqlsearch;
EditText sqlnom, sqlprenom,sqltextsearch ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
sqlnom = (EditText)findViewById(R.id.nomenter);
sqlprenom = (EditText)findViewById(R.id.prenomenter);
sqlupdate = (Button) findViewById(R.id.button1);
sqlview = (Button) findViewById(R.id.button2);
// sqlsearch = (Button) findViewById(R.id.button3);
// sqltextsearch = (EditText)findViewById(R.id.editText1);
sqlupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean diditwork = true ;
try{
String name = sqlnom.getText().toString();
String prenom = sqlprenom.getText().toString();
entry = new info();
entry.open();
entry.createEntry(name , prenom );
entry.close();
}catch (Exception e ){
diditwork = false ;
String error = e.toString();
Dialog d = new Dialog(intro.this);
d.setTitle(" merde ");
TextView tv = new TextView(intro.this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if (diditwork){
Dialog d = new Dialog(intro.this);
d.setTitle(" okkk ");
TextView tv = new TextView(intro.this);
tv.setText(" ok yes ");
d.setContentView(tv);
d.show();
}
}
}
});
sqlview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent open = new Intent("android.intent.action.SQLVIEW");
startActivity(open);
}
});
sqlsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
/*String s = sqltextsearch.getText().toString();
info se = new info();
se.open();
String returne = se.search();
*/
}
});
}
}
you have to initialize the info class without parameters:
info entry = new info();
btw. It is common in class names to write the first letter uppercase: Info
Furthermore. If you dont have more code in info your application will throw a NullPointerException here ourDatabase.insert(DATABASE_TABLE, null, cv);
Here in the Class Info there is no Constructor with an Argument of type Intro
Create one if you really need to have the instance of the class Intro at Class Info.
public Info(Intro intro){
}
Else Create a Constructor without any argument passed.
Info entry = new Info(this);
Always try to follow the naming Conventions, its not a good way to program in any way you like. http://www.oracle.com/technetwork/java/codeconv-138413.html

Categories

Resources