Im trying to create a prepared statement so that when i click a button it saves a users username and password to a database for them to be able to login. But i have no idea how to do this. Any pointers? Below is my code:
public class Register extends AppCompatActivity {
EditText username, password;
Button registartion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
private Connection getConnection()
{
String host = "jdbc:mysql://jdbc.fmc.me.uk:3306/db_ben";
String u = "user_ben";
String p = "********";
try
{
Connection con = DriverManager.getConnection(host, u, p);
return con;
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private boolean registerUser(){
//Get username
EditText regUsernameBox = (EditText) findViewById(R.id.RegUsername);
String regUsernameStr = regUsernameBox.getText().toString();
//Get password
EditText regPasswordBox = (EditText) findViewById(R.id.RegPassword);
String regPasswordStr = regPasswordBox.getText().toString();
System.out.println(regUsernameStr);
System.out.println(regPasswordStr);
return false;
}
public void buttonClick() {
final Button registerUsers = (Button) findViewById(R.id.bRegister);
registerUsers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerUser();
}
});
}
}
I've provided a example for you. You can set variables on the places where a question mark is in the query string. The index of these start with 1, not 0!
String query = "INSERT INTO User (Username, Password) VALUES (?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, regUsernameStr.toLowerCase());
ps.setString(2, regPasswordStr));
if (ps.executeUpdate() == 1) {
return true;
} else {
return false;
}
Furthermore, you should save the username as all lowercase, so you can check easier when checking the login. And you should allways hash the users password before saving it to the database!
You should not use JDBC on android, as it takes more data to communicate to the server. Best practice is to build a php api, which returns the data you want as JSON. However, if data isn't a big issue for now, you can still use JDBC.
This is how you do it.
private boolean registerUser(){
//Get username
EditText regUsernameBox = (EditText) findViewById(R.id.RegUsername);
String regUsernameStr = regUsernameBox.getText().toString();
//Get password
EditText regPasswordBox = (EditText) findViewById(R.id.RegPassword);
String regPasswordStr = regPasswordBox.getText().toString();
System.out.println(regUsernameStr);
System.out.println(regPasswordStr);
int i = 0;
Connection con = getConnection();
try {
PreparedStatement pst = con.prepareStatement("insert into users values(?,?)");
pst.setString(1, regUsernameStr);
pst.setString(2,regPasswordStr);
i = pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
if(i>0)
return true;
return false;
}
Related
I'm a new about Android Studio and I'm trying to develop a simple app with jdbc to connect Oracle database. The connection works fine and I can show a table with values. Now I'm looking for a way to show a value from DB using an input value, but when I push the button, I receive an sqlexception and the app collapses.
public class MainActivity extends AppCompatActivity {
private TextView textViewConn;
private Button buttonView;
private EditText codUser;
private TextView typeApi;
private Statement stmt;
private Statement stmt1;
private PreparedStatement pstmt;
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:#XXXXXXXXXXXXXXXX";
private static final String DEFAULT_USERNAME = "XXXXXXX";
private static final String DEFAULT_PASSWORD = "XXXXXXX";
private Connection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
textViewConn = findViewById(R.id.textView2);
buttonView = findViewById(R.id.button);
codUser = findViewById(R.id.editTextTextPersonName);
typeApi = findViewById(R.id.textView4);
try {
this.connection = createConnection();
Toast.makeText(MainActivity.this, "Connected",
Toast.LENGTH_SHORT).show();
stmt=connection.createStatement();
textViewConn.setText("Database connected");
TableLayout stk = (TableLayout) findViewById(R.id.table_main);
TableRow tbrow0 = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setText(" Code ");
tv0.setTextColor(Color.WHITE);
tbrow0.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setText(" User ");
tv1.setTextColor(Color.WHITE);
tbrow0.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(" Password ");
tv2.setTextColor(Color.WHITE);
tbrow0.addView(tv2);
/* TextView tv3 = new TextView(this);
tv3.setText(" Stock Remaining ");
tv3.setTextColor(Color.WHITE);
tbrow0.addView(tv3);*/
stk.addView(tbrow0);
ResultSet rs=stmt.executeQuery("select FEC_CODICE, FEC_IX_USERNAME, FEC_IX_PASSWORD from FE_CONTROL");
while(rs.next()) {
TableRow tbrow = new TableRow(this);
TextView t1v = new TextView(this);
t1v.setText(rs.getString(1));
t1v.setTextColor(Color.WHITE);
t1v.setGravity(Gravity.CENTER);
tbrow.addView(t1v);
TextView t2v = new TextView(this);
t2v.setText(rs.getString(2));
t2v.setTextColor(Color.WHITE);
t2v.setGravity(Gravity.CENTER);
tbrow.addView(t2v);
TextView t3v = new TextView(this);
t3v.setText(rs.getString(3));
t3v.setTextColor(Color.WHITE);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
stk.addView(tbrow);
}
stmt.close();
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//this.connection = createConnection();
Toast.makeText(MainActivity.this, "Connected",
Toast.LENGTH_SHORT).show();
//stmt=connection.createStatement();
String code=codUser.getText().toString();
//ResultSet rs1=stmt1.executeQuery("select FEC_IX_VERSIONE from FE_CONTROL FEC_CODICE = 'Z'");
pstmt= connection.prepareStatement("select FEC_IX_VERSIONE from FE_CONTROL FEC_CODICE = ?");
pstmt.setString(1,code);
pstmt.execute();
ResultSet rs1=pstmt.getResultSet();
while(rs1.next()){
typeApi.setText(rs1.getString(1));
}
pstmt.close();
} catch (SQLException throwables) {
typeApi.setText(throwables.getmessage());
}
}
});
//connection.close();
}
catch (Exception e) {
/*Toast.makeText(MainActivity.this, ""+e,
Toast.LENGTH_SHORT).show();*/
textViewConn.setText(e.getmessage());
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static Connection createConnection() throws ClassNotFoundException, SQLException {
return createConnection(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
}
}
I'm using the debugger to check the exception but the debug line doesn't go into tis method buttonView.setOnClickListener(new View.OnClickListener()
and I noticed that the app runs without to show the tableview and button, textview, etc, during the debug mode. I can't understand when they run.
Can anyone give some idea?
I have added mysql connector.jar file as well, in my project, and I have tried out every possible thing to connect my database with android application. Whenever I click on submit button my application stops running. I have debugged my progam and I am continously receiving null in mystat and mycon. Please help me out!
public class Background extends AsyncTask {
Connection mycon ;
Statement mystat;
ResultSet rs ;
String db = " student";
String pass = "wardakhan11";
String dburl = "jdbc:mysql://localhost:3306/demo";
String user = "root";
#Override
protected Object doInBackground(Object[] objects) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
mycon = DriverManager.getConnection(dburl,user,pass);
mystat = (Statement) mycon.createStatement();
System.out.println("inserting");
} catch (Exception e) {
e.printStackTrace();
}
try {
int rowsaffect;
mystat.executeUpdate("insert into student" + "(name , rollno) " +
"values " + "('sammi' ,ce12145)" );
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
this is my other class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText email = (EditText) findViewById(R.id.email);
EditText password = (EditText) findViewById(R.id.password);
Button submit = (Button) findViewById(R.id.login_submit_button);
ImageButton fornback = (ImageButton)findViewById(R.id.registration_button);
System.out.println("Before");
final Background obj1 = new Background();
String s = " abcbcnccdc";
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
obj1.execute(this);
// obj1.doInBackground(this);
// obj1.OnpostExecute();
}
});
I am developing an Android application where I have a login view and I would like to check if the ResultSet returns with no match, to write an alert text under the button. But as I heard ResultSet never returns with null value. So what should I use? Here is my short code:
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> users = new ArrayList<String>();
final String getUser = "SELECT username FROM userList WHERE username=?";
try {
pst = conn.prepareStatement(getUser);
pst.setString(1, String.valueOf(txtUsername));
rs = pst.executeQuery();
while (rs.next()) {
if(rs == null) { //change this line
txtAlert.setText("ERROR: No match!");
}
else {
users.add(rs.getString("username"));
}
}
final String getUserName = users.get(1);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
You could check what you've added
while (rs.next()) {
users.add(rs.getString("username"));
}
if (users.isEmpty()) {
// not found!
}
I am developing an android app in which I have to connect android application with SQL server database in order to authenticated the user with their username and password. I have used the jtds library in order to provide Sql connection to android.Below is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText username,password;
CheckBox mCbShowPwd;
Connection con;
String un,pass,db,ip,in;
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username_edtext);
password = (EditText) findViewById(R.id.passwd_edtext);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
t = (TextView) findViewById(R.id.text);
final Button forget_btn = (Button) findViewById(R.id.forget_btn);
forget_btn.setOnClickListener(this);
final Button login_btn = (Button) findViewById(R.id.login_button);
login_btn.setOnClickListener(this);
ip = "172.16.0.**";
in="********";
db = "*******";
un = "****";
pass = "****";
mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
password.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.forget_btn:
{
Intent intent=new Intent("com.example.pc.uowv1.ForgetPassActivity");
startActivity(intent);
break;
}
case R.id.login_button:
{
CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
checkLogin.execute("");
break;
}
}
}
public class CheckLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String usernam = username.getText().toString();
String passwordd = password.getText().toString();
#Override
protected void onPreExecute()
{
//progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r)
{
Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess)
{
Toast.makeText(MainActivity.this , "Login Successfull" , Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params)
{
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip,in);
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
String query = "select * from Login where username= '" + usernam.toString() +"'and password='"+passwordd.toString()+"'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
//mApp.setmGuser(usernam);
z = "Login successful";
isSuccess=true;
con.close();
Intent intent=new Intent(MainActivity.this,MAin2Activity.class);
intent.putExtra("username",usernam.toString());
startActivity(intent);
}
else
{
z = "Invalid Username and password!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server,String instance)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + "/"+ database+";instance=" + instance + ";user=" + user+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
t.setText(se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
t.setText(e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
t.setText(e.getMessage());
}
return connection;
}
}
The Code works on same network but when I connect to other network in my android device it throws
Exception E/error here 1 :: Network error IOException: failed to
connect to /172.16.0.** (port 1433): connect failed: ETIMEDOUT
(Connection timed out).
IMНO you have chosen the wrong way. Do not use the connection to the SQL server from Android. It is necessary to make a web service on the SQL server's side and use this web service from Android. JDBC drivers are not designed to work in mobile networks.
i am making an android app that uses jdbc to connect to a database, jdbc needs AsyncTask, i read a tutorial about it but, i have all kinds of troubles !
code :
// login stuff
Button Login;
EditText Username, Password;
String db_username, db_password;
// database variables
Database d;
ResultSet rs;
Statement stmt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
getActionBar().hide();
// defining stuff
Login = (Button) findViewById(R.id.login);
Username = (EditText) findViewById(R.id.username);
Password = (EditText) findViewById(R.id.password);
db_password = "-1";
// focus on the enter username
Username.requestFocus();
Login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// checking for the password and stuff
Con deploy = new Con();
deploy.execute();
// waiting until data is back
while (db_password.equals("-1")){
}
// checking the entered password
if (db_password.equals(Password.getText())) {
Intent i = new Intent(Login.this, Manager.class);
i.putExtra("name", db_username);
startActivity(i);
finish();
}
}
});
}
// connection class
private class Con extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
d = new Database();
d.connect();
try {
// putting the username and pass in the result set
stmt = d.createStatement();
rs = stmt
.executeQuery("SELECT username,password from users WHERE username='"
+ Username.getText() + "'");
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try {
if (rs.next()) {
db_username = rs.getString("username");
db_password = rs.getString("password");
System.out.println("check point");
System.out.println(db_password);
db_password = "0";
} else {
Username.setText("");
Password.setText("");
db_password = "0";
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
super.onPostExecute(result);
}
}
after testing i figured, inside the thread the value changes as in the database, but on the main thread the two variables db_username db_password never changes !
i made these variables static but didnt work , please help
Solved : i used this instead of AcyncTask and solved everything:
new Thread(new Runnable() {
public void run() {
}).start();
private class Con extends AsyncTask<Void, Void, ResultSet > {
#Override
protected ResultSet doInBackground(Void... params) {
d = new Database();
d.connect();
ResultSet rs;
try {
// putting the username and pass in the result set
Statement stmt = d.createStatement();
rs = stmt
.executeQuery("SELECT username,password from users WHERE username='"
+ Username.getText() + "'");
} catch (Exception e) {
return new ResultSet(); // depends on what you want to do on error
}
return rs;
}
#Override
protected void onPostExecute(ResultSet result) {
super.onPostExecute(result);
try {
if (result.next()) {
db_username = result.getString("username");
db_password = result.getString("password");
System.out.println("check point");
System.out.println(db_password);
// db_password = "0"; this always makes it zero at the end of the day
} else {
Username.setText("");
Password.setText("");
db_password = "0";
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
Edit also change this if (db_password.equals(Password.getText().toString())) { its in your onclick listener
use this asnyc ayt.. check closing tags and stuff..