title: How to check if a user already exists in SQLite database in Android?
body: <p>I am trying to create an app which does the basic signup and login functions based on an SQLite database.</p>
  
  <p>How can I check if a user already exists? What I am trying here is, if we are trying to add duplicate user it is supposed to toast a message "USER ALREADY EXITS"</p>
  
  <p>My code:</p>
  
  <pre><code>final SQLiteDatabase database = this.openOrCreateDatabase("Users", MODE_PRIVATE, null);
  database.execSQL("CREATE TABLE IF NOT EXISTS users (uname VARCHAR UNIQUE, pword VARCHAR UNIQUE)");
  //database.execSQL("CREATE UNIQUE INDEX idx_something ON users (uname, pword)");
  signUp.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
  
          String username1 = userName.getText().toString();
          String  password1 = passWord.getText().toString();
  
          if (username1 != null &amp;&amp; !username1.trim().isEmpty() &amp;&amp; password1 != null &amp;&amp; !password1.trim().isEmpty()) {
          try {
              database.execSQL("INSERT OR REPLACE INTO users(uname, pword) VALUES('"+username1+"', '"+password1+"')");
          } catch (Exception e) {
              e.printStackTrace();
          }
  
          Toast.makeText(getApplicationContext(), passWord.getText().toString(), Toast.LENGTH_LONG).show();
          } else {
              Toast.makeText(getApplicationContext(), "Please enter details", Toast.LENGTH_LONG).show();
          }
      }
  });
  
  logIn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
          Intent intent = new Intent(MainActivity.this, secondscreen.class);
          try {
              Cursor c = database.rawQuery("SELECT * FROM users", null);
              int unameIndex = c.getColumnIndex("uname");
              int pwordIndex = c.getColumnIndex("pword");
              c.moveToFirst();
              while (c != null) {
                   {
                      String savedUname = c.getString(unameIndex);
                  String savedPword = c.getString(pwordIndex);
                       Log.i("Table Content:",savedPword.toString()+savedUname.toString());
  
                if (savedUname.equals(userName.getText().toString())) {
  
                      if (savedPword.equals(passWord.getText().toString())) {
  
                          intent.setAction(Intent.ACTION_VIEW);
                          startActivity(intent);
                      } else {
                          Toast.makeText(getApplicationContext(), " Incorrect username or password ", Toast.LENGTH_LONG).show();
                      }
                  } 
              }
                  c.moveToNext();
              }
  
          }catch (Exception e){
              e.printStackTrace();
          }
      }
  });
  </code></pre>