public class SignIn extends Activity implements OnClickListener {
Button SignInbtn;
EditText Email,Password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in_screen);
Email = (EditText) findViewById(R.id.etEmail);
Password = (EditText) findViewById(R.id.etPass);
SignInbtn = (Button) findViewById(R.id.btnSignIn);
SignInbtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.btnSignIn:
boolean didItWork = true;
try{
String email = Email.getText().toString();
String password = Password.getText().toString();
PackageITDB SignIn = new PackageITDB(this);
SignIn.open();
String verifyEmail = SignIn.verifyEmail(email);
String verifyPassword = SignIn.verifyPassword(password);
SignIn.close();
if(verifyEmail == email && verifyPassword == password){
Intent intent = new Intent(SignIn.this,UpdateProfile.class);
startActivity(intent);
}
else{
Intent intent = new Intent(SignIn.this,SQLiteExample.class);
startActivity(intent);
}
}catch (Exception e){
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang it!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if(didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heck Yea!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
}
}
This is my activity class, it is suppose to get an email and a password, den will authenticate with the sqldatabase and then go to the updateprofile class, but I do not know why when I enter the email and password that is in the database, it still goes to the SQLiteExample class.
public String verifyEmail(String email) throws SQLException {
// TODO Auto-generated method stub
String [] columns = new String[]{ KEY_ROWID, KEY_EMAIL, KEY_USERNAME, KEY_PASSWORD};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String results;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
results = c.getString(1);
if (results == email)
return results;
}
return null;
}
public String verifyPassword(String password) throws SQLException {
// TODO Auto-generated method stub
String [] columns = new String[]{ KEY_ROWID, KEY_EMAIL, KEY_USERNAME, KEY_PASSWORD};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String results;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
results = c.getString(3);
if (results == password)
return results;
}
return null;
}
This is my code for the database class.
public boolean verifyEmail(String email) throws SQLException {
...
results = c.getString(1);
if (results != null && results.equals(email))
return true;
}
return false;
}
public boolean verifyPassword(String password) throws SQLException {
....
results = c.getString(3);
if (results != null && results.equals(password))
return true;
}
return false;
}
public void onClick(View v) {
...
SignIn.open();
boolean verifyEmail = SignIn.verifyEmail(email);
boolean verifyPassword = SignIn.verifyPassword(password);
SignIn.close();
if(verifyEmail && verifyPassword) {
Intent intent = new Intent(SignIn.this,UpdateProfile.class);
startActivity(intent);
}
...
By the way, are you sure you close your connection properly?
You are comparing strings in-correctly. You have to compare it this way
if( verifyEmail.equals(email) && verifyPassword.equals(password) )
EDIT:
You are pretty new to java? You are doing a wrong string comparison everywhere.
In methods verifyPassword and verifyEmail you are comparing strings using == while you should do it via equals method.
Change if (results == email) to if (results.equals(email)) and if(results == password) to if(results.equals(password). Also both methods returns null when no match found so it would obviously make a null pointer exception in onClick method. You should consider returning a boolean and based on the boolean you should start the appropiate Intent :-/
Related
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();
}
I'm currently developing an app. What it does, the user would input some sentences and then the app will get the ambiguous word and then display it meaning. In my table I have fields like _id, word, meaning, definition_number.
Sample data:
_id word meaning definition_number
1 Break to pause from something 1
2 Break to cut into pieces 2
If the user would input: My break was very fast.
The intended output would be:
Ambiguous word: Break
Meaning: To pause from something
I want to display the it randomly. This is a snippet of code from my DBHelper.class:
public Cursor getAllWords()
{
Cursor localCursor =
//this.myDataBase.query(DB_TABLE, new String[] {
// KEY_ID, KEY_WORD, KEY_MEANING }, null, null, null, null, null);//"RANDOM()");
//this.myDataBase.query(DB_TABLE, new String[] {
// KEY_ID, KEY_WORD, KEY_MEANING }, null, null, null, null, "RANDOM()", " 1");
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_WORD, KEY_MEANING },
null, null, null, null, "RANDOM()");
if (localCursor != null){
localCursor.moveToFirst();
}
return localCursor;
}
MainActivity.class:
ArrayList<String> colWords = new ArrayList<String>();
ArrayList<String> colMeanings = new ArrayList<String>();
String[] words;
String[] meanings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls() {
// TODO Auto-generated method stub
text = (EditText) findViewById (R.id.editText1);
view = (TextView) findViewById (R.id.textView1);
clear = (Button) findViewById (R.id.button2);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
text.setText("");
view.setText("");
}
});
connectDB();
ok = (Button) findViewById (R.id.button1);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Log.d(strWord, strWord);
strWord = text.getText().toString();
if(strWord.isEmpty()){
Toast.makeText(MainActivity.this, "Please input some data", Toast.LENGTH_SHORT).show();
} else {
checkAmbiguousWord();
}
}
});
}
private void connectDB(){
dbHelper = new DBHelper(MainActivity.this);
try {
dbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
cursor = dbHelper.getAllWords();
/*strWord = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_WORD))
+ cursor.getString(cursor.getColumnIndex(DBHelper.KEY_MEANING)); */
colWords.clear();///added code
colMeanings.clear();///added code
/*
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
String records = cursor.getString(0);
Log.d("Records", records);
} */
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
String records = cursor.getString(0);
Log.d("Records", records);
} while (cursor.moveToNext());
}
}
}
private void checkAmbiguousWord(){
final String textToCheck = text.getText().toString();
List<Integer> ambiguousIndexes = findAmbiguousWordIndexes(textToCheck);
view.setText(!ambiguousIndexes.isEmpty() ?
ambigousIndexesToMessage(ambiguousIndexes) : "No ambiguous word/s found.");
}
/**
* #param text checked for ambiguous words
* #return the list of indexes of the ambiguous words in the {#code words} array
*/
private List<Integer> findAmbiguousWordIndexes(String text) {
final String lowerCasedText = text.toLowerCase();
final List<Integer> ambiguousWordIndexList = new ArrayList<Integer>();
words = (String[]) colWords.toArray(new String[colWords.size()]);
meanings = (String[]) colMeanings.toArray(new String[colMeanings.size()]);
for (int i = 0; i < words.length; i++) {
if (lowerCasedText.contains(words[i].toLowerCase())) {
ambiguousWordIndexList.add(i);
}
}
return ambiguousWordIndexList;
}
public String ambigousIndexesToMessage(List<Integer> ambiguousIndexes) {
// create the text using the indexes
// this is an example implementation
StringBuilder sb = new StringBuilder();
for (Integer index : ambiguousIndexes) {
sb.append("Ambiguous words: ");
sb.append(words[index] + "\nMeaning: " + meanings[index] + "\n");
sb.append("");
}
return sb.toString();
}
But all it does is displaying the two records. Both id 1 and id 2. I just want to display only one record randomly. I really need help regarding this. Any ideas? I would gladly appreciate it.
You have RANDOM() ordering but you also need to add a LIMIT 1 to only return one result row. There's an overload of SQLiteDatabase.query() that takes in a limit parameter:
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_WORD, KEY_MEANING },
null, null, null, null, "RANDOM()", "1");
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()) {
...
here i tried to take name and password from database if the user have already an account, or sign up him by enter his data.
This is the first activity which has force close by clicking on first button to log into the data base
public class SelesMeter2Activity extends Activity implements OnClickListener {
EditText ed1;
EditText ed2;
Button b1;
Button b2;
SQLiteDatabase sql;
Cursor c;
Intent in;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed1 = (EditText) findViewById(R.id.ed1);
ed2 = (EditText) findViewById(R.id.ed2);
b1 = (Button) findViewById(R.id.bt1);
b2 = (Button) findViewById(R.id.bt2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
sql = openOrCreateDatabase("db", 0, null);
sql.execSQL("CREATE TABLE if not exists "
+ "Employee2 (password integer NOT NULL PRIMARY KEY,name text NOT NULL)");
}
#Override
public void onClick(View arg0) {
// log in
if (arg0.getId() == R.id.bt1) {
int p = 0;
String name = ed1.getText().toString();
String sp = ed2.getText().toString();
try {
// Attempt to parse the number as an integer
p = Integer.parseInt(sp);
} catch (NumberFormatException nfe) {
// parseInt failed, so tell the user it's not a number
Toast.makeText(this,
"Sorry, " + sp + " is not a number. Please try again.",
Toast.LENGTH_LONG).show();
}
if (c.getCount() != 0) {
c = sql.rawQuery("select * from Employee", null);
while (c.moveToNext()) {
if (name.equals("c.getString(1)") && p == c.getInt(0)) {
in = new Intent(this, secondview.class);
startActivity(in);
break;
}
}
}
else {
Toast.makeText(this,
"please sign up first or enter " + "correct data", 2000)
.show();
}
} else if (arg0.getId() == R.id.bt2) {
// sign up
Intent in2 = new Intent(this, signup.class);
startActivity(in2);
}
}
}
the second class that enter the new user which is not working as expected,
the toast does not work :
public class signup extends Activity implements OnClickListener {
EditText e1;
EditText e2;
SQLiteDatabase sql;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.singupx);
Intent in = getIntent();
e1 = (EditText) findViewById(R.id.ed1s);
e2 = (EditText) findViewById(R.id.ed2s);
b = (Button) findViewById(R.id.bt1s);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String n = e1.getText().toString();
String sp = e2.getText().toString();
try {
// Attempt to parse the number as an integer
int p = Integer.parseInt(sp);
// This insertion will *only* execute if the parseInt was successful
// sql.execSQL("insert into Employee2(password,name)values('"+n+"',"+p+")");
ContentValues values = new ContentValues();
values.put("password", p);
values.put("name", n);
sql.insert("Employee2", null, values);
Toast.makeText(this, "Data inserted", Toast.LENGTH_LONG).show();
Intent in2 = new Intent(this, secondview.class);
startActivity(in2);
} catch (NumberFormatException nfe) {
// parseInt failed, so tell the user it's not a number
Toast.makeText(this,
"Sorry, " + sp + " is not a number. Please try again.",
Toast.LENGTH_LONG).show();
}
}
}
In the SelesMeter2Activity you'll have a NullPointerException at the line:
if (c.getCount() != 0) {
as you don't initialize the Cursor before that line. Move the query before the above line:
c = sql.rawQuery("select * from Employee", null);
if (c.getCount() != 0) {
// ...
You should post the exception you get from the logcat.
Also regarding your signup activity please don't instantiate the first activity to access fields from it. Open the database again in the second activity and insert the values.
This is why you are getting error
// you are calling the `c.getCount();` before you are assigning
// It will throw null pointer exception
if (c.getCount() != 0) {
c = sql.rawQuery("select * from Employee", null);
while (c.moveToNext()) {
if (name.equals(c.getString(1)) && p == c.getInt(0)) {
in = new Intent(this, secondview.class);
startActivity(in);
break;
}
}
}
Change the logic like
c = sql.rawQuery("select * from Employee", null);
c.moveToFirst();
if(!c.isAfterLast()) {
do {
if (name.equals(c.getString(1)) && p == c.getInt(0)) {
in = new Intent(this, secondview.class);
startActivity(in);
break;
}
} while (c.moveToNext());
}
and name.equals("c.getString(1)") should be name.equals(c.getString(1))
EDIT
Example of insert method
ContentValues values = new ContentValues();
values.put("password", n);
values.put("name", p);
database.insert("Employee2", null, values);
So I have a ListView on which I click to start new Activity called MerchantView.
Between the activities I am passing the uid which is a unique identifier of a merchant.
Im then extracting merchant data from DB and want to view this data in this view.
Everything works (while debugging i can see that data is taken from DB and passed properly to setText methods) but the data does not show, am I doing this right?
public class MerchantView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchant);
String desc = "";
String name = "";
Bundle extras = getIntent().getExtras();
String uid = "0";
if(extras !=null) {
uid = extras.getString("uid");
}
// get merchant from database
if(Integer.valueOf(uid) > 0){
Cursor c = Utilities.db.query(mydb.TABLE_MERCHANT,
null,
"uid=?", new String[] {uid}, null, null, null);
if(c.moveToFirst() != false){
name = c.getString(c.getColumnIndex(MerchantsColumns.COLname));
desc = c.getString(c.getColumnIndex(MerchantsColumns.COLdesc));
}
// set values to UI
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
}
else{
}
Button buttonMerchants = (Button) findViewById(R.id.buttonMerchants);
buttonMerchants.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
Data was set properly. The problem was in layout. The header (LinearLayout) at the top had two buttons and it was set to android:layout_height="fill_parent" which was taking whole space. After fixing that, data is showing properly.
Try Below code hope it helps
SQLiteDatabase myDB = this.openOrCreateDatabase("databasename.db", SQLiteDatabase.OPEN_READWRITE, null);
try{
Cursor c = myDB.rawQuery("select name, desc from abctable where uid="+uid, null);
int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("desc");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
int i = 0;
// Loop through all Results
do {
i++;
String name = c.getString(Column1);
String desc = c.getString(Column2);
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
} while (c.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if (myDB != null)
myDB.close();
}