Home > OS >  Check whether Username is exist in the database or not using edittext setOnFocuschangeListner
Check whether Username is exist in the database or not using edittext setOnFocuschangeListner

Time:03-10

Here is the username which is defined as Edittext I want to check when user entered the username and move to the next field ,but it generates Error

E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference

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.speech.tts.TextToSpeech;
import android.text.Editable;
import android.text.TextWatcher;
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 java.util.Locale;
import java.util.Random;

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  {
    EditText name, email, password,
            contactno, Address, city, Age, username, gender;
    Button registerbtn;
    public static final int REQUEST_LOAD_IMAGE = 1;
    ImageView img;
    Button btnupload;
    TextView status1, uid,registration;
    byte[] byteArray;
    ProgressBar progressBar;
    String encodedImage;
    Spinner spinner;
    Connection con;
    String gender1 = "male";
    CheckBox blood;
    RadioGroup radioGroup;
    private static String value;
    private TextToSpeech textToSpeech;

    public String getvalue() {
        return value;
    }

    Statement stmt,stmt1;
    static boolean isAllFieldsChecked = true;


    private Context context;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        status1 = findViewById(R.id.status1);

        username = (EditText) findViewById(R.id.username);
        username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(!b){
                    switch (view.getId()){
                        case R.id.username:
                            try{
                                stmt1 = con.createStatement();
                                String sql1 = "select Username from register where Username = '" username.getText() "'";
                                ResultSet rs = stmt1.executeQuery(sql1);
                                if(rs.next()){
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(RegisterActivity.this, "Username already exists", Toast.LENGTH_LONG).show();

                                        }
                                    });
                                }
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }

                    }
                }
            }
        });
     

        registerbtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                city.onEditorAction(EditorInfo.IME_ACTION_DONE);

                    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);
            }

        });

    }






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


        String z = "";
        Boolean isSuccess = false;

        @Override
        protected void onPreExecute() {
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "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.status1);
                        stmt = con.createStatement();
                        String sql = "INSERT INTO register(Name,Age,gender,Email,Username,password,contactNo,Address,city,img,bloodgrp,Uid) VALUES ('"   name.getText()   "',"   Age.getText()   ",'"   gender1.trim()   "','"   email.getText()   "','"   username.getText()   "','"   password.getText()   "','"   contactno.getText()   "','"   Address.getText()   "','"   city.getText()   "','"   encodedImage   "','"   textView.getText()   "',"   uid.getText()   ");";
                        stmt.executeUpdate(sql);
                        if (blood.isChecked()) {
                            String sql1 = "insert into Donor (Name,contactNo,Address,city,donor,bloodgrp,img,Uid) values ('"   name.getText()   "','"   contactno.getText()   "','"   Address.getText()   "','" city.getText() "','yes','" textView.getText() "', '"   encodedImage  "',"   uid.getText()   ")";
                            stmt.executeUpdate(sql1);
                        } else {
                            String sql1 = "insert into Donor (Name,contactNo,Address,city,donor,bloodgrp,img,Uid) values ('"   name.getText()   "','"   contactno.getText()   "','"   Address.getText()   "','" city.getText() "','no','" textView.getText() "','"   encodedImage  "',"   uid.getText()   ")";
                            stmt.executeUpdate(sql1);

                        }
                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getApplicationContext(), "Registration successful", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (Exception e) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                }
            } catch (Exception e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), e.getMessage(), 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;
    }
}

E/InputEventReceiver: Exception dispatching input event.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference
        at com.example.software2.bloodbankmanagement.RegisterActivity$19.onFocusChange(RegisterActivity.java:362)
        at android.view.View.onFocusChanged(View.java:7084)
        at android.widget.TextView.onFocusChanged(TextView.java:9754)
        at android.view.View.clearFocusInternal(View.java:6916)
        at android.view.View.unFocus(View.java:6949)
        at android.view.ViewGroup.requestChildFocus(ViewGroup.java:757)
        at android.view.View.handleFocusGainInternal(View.java:6743)
        at android.view.View.requestFocusNoSearch(View.java:11029)
        at android.view.View.requestFocus(View.java:11008)
        at android.view.View.requestFocus(View.java:10975)
        at android.view.View.requestFocus(View.java:10917)
        at android.view.View.onTouchEvent(View.java:13236)
        at android.widget.TextView.onTouchEvent(TextView.java:9813)
        at android.view.View.dispatchTouchEvent(View.java:11969)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2703)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2703)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2703)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2703)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2703)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2703)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2703)
        at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:516)
        at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1874)
        at android.app.Activity.dispatchTouchEvent(Activity.java:3453)
        at androidx.appcompat.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:69)
        at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:470)
        at android.view.View.dispatchPointerEvent(View.java:12213)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5510)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5253)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4735)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4795)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4754)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4903)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4762)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4960)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4735)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4795)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4754)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4762)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4735)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7493)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7467)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7424)
        at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7611)
        at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:186)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:325)
        at android.os.Looper.loop(Looper.java:180)

`

CodePudding user response:

stmt1 = con.createStatement();

Here con is not defined. Try initializing con first and then do this.

CodePudding user response:

From the error message, I can see you are trying to execute creteStatement() on the con variable but that is null at that point. Can't see any other code to give any other advice.

  • Related