AsyncTask wont change the values of other variables - java

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..

Related

How can i connect my mobile app to mysql database in domain using jdbc?

I recently bought domain and hosting to godaddy.com for my thesis project under cpanel type. I already uploaded my database. However, I can not connect my mobile app to the database using Android Studio as IDE with jdbc as a connector and nox player as an emulator.
I already tried checking my database's username and password.
Here is my Connection Class
'''
public class ConnClass {
String clazz="com.mysql.jdbc.Driver";
String url="jdbc:mysql://realclinic.com/dbclinic";
//Already tried the following but none of these work
//String url="realclinic.com:3306/";
//String url="xxx.xx.xx.xxx.xx/dbclinic";
//String url="jdbc:mysql://localhost/dbclinic";
//This exact IP code run fine but only when I tested it on same device(PC)
//String url="jdbc:mysql://123.456.7.8/dbclinic";
String dbusername="clinic";
String dbpassword="951736482";
#SuppressLint("NewApi")
public Connection CONN()
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn=null;
String ConnURL=null;
try{
Class.forName(clazz);
conn= DriverManager.getConnection(url,dbusername,dbpassword);
//conn=DriverManager.getConnection(ConnURL);
}
catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
'''
And here is my main activity code
public class Login extends AppCompatActivity {
ConnClass cc;
DataClass dc=new DataClass();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
cc = new ConnClass();
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dologin dologin = new Dologin();
dologin.execute();
}
});
}
private class Dologin extends AsyncTask<String, String, String>
{
String user=txtuser.getText().toString();
String pass=txtpass.getText().toString();
String msger="Oops";
Boolean isSuccess=false;
String dataReader_user,dataReader_pass;
#Override
protected String doInBackground(String... strings) {
if(user.equals("") || pass.equals(""))
{
msger="Please fill up";
}
else
{
try{
Connection con=cc.CONN();
if(con==null)
{
msger="Please Check your Internet Connection";
}
else
{
String query="select * from parents_accts where Username='"+user+"' and Password='"+pass+"' ";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
qwer=rs.getRow();
dataReader_user=rs.getString(1);
dataReader_pass=rs.getString(2);
if(dataReader_user.equals(user) && dataReader_pass.equals(pass))
{
isSuccess=true;
msger="Log in Success";
dc.setAcct(user,pass,dataReader_lname,dataReader_fname,dataReader_mname);
}
else
{
isSuccess=false;
msger="Invalid Acct";
}
}
rs.close();
}
}
catch (Exception ex){
isSuccess=false;
msger="Exception" + ex;
}
}
return msger;
}
#Override
protected void onPostExecute(String a){
Toast.makeText(getBaseContext(),""+msger+String.valueOf(qwer),Toast.LENGTH_SHORT).show();
if(isSuccess==true)
{
Intent startIntent=new Intent(Login.this, PatientLists.class);
startActivity(startIntent);
//finish();
}
}
}
'''
The program should shift to another page once the connection is successful but it returns me "Please check your internet connection" as toast instead.
I'm really at lost here, could anyone tell me what is the right syntax for my conection string here? Thanks in advance

Mysql Connection is returning ' null ' . I am unable to connect mysql database

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

Get data from a table in sql to a textview in android studio from a specific row

I have a table in ms sql this table contains FName and FInfo i want to get th FInfo according to the FName like if the FName in the app is equal to john it gets the FInfo of john in the same row.
i have tried everything including query's and Result set but it didn't work out for me.
here is my code:
public class InsideFamily extends AppCompatActivity {
private TextView inf;
private boolean success = false; // boolean
private ConnectionClass connectionClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inside_family);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
inf = (TextView) findViewById(R.id.thefamilyinf);
connectionClass = new ConnectionClass();
SyncData orderData = new SyncData();
orderData.execute("");
}
private class SyncData extends AsyncTask<String, String, String> {
String msg = "No Data Found";
ProgressDialog progress;
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(InsideFamily.this, "Synchronising",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Connection conn = connectionClass.CONN();
if (conn == null) {
msg = "Please Check Your Connection";
success = false;
} else {
String gettingfam = getIntent().getStringExtra("defamily");
String query = "SELECT * FROM family where FName='" + gettingfam + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
inf.setText((rs.getString("FInfo")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String
msg)
{
progress.dismiss();
Toast.makeText(InsideFamily.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
} catch (Exception ex) {
}
}
}
}
}
the errors i get is that it brings a toast for me saying that "No Data Found!"
which means that that the result set equals null how can i fix it??
I found the answer
the wrong was in the query
because its nvarchar i have to wright
"SELECT * FROM family WHERE FName = (N'" +dta+ "')"
rather than
"SELECT * FROM family where FName='" + gettingfam + "'"

java.sql.SQLException: Network error IOException: failed to connect ETIMEDOUT

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.

creating a prepared statement to save values to a database

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

Categories

Resources