• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps how to insert data and check the data from database and move on

hi im stuck again :(

this is my code. can anyone kindly teach me where do i insert my data into database so that when i click on the login button it will check the username and password typed by the user with the database. if its correct it will move on the menu page.

my code below

Code:
package com.logintesting;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LogintestingActivity extends Activity {
    
    @Override
    
            protected void onCreate(Bundle savedInstanceState) {
    
                    // TODO Auto-generated method stub
    
                    super.onCreate(savedInstanceState);
    
                    setContentView(R.layout.main);
    
                    final EditText txtUserName = (EditText)findViewById(R.id.txtUsername);
    
                    final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
    
                    Button btnLogin = (Button)findViewById(R.id.btnLogin);
    
                    btnLogin.setOnClickListener(new OnClickListener(){
    
     
    
                            @Override
    
                            public void onClick(View v) {
    
                                    String username = txtUserName.getText().toString();
    
                                    String password = txtPassword.getText().toString();
    
                                    try{
    
                                            if(username.length() > 0 && password.length() >0)
    
                                            {
    
                                                   db dbUser = new db(LogintestingActivity.this);
    
                                                    dbUser.open();
    
                                                   
    
                                                    if(dbUser.Login(username, password))
    
                                                    {
    
                                                            Toast.makeText(LogintestingActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
    
                                                    }else{
    
                                                            Toast.makeText(LogintestingActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
    
                                                    }
    
                                                    dbUser.close();
    
                                            }
    
                                           
    
                                    }catch(Exception e)
    
                                    {
    
                                            Toast.makeText(LogintestingActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
    
                                    }
    
                            }
    
                           
    
                    });
    
            }
    
    }


Code:
package com.logintesting;

import java.sql.SQLException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class db {

    
    public static final String KEY_ROWID = "_id";
    
        public static final String KEY_USERNAME= "username";
    
        public static final String KEY_PASSWORD = "password";    
    
        private static final String TAG = "DBAdapter";
    
       
    
        private static final String DATABASE_NAME = "usersdb";
    
        private static final String DATABASE_TABLE = "users";
    
        private static final int DATABASE_VERSION = 1;
    
     
    
        private static final String DATABASE_CREATE =
    
            "create table users (_id integer primary key autoincrement, "
    
            + "username text not null, "
    
            + "password text not null);";
    
           
    
        private Context context = null;  
    
        private DatabaseHelper DBHelper;
    
        private SQLiteDatabase db;
    
     
    
        public db(Context ctx)
    
        {
    
            this.context = ctx;
    
            DBHelper = new DatabaseHelper(context);
    
        }
    
           
    
        private static class DatabaseHelper extends SQLiteOpenHelper
    
        {
    
            DatabaseHelper(Context context)
    
            {
    
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
    
            }
    
     
    
            @Override
    
            public void onCreate(SQLiteDatabase db)
    
            {
    
                db.execSQL(DATABASE_CREATE);
    
            }
    
     
    
            @Override
    
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    
            {
    
                Log.w(TAG, "Upgrading database from version " + oldVersion
    
                        + " to "
    
                        + newVersion + ", which will destroy all old data");
    
                db.execSQL("DROP TABLE IF EXISTS users");
    
                onCreate(db);
    
            }
    
        }    
    
       
    
       
    
        public void open() throws SQLException
    
        {
    
            db = DBHelper.getWritableDatabase();
    
        }
    
     
    
         
    
        public void close()
    
        {
    
            DBHelper.close();
    
        }    
    
       
    
        public long AddUser(String username, String password)
    
        {
    
             ContentValues initialValues = new ContentValues();
    
             initialValues.put(KEY_USERNAME, username);
    
             initialValues.put(KEY_PASSWORD, password);      
    
             return db.insert(DATABASE_TABLE, null, initialValues);
    
     
    
        }
    
     
    
        public boolean Login(String username, String password) throws SQLException
    
        {
    
            Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[]{username,password});
    
            if (mCursor != null) {          
    
                if(mCursor.getCount() > 0)
    
                {
    
                    return true;
    
                }
    
            }
    
         return false;
    
        }
    
     
    
    }


XML
Code:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

 xmlns:android="http://schemas.android.com/apk/res/android"

 android:layout_width="fill_parent"

 android:layout_height="fill_parent" android:padding="10dip">

     <TextView

       android:id="@+id/lblUsername"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"      

       android:textSize="20sp" android:text="Username:"

       android:textStyle="bold"

       android:layout_marginBottom="8dip"

       />

      <EditText

                android:id="@+id/txtUsername"

                android:layout_below="@id/lblUsername"

                android:layout_width="fill_parent"

                        android:layout_height="wrap_content"                   

                        android:textSize="12sp"

                        android:layout_marginBottom="8dip"

                />

          <TextView

       android:id="@+id/lblPassword"

        android:layout_below="@id/txtUsername"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"      

       android:textSize="20sp" android:text="Password:"

       android:textStyle="bold"

       android:layout_marginBottom="8dip"

       />

      <EditText

                android:id="@+id/txtPassword"

                android:layout_below="@id/lblPassword"

                android:layout_width="fill_parent"

                        android:layout_height="wrap_content"                   

                        android:textSize="12sp"

                        android:layout_marginBottom="8dip"

                       android:password="true"

                />  

               

           <Button

                        android:id="@+id/btnLogin"

                        android:layout_below="@id/txtPassword"

                        android:layout_width="fill_parent"

                        android:layout_height="wrap_content"

                        android:text="Login"           

              />    

</RelativeLayout>
 
Code:
If this is just a test app with a set username and password then I'd put something like the following in your onCreate method of your DatabaseHelper class:

Code:
String sql = "INSERT INTO " + DATABASE_TABLE + " (" + KEY_USERNAME + ", " + KEY_PASSWORD + ") VALUES ('myUsername', 'myPassword');"
db.execSQL(sql);

If this is going to be in an app that requires users to enter their own username/password, then I'd use a dialog to get the data from users first and then enter it with the above code.

Does that help?
 
Upvote 0
Also, I just noticed you have a method called "AddUser" that basically does the same thing. Why not use that???

because tis is not my code.

i found this code online. and im a newbie in android programming.

how do i add code under the add user part so that when i type the user name and password into the the textfield and when i press the login button it will check the username and passsword with the username andd password from the databse.
 
Upvote 0
I just loaded the code and ran it. As I mentioned before, there are some things missing that you need to get this working. It sounds like you don't have a good grasp of Android/Java yet, so I would start by going through some general Android tutorials first. Just search Google for "getting started with Android" and you should find more than enough! Then look at the tutorials I sent you in my first post.

To answer your question though. You'll have to create either a dialog or activity that asks the user to enter a new username & password. Then you'll insert the password into the DB and return the user back to the login screen. That can be done using the AddUser() method that's already in the code.

If what I said it completely foreign to you then you REALLY need to study a bit more before diving into the code. I know that's probably not what you want to hear, but it will save you hours upon hours of troubleshooting later.
 
Upvote 0
I just loaded the code and ran it. As I mentioned before, there are some things missing that you need to get this working. It sounds like you don't have a good grasp of Android/Java yet, so I would start by going through some general Android tutorials first. Just search Google for "getting started with Android" and you should find more than enough! Then look at the tutorials I sent you in my first post.

To answer your question though. You'll have to create either a dialog or activity that asks the user to enter a new username & password. Then you'll insert the password into the DB and return the user back to the login screen. That can be done using the AddUser() method that's already in the code.

If what I said it completely foreign to you then you REALLY need to study a bit more before diving into the code. I know that's probably not what you want to hear, but it will save you hours upon hours of troubleshooting later.


hahas. okay. letme have a try first.

actually what im doing is the username and password is already in the database jux when the user type in the username and password the programme will check if the username and password works.
 
Upvote 0
Is this an app just for you or is this something you are posting in the market for all users? If this is going in the market (or you're handing it out to various users), you should pop a dialog asking the user for a username and password. Here are a couple of tutorials on how to make dialogs:



If it's just for you, place this code at the very end of your onCreate method in your DatabaseHelper class (in db.java). NOTE: Be sure to edit your username and password!

Code:
AddUser("[B][COLOR="Blue"]myUsername[/COLOR][/B]", "[B][COLOR="Blue"]myPassword[/COLOR][/B]");
 
  • Like
Reactions: currycrab
Upvote 0
Is this an app just for you or is this something you are posting in the market for all users? If this is going in the market (or you're handing it out to various users), you should pop a dialog asking the user for a username and password. Here are a couple of tutorials on how to make dialogs:



If it's just for you, place this code at the very end of your onCreate method in your DatabaseHelper class (in db.java). NOTE: Be sure to edit your username and password!

Code:
AddUser("[B][COLOR=Blue]myUsername[/COLOR][/B]", "[B][COLOR=Blue]myPassword[/COLOR][/B]");


dude thanks. your code is very usefull. im doing the project for my self use. not for the market. thanks alot.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones