Click here to Skip to main content
15,121,818 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to create a simple login app in android studio in that I want to fetch first time username and password from local database sqlite and after that when we log in then the imei number of device can store in database... then when we try to log in next time it will login through only that imei number

What I have tried:

So This is MainActivity.java file In this File that Insert method Has Some problem
Java
package com.example.newlogin;


import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.LoginFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.textfield.TextInputLayout;


public class MainActivity extends AppCompatActivity {

     Button login;
    DatabaseHandler sqLiteHelper;
    String SQLiteDataBaseQueryHolder ;
    SQLiteDatabase sqLiteDatabaseObj;
    String imeistr;

    TextInputLayout userview ;
    TextInputLayout passview ;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        sqLiteHelper = new DatabaseHandler(this);

        login = (Button) findViewById(R.id.button1);
             userview = (TextInputLayout) findViewById(R.id.Username);
            passview    = (TextInputLayout) findViewById(R.id.Password);

     //  TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
     //   String imeistr = telephonyManager.getDeviceId();
      //  Toast.makeText(getApplicationContext(), imeistr, Toast.LENGTH_SHORT).show();

        userview.getEditText().addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {}

            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {}

            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                //get the String from CharSequence with s.toString() and process it to validation

            }
        });
        passview.getEditText().addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {}

            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {}

            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                //get the String from CharSequence with s.toString() and process it to validation

            }
        });

     login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                {

                    SQLiteDataBaseBuild();
                    // Creating SQLite table if dose n't exists.
                    SQLiteTableBuild();
                    InsertDataIntoSQLiteDatabase();
                } }

        });

    }
    // SQLite database build method.
    public void SQLiteDataBaseBuild(){

        sqLiteDatabaseObj = openOrCreateDatabase(DatabaseHandler.DATABASE_NAME, Context.MODE_PRIVATE, null);

    }

    // SQLite table build method.
    public void SQLiteTableBuild() {

        sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS " + DatabaseHandler.TABLE_NAME + "(" + DatabaseHandler.KEY_User + " PRIMARY KEY , " + DatabaseHandler.KEY_PASS + " STRING);");

    }

    // Insert data into SQLite database method.
    public void InsertDataIntoSQLiteDatabase(){


        if (userview.getEditText().getText().toString().equals("admin") &&
               passview.getEditText().getText().toString().equals("admin"))
        {

            // SQLite query to insert data into table.
            SQLiteDataBaseQueryHolder = "INSERT INTO " + DatabaseHandler.TABLE_NAME + " (username,password) VALUES('" + userview + "', '" + passview + "');";

            // Executing query.
            sqLiteDatabaseObj.execSQL(SQLiteDataBaseQueryHolder);

            // Closing SQLite database object.
         //   sqLiteDatabaseObj.close();

            // Printing toast message after done inserting.
            Toast.makeText(MainActivity.this, "User Login Successfully", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(MainActivity.this, wv.class);
            startActivity(intent);
        }
        // This block will execute if any of the registration EditText is empty.
        else {

            // Printing toast message if any of EditText is empty.
            Toast.makeText(MainActivity.this,"Please Fill All The Required Fields.", Toast.LENGTH_LONG).show();

        }

    }

}

This is My DatabaseHandler class
Java
package com.example.newlogin;


import android.content.Context;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;



public class DatabaseHandler extends SQLiteOpenHelper {


     static final String DATABASE_NAME = "Galaxy";
    public static final String TABLE_NAME = "LOGINUSER";

    public static final String KEY_User = "username";
    public static final String KEY_PASS = "password";
    public static final String KEY_IMEI_NO = "imei_number";



    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);

    }
    public static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + TABLE_NAME + " (" +KEY_User+ "STRING , "+
                    KEY_PASS +" STRING,"+ KEY_IMEI_NO + "STRING"+ " )";

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

        // Create tables again
        onCreate(db);

    }
}

This is my Activty_main.xml file
XML
<linearlayout

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

="" android:layout_height="match_parent" 
="" android:layout_width="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:padding="20dp" android:background="#fed8b1">

    <imageview
 android:id="@+id/Logo_Image" 
="" android:layout_width="420dp" android:layout_height="150dp" android:src="@mipmap/neumann_logo_final">

    <textview
 android:id="@+id/Logo_Name" 
="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:fontfamily="sans-serif-black" android:text="Welcome" android:textcolor="#B71C1C" android:textsize="40sp">

    <linearlayout


 android:layout_height="wrap_content" 
="" android:layout_width="match_parent" android:layout_margintop="20dp" android:layout_marginbottom="20dp" android:orientation="vertical">
        <com.google.android.material.textfield.textinputlayout
 android:layout_height="wrap_content" 
="" android:layout_width="match_parent" android:id="@+id/Username" android:hint="UserName" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

            <com.google.android.material.textfield.textinputedittext

 android:layout_width="match_parent" 
="" android:layout_height="60dp" android:background="#FF5722" android:textappearance="@style/TextAppearance.AppCompat.Large">
        

        <com.google.android.material.textfield.textinputlayout
 android:layout_height="wrap_content" 
="" android:layout_width="match_parent" android:id="@+id/Password" 

="" android:hint="Password" app:passwordtoggleenabled="true" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

            <com.google.android.material.textfield.textinputedittext

 android:layout_width="match_parent" 
="" android:layout_height="wrap_content" android:background="#FF5722" android:textappearance="@style/TextAppearance.AppCompat.Large">
        




    

    <button
 android:id="@+id/button1" 
="" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#800000" android:paddingbottom="4dp" android:text="Login" android:textappearance="@style/TextAppearance.AppCompat.Large">

so please what is the problem in this code

EDIT: Added from comment:
my apllication run very properly but the LOGINUSER table saves the entry like:
com.google.android.material.textfield.TextInputLayout{16aa1a2 V.ED..... ........ 0,0-1300,229 #7f080011 app:id/Username aid=1073741828}

Now what change can i do to store table values as admin
Posted
Updated 8-Jan-21 2:15am
v6
Comments
Richard MacCutchan 6-Jan-21 6:27am
   
What is the question?
Richard MacCutchan 7-Jan-21 4:46am
   
Well that is just a repeat of what you posted above.
Richard MacCutchan 8-Jan-21 3:08am
   
Where is the code that adds the information to the database?
David Crow 8-Jan-21 9:31am
   
Neither of the calls to addTextChangedListener() are doing anything so I would suggest removing them from your post to make it that much easier to read. You should only show relevant code.

In the InsertDataIntoSQLiteDatabase() method, what is the reference to wv.class? In that same area, why are you restarting MainActivity after inserting a record? That method should really look something like:
String username = userview.getEditText().getText().toString();
String password = passview.getEditText().getText().toString();

if (username.equals("admin") && password.equals("admin"))
{
    // SQLite query to insert data into table.
    ContentValues cv = new ContentValues();
    cv.put(sqLiteHelper.KEY_User, username);
    cv.put(sqLiteHelper.KEY_PASS, password);

    try
    {
        // Executing query.
        sqLiteDatabaseObj.beginTransaction();
        sqLiteDatabaseObj.insert(sqLiteHelper.TABLE_NAME, null, cv);
        sqLiteDatabaseObj.setTransactionSuccessful();
        sqLiteDatabaseObj.endTransaction();

        // Closing SQLite database object.
        sqLiteDatabaseObj.close();
    }
    catch(SQLException e)
    {
        android.util.Log.e(TAG, e.getMessage());
    }
}
You also might consider cleaning up the layout file (activity_main) in this post. As it is, it will not compile due to all of the syntax errors. Normally that is not a major concern, but if you've overlooked something that egregious with errors, what else has been overlooked?
Member 15038801 8-Jan-21 23:34pm
   
wv.class is my webview class ....After a login i want to start my webview ...so i am Giving like this...And suppose user enter wrong Details it will remain on MainActivity so in else i am giving call to MainActivity..
David Crow 9-Jan-21 12:14pm
   
Ignore my incorrect question about MainActvity.
Member 15038801 8-Jan-21 23:55pm
   
Thanks...Its working in my application...

Firstly, your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Secondly, you are storing the users' passwords in plain text. Don't do that. Store a salted hash of the password, using a unique salt per record, and using multiple iterations of a secure hashing algorithm.

Finally, you are currently passing a string representation of your edit controls to your SQL command. You need to pass the controls' text instead.


Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

Secure Password Authentication Explained Simply[^]
Salted Password Hashing - Doing it Right[^]
   
See also https://www.codeproject.com/KB/android/[^] for many examples of Android programming.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900