I'm new in this programming in Android Studio.I have a problem with this code that I write from a tutorial.
public void onClick(View v){
if (editusername.getText().toString().trim().length() == 0 || editpassword.getText().toString().trim().length() ==0) {
Toast.makeText(getApplicationContext(), "Semua Kolom harus Diisi", Toast.LENGTH_SHORT).show();}
else try{ String username = editusername.getText().toString().trim();
String password = editpassword.getText().toString().trim();
String query = "Select * From User where username = '"+username+"'";
if(DbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
DbManager.insert(username, password);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {
e.printStackTrace();
}
In the 'fetch' and 'insert' Method there was an error of 'cannot be referenced as static method'.
This is the code in the corresponding class DbManager
public void insert(String usn, String pwd) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.USERNAME, usn);
contentValue.put(SQLiteHelper.PASSWORD, pwd);
this.database.insert(SQLiteHelper.TABLE_NAME_USER, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_USER, new String[]{SQLiteHelper._ID, SQLiteHelper.USERNAME, SQLiteHelper.PASSWORD}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
You never created an instance of the DbManager class.
Adding an DbManager manager = new DbManager(); and then using manager.fetch() and manager.insert(params...) should solve your problem.
Doing Class.Method() is only possible if Method() was declares as public static void Method(). If it wasn't, you need to first create an object, then call the method on that object like I showed you above.
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
I want to match password by enter user to database base password.Anybody Help me please.I am very Tired.
Adapter.java
public Cursor getUserInfo(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_FULLNAME, KEY_EMAILID, KEY_PASSWORD}, KEY_ROWID + "=" + rowId , null,
null, null, null, null);
if (mCursor.getCount()<1) {
return mCursor;
}
mCursor.moveToNext();
String dpassword = mCursor.getString(mCursor.getColumnIndex("PASSWORD"));
return mCursor;
}
Login.java
Error come in this Class that tell to create the a variable dpassword.
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
// get the user details email or password
String useremail = emailornumber.getText().toString();
String password = userpassword.getText().toString();
//fetch the password from the database
String storedPassword = databaseAdapter.getUserInfo(dpassword);
// check if password is match
if(userpassword.equals(storedPassword)){
Toast.makeText(LoginActivity.this, "You are Login", Toast.LENGTH_LONG).show();
Intent in = new Intent(LoginActivity.this, MainActivity.class);
}
else
{
Toast.makeText(LoginActivity.this, "Username and Password Does not match", Toast.LENGTH_LONG).show();
}
}
Your line of code:
String storedPassword = databaseAdapter.getUserInfo(dpassword);
is incorrect. You do not have a variable named dpassword and therefore cannot use that name. This is why you are receiving the error message you describe.
Try Lik this ,it will Solve your Problem
Calling the method
String storedPassword = DB.getSingleEntry(email);
Your Database Method
//checking email to Corresponding password
public String getSingleEntry(String email)
{
Cursor cursor=database.query(DataBaseConnector.TABLE_NAME, null, " email=?", new String[]{email}, null, null, null);
if(cursor.getCount()<1) // Email Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("Password"));
cursor.close();
return password;
}
This question already exists:
how to insert data into sq-lite database at run-time [closed]
Closed 9 years ago.
I built an application that uses sq-lite database and within the application at run-time i made a button that when pressed added a new Edit-Text i'm wondering how can i save the values in the new Edit-Text into my database? please help me
Use this method :
public long saveData(Context context, String editTextValue) {
long x = -1;
appDb = new AppDatabase(context);
sqliteDb = appDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("monthOfBirth", editTextValue);
try {
if (sqliteDb.isOpen()) {
x = sqliteDb.insert("password", null, values);
if (x >= 0)
{
Toast.makeText(context, "Password Save", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
return x;
}
Call this method in your button's onClickListener()
button.setOnCLickListener(new View.OnClickListener())
{
#override
public void onClick(View v)
{
if(editText.getText().toString.equals(""))
{
Toast.makeText(context, "Fill Value first.", Toast.LENGTH_SHORT).show();
return;
}
saveData(YourActivity.this, editText.getText().toString());
}
}
Have you created the class extending SQLiteOpenHelper? If you have it, then use the constructor and get an object of this class:
dbHelper = new SQLiteHelper(context, getString(R.string.db_name_dev), null, DB_VERSION);
And then for example:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("term", term);
db.insert("Search", null, cv);
Simply make a String which contains insert query of SQL. Then call the method
db.execSQL(sql);
on your datebase refence variable.
String sql =
"INSERT INTO <TABLE_NAME> VALUES('this is','03/04/2005','5000','tran','y')" ;
db.execSQL(sql);
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()) {
//
}
So I have a db in my app that gets build when the app is first open through an Helper class, I can add (it adds if just use dbfavoritosHelper.insert(favId, favName, favType);ourCursor.requery();Toast.makeText(getApplicationContext(),"El medio a sido a tus favorites!" inside the Agrefav button,)) and delete items from it with no problem, but what I want to accomplish is at the moment of pressing the adding button to check is an item with the same favId already exist, so if it does I don't want to add it because I don't want to create a duplicate so I want to update that item, so far the code I have is not working here it is:
in my main activity
//this is how I call insert
Button Agrefav = (Button) findViewById(R.id.btnFav);
Agrefav.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(arrayOfWebData.isEmpty()){
Toast.makeText(getApplicationContext(),
"No hay medio para agregar a favoritos!",
Toast.LENGTH_LONG).show();
}else{
if(!dbfavoritosHelper.find(favId)){
dbfavoritosHelper.insert(favId, favName, favType);
ourCursor.requery();
Toast.makeText(getApplicationContext(),
"El medio a sido a tus favoritos!",
Toast.LENGTH_LONG).show();
}else{
dbfavoritosHelper.update(favId, favId, favName, favType);
ourCursor.requery();
Toast.makeText(getApplicationContext(),
"El medio se a actualizado en tus favoritos!",
Toast.LENGTH_LONG).show();
}
}
}});
//this is how I call delete
dbfavoritosHelper.delete(delId);
delId=null;
ourCursor.requery();
in my helper:
//this is how I insert items to table
public void insert(String mId, String mName, String mType) {
ContentValues cv=new ContentValues();
cv.put("medioId", mId);
cv.put("medioName", mName);
cv.put("medioType", mType);
getWritableDatabase().insert("favorito", null, cv);
}
//this is how I'm trying to find if an item already exists in db, but not working
public boolean find(String mId){
try {
getReadableDatabase().rawQuery("SELECT * FROM favorito WHERE favorito.medioId='"+mId+"';", null);
return true;
} catch (SQLException sqle){
return false;
}
}
//this is how I update items
public void update(String id, String mId, String mName, String mType){
ContentValues cv=new ContentValues();
String[] args={id};
cv.put("medioId", mId);
cv.put("medioName", mName);
cv.put("medioType", mType);
getWritableDatabase().update("favorito", cv, "_id=?", args);
}
//this is how I delete them
public void delete(String id){
getWritableDatabase().delete("favorito", "_id=?", new String[] {id});
}
any recommendations are welcome, Thanks
You can also let your table check for you. Here's an example in SQLite:
create table foo (
name text unique);
insert into foo (name) values ("Pablo");
insert into foo (name) values ("Pablo"); // Doesn't add row!
So if we change your insert function a little to catch the constraint exception and have it return true/false:
public boolean insert(String mId, String mName, String mType) {
ContentValues cv = new ContentValues();
cv.put("medioId", mId);
cv.put("medioName", mName);
cv.put("medioType", mType);
try {
getWritableDatabase().insertOrThrow("favorito", null, cv);
return true; // Won't be executed if an error is thrown
}
catch(SQLiteConstraintException e) {
return false;
}
}
My solution was to change to
public boolean find(String mId){
Cursor c = getReadableDatabase().rawQuery("SELECT * FROM favorito WHERE favorito.medioId='"+mId+"';", null);
if (c.moveToFirst())
{ return true; }else{
return false;}
}