Home > Back-end >  How to check Username is already exist in the database or not sql server
How to check Username is already exist in the database or not sql server

Time:03-01

Below is my code where i want to add query and display the toast message that username is exist. First i am inserting values in the database using Asynctask method but now i don't want duplication of username. username should be unique. So when user type username it suddenly check whether it exist or not in the database and display the toast message.

package com.example.software2.bloodbankmanagement;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOError;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.AndroidRuntimeException;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public  class RegisterActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    EditText name, email, name2, password,
            contactno, Address, city, Age, username, gender;
    Button registerbtn;
    public static final int REQUEST_LOAD_IMAGE = 1;
    ImageView img;
    Button btnupload;
    TextView auth;
    byte[] byteArray;
    ProgressBar progressBar;
    String encodedImage;
    Spinner spinner;
    Connection con;
    String gender1 = "male";
    CheckBox blood;
    RadioGroup radioGroup;
    private static String value;

    public String getvalue(){
        return value;
    }
    Statement stmt;
    static boolean isAllFieldsChecked = true;

    private Context context;

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

        RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
        RadioButton gender_radio_male = (RadioButton) findViewById(R.id.Male);
        RadioButton gender_radio_female = (RadioButton) findViewById(R.id.Female);

        blood = findViewById(R.id.checkBox);
        name = (EditText) findViewById(R.id.name);
        name2 = (EditText) findViewById(R.id.name2);
        username = (EditText) findViewById(R.id.username);
        img = (ImageView) findViewById(R.id.img);
        Age = (EditText) findViewById(R.id.age);
        gender = (EditText) findViewById(R.id.gender);

        btnupload = (Button) findViewById(R.id.btnupload);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        contactno = (EditText) findViewById(R.id.contactno);
        Address = (EditText) findViewById(R.id.Address);
        progressBar.setVisibility(View.GONE);
        city = findViewById(R.id.city);
        registerbtn = (Button) findViewById(R.id.regbtn);

    

        registerbtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                city.onEditorAction(EditorInfo.IME_ACTION_DONE);
                        isAllFieldsChecked = CheckAllFields();
                new registeruser().execute("");
            }
        });
        btnupload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, REQUEST_LOAD_IMAGE);
            }
        });
    }
    @SuppressLint("NonConstantResourceId")
    public void onRadioButtonClicked(View v) {
        switch (v.getId()) {
            case R.id.Male:
                gender1 = "male";
                break;
            case R.id.Female:
                gender1 = "female";
                break;
        }
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Bitmap originBitmap = null;
            Uri selectedImage = data.getData();
            InputStream imageStream;

            try {
                imageStream = getContentResolver().openInputStream(selectedImage);
                originBitmap = BitmapFactory.decodeStream(imageStream);
            } catch (FileNotFoundException e) {
                Toast.makeText(getApplicationContext(), (CharSequence) e, Toast.LENGTH_LONG).show();
            }
            if (originBitmap != null) {
                this.img.setImageBitmap(originBitmap);
                Bitmap image = ((BitmapDrawable) img.getDrawable()).getBitmap();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
                //new DoFetchList().execute("");
                //new registeruser().execute("");

            }
        }

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // On selecting a spinner item

        final TextView textView = findViewById(R.id.auth);

            String item = parent.getItemAtPosition(position).toString();
            textView.setText(item);

    }
    public void onNothingSelected(AdapterView<?> arg0) {
    }


    public class registeruser extends AsyncTask<String, String , String>{


        String z = "";
        Boolean isSuccess = false;

        @Override
        protected void onPreExecute() {
            Toast.makeText(RegisterActivity.this,"Please wait",Toast.LENGTH_LONG).show();
 }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onPostExecute(String s) {

            Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();

        }
        @Override
        protected String doInBackground(String... strings) {

            try{
                con = connectionClass(MainActivity.ConnectionClass.un.toString(), MainActivity.ConnectionClass.pass.toString(), MainActivity.ConnectionClass.db.toString(), MainActivity.ConnectionClass.ip.toString());
                if(con == null){
                    z = "Check Your Internet Connection";
                }
                else{

                    try {
                        final TextView textView = findViewById(R.id.auth);
                        stmt = con.createStatement();
                        String sql = "INSERT INTO register (FirstName,LastName,Age,gender,Email,Username,password,contactNo,Address,city,img,bloodgrp) VALUES ('" name.getText() "','" name2.getText() "'," Age.getText() ",'" gender1.trim() "','" email.getText() "','" username.getText() "','" password.getText() "','" contactno.getText() "','" Address.getText() "','" city.getText() "','" encodedImage "','" textView.getText() "');";
                         stmt.executeUpdate(sql);

                    }
                    catch (Exception e){
                        z = "Username already exist";
                    }
                    StringBuilder result = new StringBuilder();
                    if(blood.isChecked()){
                        result.append("selected i want to be a donor");
                        result.toString().trim();
                        try {
                            stmt = con.createStatement();
                            String sql1 = "INSERT INTO DONOR (FirstName,LastName,contactNo,Address,city) VALUES ('" name.getText() "','" name2.getText() "','" contactno.getText() "','" Address.getText() "','" city.getText() "')";
                            stmt.executeUpdate(sql1);
//                            String sql2 = "insert into register (img) values ('"  encodedImage "')";
//                            PreparedStatement prstmt = con.prepareStatement(sql2);
//                            prstmt.execute();
                            Toast.makeText(RegisterActivity.this,"",Toast.LENGTH_LONG).show();

                        }
                        catch (Exception e){
                            z = "Please enter all fields and correct information";

                        }
                    }

                  //  stmt.executeUpdate(sql);


                }

            }catch (Exception e){
                z = "Please enter all fields and correct information";

                //Toast.makeText(RegisterActivity.this, "Username is already exist", Toast.LENGTH_SHORT).show();

            }

            return z;
        }
    }


    @SuppressLint("NewApi")
    public Connection connectionClass(String user, String password, String database, String server){
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        String connectionURL;
        try{
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            connectionURL = "jdbc:jtds:sqlserver://"   server "/"   database   ";user="   user   ";password="   password   ";";
            connection = DriverManager.getConnection(connectionURL);
        }catch (Exception e){
            Log.e("SQL Connection Error : ", e.getMessage());
        }

        return connection;
    }



}

CodePudding user response:

make database column unique , then this will restrict user to add duplicate data in this unique column enter image description here

For more detail click here

CodePudding user response:

There are 2 possible solutions for this,

1, write a check query to ensure whether the same data is already present in DB

like "int x = Select count(*) from register where username=" username.getText()

if x value is 0 you can insert the new record or else show the error message.

if(x==0){
// insert the values into table
}else{
// show your error message
}

2, For each successful insertion MySql returns a long value using this return value you can confirm the insertion of the data into table.

public class registeruser extends AsyncTask<String, String , String>{


        String z = "";
        Boolean isSuccess = false;

        @Override
        protected void onPreExecute() {
            Toast.makeText(RegisterActivity.this,"Please wait",Toast.LENGTH_LONG).show();
}

        @SuppressLint("SetTextI18n")
        @Override
        protected void onPostExecute(String s) {

            Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();

        }
        @Override
        protected String doInBackground(String... strings) {

            try{
                con = connectionClass(MainActivity.ConnectionClass.un.toString(), MainActivity.ConnectionClass.pass.toString(), MainActivity.ConnectionClass.db.toString(), MainActivity.ConnectionClass.ip.toString());
                if(con == null){
                    z = "Check Your Internet Connection";
                }
                else{

                    try {
                        final TextView textView = findViewById(R.id.auth);
                        stmt = con.createStatement();

                        String checkQry = "Select count(*) from register where Username=" "'" username.getText() "'";
                        int count = stmt.executeUpdate(checkQry)

                        if(count == 0){

                        String sql = "INSERT INTO register (FirstName,LastName,Age,gender,Email,Username,password,contactNo,Address,city,img,bloodgrp) VALUES ('" name.getText() "','" name2.getText() "'," Age.getText() ",'" gender1.trim() "','" email.getText() "','" username.getText() "','" password.getText() "','" contactno.getText() "','" Address.getText() "','" city.getText() "','" encodedImage "','" textView.getText() "');";
                         stmt.executeUpdate(sql);
                         }else{
                           z = "Username already exist";
                         }
                    }
                    catch (Exception e){
                        z = "Username already exist";
                    }
                    StringBuilder result = new StringBuilder();
                    if(blood.isChecked()){
                        result.append("selected i want to be a donor");
                        result.toString().trim();
                        try {
                            stmt = con.createStatement();
                            String sql1 = "INSERT INTO DONOR (FirstName,LastName,contactNo,Address,city) VALUES ('" name.getText() "','" name2.getText() "','" contactno.getText() "','" Address.getText() "','" city.getText() "')";
                            stmt.executeUpdate(sql1);
//                            String sql2 = "insert into register (img) values ('"  encodedImage "')";
//                            PreparedStatement prstmt = con.prepareStatement(sql2);
//                            prstmt.execute();
                            Toast.makeText(RegisterActivity.this,"",Toast.LENGTH_LONG).show();

                        }
                        catch (Exception e){
                            z = "Please enter all fields and correct information";

                        }
                    }

                  //  stmt.executeUpdate(sql);


                }

            }catch (Exception e){
                z = "Please enter all fields and correct information";

                //Toast.makeText(RegisterActivity.this, "Username is already exist", Toast.LENGTH_SHORT).show();

            }

            return z;
        }
    }
  • Related