I have editText's (Username, Firstname, Lastname and Email Address) in my activity for user registration. The user has the privilege to search if the username that he input is already existing or not, by clicking the Search Button. If the username is existing, all the information with regards to that username like the name of the user will be showed. However, if the user click the button if it is not existing, my app crashes and I am getting CursorIndexOutOfBoundsException error. How can I debug that one?
MainActivity.java
btn_Search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String searchableUser = txt_User.getText().toString();
ConsUserRegistration consUserRegistration = db.searchUser(searchableUser);
String searchUser = consUserRegistration.getUser().toString();
String searchFirst = consUserRegistration.getFirstName().toString();
String searchLast = consUserRegistration.getLastName().toString();
String searchEmail = consUserRegistration.getEmail().toString();
txt_User.setText(searchUser);
txt_First.setText(searchFirst);
txt_Last.setText(searchLast);
txt_Email.setText(searchEmail);
}
});
DatabaseHandler.java
public ConsUserRegistration searchUser(String username){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Constants.TABLE_USER, new String[] {Constants.KEY_USER, Constants.KEY_FIRST,
Constants.KEY_LAST, Constants.KEY_EMAIL}, Constants.KEY_USER + " =? ",
new String[] { String.valueOf(username) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
ConsUserRegistration search = new ConsUserRegistration (cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
return search;
}
Try this:
MainActivity.java
btn_Search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String searchableUser = txt_User.getText().toString();
ConsUserRegistration consUserRegistration = db.searchUser(searchableUser);
if (consUserRegistration != null){
String searchUser = consUserRegistration.getUser().toString();
String searchFirst = consUserRegistration.getFirstName().toString();
String searchLast = consUserRegistration.getLastName().toString();
String searchEmail = consUserRegistration.getEmail().toString();
txt_User.setText(searchUser);
txt_First.setText(searchFirst);
txt_Last.setText(searchLast);
txt_Email.setText(searchEmail);
}else{
Toast.makeText(getApplicationContext(), "Username Not Found", Toast.LENGTH_LONG).show();
}
}
});
DatabaseHandler.java
public ConsUserRegistration searchUser(String username){
ConsUserRegistration search;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Constants.TABLE_USER, new String[] {Constants.KEY_USER, Constants.KEY_FIRST,
Constants.KEY_LAST, Constants.KEY_EMAIL}, Constants.KEY_USER + " =? ",
new String[] { String.valueOf(username) }, null, null, null);
if (cursor != null && cursor.moveToFirst()){
search = new ConsUserRegistration (cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
}else{
search = null;
}
return search;
}
so... what happens if your cursor IS null or has no elements? you're still trying to access it ...
Try something like...
if (cursor != null && cursor.moveToFirst()) {
...
Related
I'm confused and cannot figure out how I can send an SMS message using values stored on my database.
The SMS would appear like this: ('NAME'... Message content, etc..), the message would then be sent using the contact numbers entered by the user on the sqlite database.
Here's the code I've used to get the data during signup.
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_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text, PASSWORD text, NAME text, C1 integer, C2 integer); ";
// 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, String name, String cn1, String cn2) {
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("NAME",name);
newValues.put("C1", cn1);
newValues.put("C2", cn2);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
// Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
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 getSingleEntry(String userName) {
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) { // username doesn't exist
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public boolean isExist (String userName) {
boolean exists;
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if (cursor.getCount()>0) { // username exists
exists = true;
cursor.close();
return exists;
}
return false;
}
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});
}}
And here is the SignUpActivity
public class SignUpActivity extends AppCompatActivity {
Button bSignup;
TextView tvSign;
EditText etUN, etPW, etPW2, etFN, etC1, etC2;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
bSignup = (Button)findViewById(R.id.bSignup);
tvSign = (TextView)findViewById(R.id.tvSign);
etUN = (EditText)findViewById(R.id.etUN);
etPW = (EditText)findViewById(R.id.etPW);
etPW2 = (EditText)findViewById(R.id.etPW2);
etFN = (EditText)findViewById(R.id.etFN);
etC1 = (EditText)findViewById(R.id.etC1);
etC2 = (EditText)findViewById(R.id.etC2);
bSignup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUN.getText().toString();
String password = etPW.getText().toString();
String password2 = etPW2.getText().toString();
String name = etFN.getText().toString();
String c1 = etC1.getText().toString();
String c2 = etC2.getText().toString();
// check if fields are vacant
if (username.equals("") || password.equals("") || password2.equals("") || name.equals("")
|| c1.equals("")|| c2.equals("")) {
Toast.makeText(getApplicationContext(), "Incomplete Data", Toast.LENGTH_SHORT).show();
return;
}
// check if passwords 1 and 2 match
if (!password.equals(password2)) {
Toast.makeText(getApplicationContext(), "Passwords don't match. Please try again.", Toast.LENGTH_LONG).show();
return;
}
//check is username is still available for use
if (loginDataBaseAdapter.isExist(username)){
Toast.makeText(getApplicationContext(),"Username already taken. Please try again.", Toast.LENGTH_LONG).show();
return;
}
else {
// allow data to be saved in the database
loginDataBaseAdapter.insertEntry(username, password, name, c1, c2);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
});
tvSign.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
Once I'm logged in, how can I get those values ("i.e. NAME, C1, and C2") and send an SMS by pushing a button?
Update
I've used this on my LoginDataBaseAdapter.
public HashMap<String, String> getUserDetails(){
HashMap <String,String> user = new HashMap <String,String> ();
String selectQuery = "SELECT * FROM " + "LOGIN";
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount()>0){
user.put("USERNAME", cursor.getString(1));
user.put("PASSWORD", cursor.getString(2));
user.put("NAME", cursor.getString(3));
user.put("C1", cursor.getString(4));
user.put("C2", cursor.getString(5));
}
cursor.close();
db.close();
// return user
return user;
}
Then this code at my HomeActivity:
tvHello = (TextView)findViewById(R.id.tvHello);
HashMap <String, String> details = loginDataBaseAdapter.getUserDetails();
String name_text = details.get("NAME");
tvHello.setText("Welcome " + name_text);
It seems that it can only get the first entry and not the current entry for the current user. Any ideas to fix this issue? Thank you very much.
Managed to get it right. So I'll answer my own question.
Create a editText area wherein you'll enter your name to retrieve. Then use this code to retrieve it
public String getData(String verif) {
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{verif}, null, null, null);
if(cursor.getCount()<1) {
cursor.close();
return "No records exist";
}
cursor.moveToFirst();
String get_name = cursor.getString(cursor.getColumnIndex("NAME"));
cursor.close();
return get_name;
}
Once retrieved, set the name in a TextView. Then convert it to string like so:
String myName = myTextView.getText().toString();
Then:
smsManager.sendTextMessage(number, null, "My name is "+ myName ,null,
null);
'number' is a String containing the contact number where you want to send your SMS
In my app i am storing data to SQLite, and now i am trying to fetch that data from SQLite to activity.
as per requirement i just have to store single data at a time and my table will contain only single data row not more than one row.
so I want if table has data row then fetch data and show in form in onCreate(..) of LoginActivity.java
Getting:
The method SelectData(String) in the type myDBClass is not applicable for the arguments ()
myDBClass.java:
// Select Data
public String[] SelectData(String strOperatorID) {
// TODO Auto-generated method stub
try {
String arrData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, new String[] { "*" },
"OperatorID=?",
new String[] { String.valueOf(strOperatorID) }, null, null, null, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
arrData = new String[cursor.getColumnCount()];
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
LoginActivity.java:-
public class LoginActivity extends Activity {
.................
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}
From the op requirement..
change your method like this..
public String[] SelectData() {
// TODO Auto-generated method stub
try {
String arrData[] = new String[5];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
Your SelectData method takes a String argument (strOperatorID) but you are calling it with no argument, so obviously it cannot be found.
By the way you should respect Java naming conventions for your methods (i.e. not starting with upper case character)
public String[] SelectData() {
// TODO Auto-generated method stub
try {
String arrData[] = new String[5];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do{
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
} while (cur.moveToNext());
}
}
return arrData;
} catch (Exception e) {
return null;
}finally{
cursor.close();
db.close();
}
In my activity, I have editText's (Username, Firstname, Lastname and Email Address). When the user input an existing username, he can search it by clicking the Search Button and the data which the user have will appear to the editText's.
MainActivity.java
btn_Search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String searchableUser = txt_User.getText().toString();
ConsUserRegistration consUserRegistration = db.searchUser(searchableUser);
String searchUser = consUserRegistration.getUser().toString();
String searchFirst = consUserRegistration.getFirstName().toString();
String searchLast = consUserRegistration.getLastName().toString();
String searchEmail = consUserRegistration.getEmail().toString();
txt_User.setText(searchUser);
txt_First.setText(searchFirst);
txt_Last.setText(searchLast);
txt_Email.setText(searchEmail);
}
});
DatabaseHandler.java
public ConsUserRegistration searchUser(String username){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Constants.TABLE_USER, new String[] {Constants.KEY_USER, Constants.KEY_FIRST,
Constants.KEY_LAST, Constants.KEY_EMAIL}, Constants.KEY_USER + " =? ",
new String[] { String.valueOf(username) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
ConsUserRegistration search = new ConsUserRegistration (cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
return search;
}
But when the user click the Search Button and didn't input any character from the Username EditText, I am getting a CursorIndexOutOfBoundsException error in the DatabaseHandler in line: ConsUserRegistration search = new ConsUserRegistration (cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
Also, I couldn't retrieve the data from the database since it's crashing.
Change
db.searchUser(searchableUser);
ConsUserRegistration consUserRegistration = new ConsUserRegistration();
to
ConsUserRegistration consUserRegistration = db.searchUser(searchableUser);
Button button_Search(button)findViewById(r.I'd.itsIdInYourXml);
Button probably needs declared or defined further need to see whole code
I am getting cursor index out of bounds "index 0 requested: with size 0". Its just a user registration and login application. When there is no user with matching Username and Password my application is getting crashed.
Below is the code:
MainActivity.java
final SUSQLiteHelper dbhelper = new SUSQLiteHelper(this);
LoginData login = dbhelper.readOneUser(loginuname.getText().toString(), loginpwd.getText().toString());
if(login.getUname().toString().equals(loginuname.getText().toString()) &&
login.getPwd().toString().equals(loginpwd.getText().toString()))
{
Toast.makeText(getApplicationContext(), "Login Successfull. Welcome " + login.getUname().toUpperCase() +" !".toString(),
Toast.LENGTH_LONG).show();
}
else if(login.getUname().toString().equals(loginuname.getText().toString()) &&
!login.getPwd().toString().equals(loginpwd.getText().toString()))
{
Toast.makeText(getApplicationContext(), "Login Failed. Incorrect password !",
Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(), "Login Failed. User doesn't exist !",
Toast.LENGTH_LONG).show(); //it never goes here if no username is found in the table
SUSQLiteHelper.java
public LoginData readOneUser(String uname, String pwd)
{
SQLiteDatabase loginUserDB = this.getReadableDatabase();
LoginData newLogin = null;
Cursor cursor = loginUserDB.query(TABLE_NAME, new String[]{TABLE_ROW_UNAME, TABLE_ROW_EMAIL, TABLE_ROW_PWD}, TABLE_ROW_UNAME + "=?",
new String[]{String.valueOf(uname)}, null, null, null);
if(cursor.moveToFirst())
{
newLogin = new LoginData(cursor.getString(0), cursor.getString(1), cursor.getString(2));
}
cursor.close();
loginUserDB.close();
return newLogin;
}
LoginData.java
This class has getter and setter methods for Uname, Pwd, Email fields and a constructor which takes these fields as arguments.
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
It means that cursor.moveToFirst() returns false and Cursor is empty. So try to add the snippet for checking whether cursor is null or not and depends upon that modify your logic.
public LoginData readOneUser(String uname, String pwd)
{
SQLiteDatabase loginUserDB = this.getReadableDatabase();
LoginData newLogin = null;
Cursor cursor = loginUserDB.query(TABLE_NAME, new String[]{TABLE_ROW_UNAME, TABLE_ROW_EMAIL,TABLE_ROW_PWD}, TABLE_ROW_UNAME + "=?",new String[]{String.valueOf(uname)}, null, null, null);
if(cursor!=null) //Check whether cursor is null or not
{
if(cursor.moveToFirst())
{
newLogin = new LoginData(cursor.getString(0), cursor.getString(1), cursor.getString(2));
}
}
cursor.close();
loginUserDB.close();
return newLogin;
}
LoginData login = dbhelper.readOneUser(loginuname.getText().toString(), loginpwd.getText().toString());
if(login!=null)
{
//check for incorrect username or password
}
else
{
//Notify that no Username available with these Username
}
In function readOneUser(), check:
if(cursor.moveToFirst() && !cursor.isAfterLast()) {
//
}
I've been playing with a sample application I found online. Just changing things to see how it works. Yesterday this was not an issue. Today is a different story. I seem to write the correct info to the db. I've checked through log outputs. When I return the information through a cursor I get "null". So, say I enter "Eggs","Bread", and "Candy". I get back "null","null", and "null".
It all starts with the listener for the add grocery button. Adds to the db and writes the list to an label.
Any help?
private void addEvent(String title) {
SQLiteDatabase db = eventsData.getWritableDatabase();
ContentValues values = new ContentValues();
Log.v(TAG, "Adding " + title);
values.put(EventsDataSQLHelper.TITLE, title);
db.insert(EventsDataSQLHelper.TABLE, null, values);
}
private Cursor getEvents() {
SQLiteDatabase db = eventsData.getReadableDatabase();
Cursor cursor = db.query(EventsDataSQLHelper.TABLE, null, null, null, null,
null, EventsDataSQLHelper.TITLE);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
StringBuilder ret = new StringBuilder();
while (cursor.moveToNext()) {
String title = cursor.getString(1);
ret.append(title + "\n");
Log.v(TAG, "SHOWING RET VARIABLE" + ret);
}
t.setText(ret);
}
View.OnClickListener myhandler = new View.OnClickListener()
{
#Override
public void onClick(View GLview)
{
EditText eT = (EditText)findViewById(R.id.itemName1);
editTextStr = eT.getText().toString();
Log.v(TAG, editTextStr);
if(editTextStr != null)
{
addEvent(editTextStr.toString());
Cursor cursor = getEvents();
showEvents(cursor);
eT.setText(null);
}
}
};
Make sure cursor points to the first element of the result cursor.moveToFirst();
Then call cursor.moveToNext()