Welcome the logged in user

Asked

Viewed 183 times

-3

I am creating a database to register users, I would like that after the user shows the login in another Activity one textView with a welcome message of some data entered at the time of registration.

for example:

Welcome!
Name: Thed Alves dos Santos Santana
Registration: 12345678

follows my database.

package com.tass.login_teste.database;

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


public class DatabaseHelper extends SQLiteOpenHelper {


    private static final String DB_NAME = "login";
    private static final int DB_VERSION = 1;

    private static final String DB_TABLE = "create table user (id integer primary key autoincrement, " +
            "usuario text not null, " +
            "senha text not null, " +
            "nome_completo text not null, " +
            "matricula text not null);";


    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DB_TABLE);
    }



    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                "Upgrading databse from version" + oldVersion + "to "
                        + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS user");
        onCreate(database);
    }
}

follows the Adapter

package com.tass.login_teste.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;


public class DatabaseAdapter {
    //Table name
    private static final String LOGIN_TABLE = "user";
    //Table unique id
    public static final String COL_ID = "id";
    //Table username and password columns
    public static final String COL_USUARIO = "usuario";
    public static final String COL_SENHA = "senha";
    public static final String COL_NOME_COMPLETO = "nome_completo";
    public static final String COL_MATRICULA = "matricula";

    private Context context;
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;




    public DatabaseAdapter(Context context) {
        this.context = context;
    }



    public DatabaseAdapter open() throws SQLException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        return this;
    }



    public void close() {
        dbHelper.close();
    }



    public long criarUsuario(String usuario, String senha, String nome_completo, String matricula) {
        ContentValues initialValues = createUserTableContentValues(usuario, senha, nome_completo, matricula);
        return database.insert(LOGIN_TABLE, null, initialValues);
    }




    public boolean deleteUser(long rowId) {
        return database.delete(LOGIN_TABLE, COL_ID + "=" + rowId, null) > 0;
    }



    public boolean updateUserTable(long rowId, String usuario, String senha, String nome_completo, String matricula) {
        ContentValues updateValues = createUserTableContentValues(usuario, senha, nome_completo, matricula);
        return database.update(LOGIN_TABLE, updateValues, COL_ID + "=" + rowId, null) > 0;
    }



    public Cursor fetchAllUsers() {
        return database.query(LOGIN_TABLE, new String[] { COL_ID, COL_USUARIO,
                COL_SENHA }, null, null, null, null, null);
    }



    public Cursor fetchUser(String username, String password) {
        Cursor myCursor = database.query(LOGIN_TABLE,
                new String[] { COL_ID, COL_USUARIO, COL_SENHA },
                COL_USUARIO + "='" + username + "' AND " +
                        COL_SENHA + "='" + password + "'", null, null, null, null);

        if (myCursor != null) {
            myCursor.moveToFirst();
        }
        return myCursor;
    }




    public Cursor fetchUserById(long rowId) throws SQLException {
        Cursor myCursor = database.query(LOGIN_TABLE,
                new String[] { COL_ID, COL_USUARIO, COL_SENHA },
                COL_ID + "=" + rowId, null, null, null, null);
        if (myCursor != null) {
            myCursor.moveToFirst();
        }
        return myCursor;
    }




    private ContentValues createUserTableContentValues(String usuario, String senha, String nome_completo, String matricula) {
        ContentValues values = new ContentValues();
        values.put(COL_USUARIO, usuario);
        values.put(COL_SENHA, senha);
        values.put(COL_NOME_COMPLETO, nome_completo);
        values.put(COL_MATRICULA, matricula);
        return values;
    }
}

below follows the main

public class login extends Activity {

    public static final String MY_PREFS = "SharedPreferences";
    private DatabaseAdapter dbHelper;
    private EditText theUsername;
    private EditText thePassword;
    private Button loginButton;
    private Button registerButton;
    private Button clearButton;
    private Button exitButton;
    private CheckBox rememberDetails;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, 0);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.putLong("uid", 0);
        editor.commit();

        dbHelper = new DatabaseAdapter(this);
        dbHelper.open();

        setContentView(R.layout.login);
        initControls();
    }

    private void initControls() {
        //Set the activity layout.
        theUsername = (EditText) findViewById(R.id.Username);
        thePassword = (EditText) findViewById(R.id.Password);
        loginButton = (Button) findViewById(R.id.Login);
        registerButton = (Button) findViewById(R.id.Register);
        clearButton = (Button) findViewById(R.id.Clear);
        exitButton = (Button) findViewById(R.id.Exit);
        rememberDetails = (CheckBox) findViewById(R.id.RememberMe);

        //Create touch listeners for all buttons.
        loginButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                LogMeIn(v);
            }
        });

        registerButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Register(v);
            }
        });

        clearButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                ClearForm();
            }
        });

        exitButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Exit();
            }
        });
        //Create remember password check box listener.
        rememberDetails.setOnClickListener(new CheckBox.OnClickListener() {
            public void onClick(View v) {
                RememberMe();
            }
        });

        //Handle remember password preferences.
        SharedPreferences prefs = getSharedPreferences(MY_PREFS, 0);
        String thisUsername = prefs.getString("username", "");
        String thisPassword = prefs.getString("password", "");
        boolean thisRemember = prefs.getBoolean("remember", false);
        if (thisRemember) {
            theUsername.setText(thisUsername);
            thePassword.setText(thisPassword);
            rememberDetails.setChecked(thisRemember);
        }

    }


    private void Exit() {
        finish();
    }


    private void ClearForm() {
        saveLoggedInUId(0, "", "");
        theUsername.setText("");
        thePassword.setText("");
    }


    private void RememberMe() {
        boolean thisRemember = rememberDetails.isChecked();
        SharedPreferences prefs = getSharedPreferences(MY_PREFS, 0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("remember", thisRemember);
        editor.commit();
    }


    private void LogMeIn(View v) {
        //Get the username and password
        String thisUsername = theUsername.getText().toString();
        String thisPassword = thePassword.getText().toString();

        //Assign the hash to the password
        thisPassword = md5(thisPassword);



        Cursor theUser = dbHelper.fetchUser(thisUsername, thisPassword);
        if (theUser != null) {
            startManagingCursor(theUser);
            if (theUser.getCount() > 0) {
                saveLoggedInUId(theUser.getLong(theUser.getColumnIndex(DatabaseAdapter.COL_ID)), thisUsername, thePassword.getText().toString());
                stopManagingCursor(theUser);
                theUser.close();
                Intent i = new Intent(v.getContext(), Menu.class);
                //Intent i = new Intent(v.getContext(), teste.class);
                startActivity(i);
            }

            //Returns appropriate message if no match is made
            else {
                Toast.makeText(getApplicationContext(),
                        "Você digitou um nome de usuário ou senha incorreto.",
                        Toast.LENGTH_SHORT).show();
                saveLoggedInUId(0, "", "");
            }
            stopManagingCursor(theUser);
            theUser.close();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Erro de consulta de banco de dados",
                    Toast.LENGTH_SHORT).show();
        }


    }


    private void Register(View v) {
        Intent i = new Intent(v.getContext(), Register.class);
        startActivity(i);
    }



    private void saveLoggedInUId(long id, String username, String password) {
        SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
        SharedPreferences.Editor myEditor = settings.edit();
        myEditor.putLong("uid", id);
        myEditor.putString("username", username);
        myEditor.putString("password", password);
        boolean rememberThis = rememberDetails.isChecked();
        myEditor.putBoolean("rememberThis", rememberThis);
        myEditor.commit();
    }



    private String md5(String s) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            return s;
        }
    }
}

if anyone can give me a light I will be grateful.

2 answers

0

Whoa, that’s all right!?

You simply create a Alertdialog on the user screen, creating the following function:

    public void mensagemSucesso() {
    AlertDialog.Builder alertaLogin = new AlertDialog.Builder(this);
    alertaLogin.setMessage("Mensagem de boas vindas ao usuário")
            .setTitle("Título de boas vindas ao usuário!")
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //continue sua ação (caso deseje salvar pra nao exibir novamente, essa é a hora)
                    alertaLogin.dismiss();
                }
            });
    alertaLogin.show();
}
  • Hello Leonardo, I appreciate the help more was not quite what I intended, I already managed to resolve soon I will post the solution to the question I launched.

0

class I managed to solve my problem.

inside the login button I made the comparison with what I wanted, it was like this.

btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String usuario = edtusuario.getText().toString();
            String senha = edtsenha.getText().toString();

            if (usuario.equals("") || senha.equals("")){
                Toast.makeText(getApplicationContext(), "Preencha todos os campos", Toast.LENGTH_SHORT).show();
            }else {

                myDb = new BancoDB(Login.this);
                SQLiteDatabase db = myDb.getReadableDatabase();
                @SuppressLint("Recycle")
                //Cursor cursor=db.rawQuery("select * from user where LOGIN= '"+usuario+"'and SENHA= '"+senha+"' ",null);
                Cursor cursor = db.rawQuery("SELECT * FROM user WHERE LOGIN=? AND SENHA=?", new String[]{usuario, senha});

                if (cursor.moveToFirst()){
                    do {
                        String stData = cursor.getString(cursor.getColumnIndex("DATA"));
                        String stHora = cursor.getString(cursor.getColumnIndex("HORA"));
                        String stNome = cursor.getString(cursor.getColumnIndex("NOME"));
                        String stMatricula = cursor.getString(cursor.getColumnIndex("MATRICULA"));
                        String stLogin = cursor.getString(cursor.getColumnIndex("LOGIN"));
                        String stSenha = cursor.getString(cursor.getColumnIndex("SENHA"));

                        Bundle params = new Bundle();
                        params.putString("data", stData);
                        params.putString("hora", stHora);
                        params.putString("nome", stNome);
                        params.putString("matricula", stMatricula);
                        params.putString("usuario", stLogin);
                        params.putString("senha", stSenha);

                        Intent intent = new Intent(Login.this,MainActivity.class); // ENVIA OS DADOS DESTA TELA PARA A MAINACTIVITY.
                        intent.putExtras(params); // DADOS DE TEXTO QUE SERÁ ENVIADO.
                        startActivity(intent); // DÁ O START A INTENÇÃO.
                        finish();

                        Toast.makeText(getApplicationContext(), "Login efetuado com sucesso!", Toast.LENGTH_SHORT).show();

                    }while (cursor.moveToNext());

                }
                else {
                    Toast.makeText(getApplicationContext(), "Usuário ou Senha não confere...", Toast.LENGTH_SHORT).show();
                }

                edtusuario.setText("");
                edtsenha.setText("");

            }
        }
    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.