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.
Related
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
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 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 + "'"
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..
Hi I'm starting android development and trying to do an instant messaging/chat app.
I downloaded this source code here and trying to understand how it works. My problem is on 2 mobile devices, 1 user cannot receive the message of the other user, and vice versa, but I can see those chat message on gmail accounts. And if i type a message from gmail account browser the user who use the mobile device received the message(which made me think the problem is in "connection.sendPacket(msg);").
public class XMPPChatDemoActivity extends Activity {
public static final String HOST = "talk.google.com";
public static final int PORT = 5222;
public static final String SERVICE = "gmail.com";
public static final String USERNAME = "xxxxxxxx#gmail.com";
public static final String PASSWORD = "xxxxxxx";
private XMPPConnection connection;
private ArrayList<String> messages = new ArrayList<String>();
private Handler mHandler = new Handler();
private EditText recipient;
private EditText textMessage;
private ListView listview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
recipient = (EditText) this.findViewById(R.id.toET);
textMessage = (EditText) this.findViewById(R.id.chatET);
listview = (ListView) this.findViewById(R.id.listMessages);
setListAdapter();
// Set a listener to send a chat text message
Button send = (Button) this.findViewById(R.id.sendBtn);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String to = recipient.getText().toString();
String text = textMessage.getText().toString();
Message msg = new Message(to, Message.Type.groupchat);
msg.setBody(text);
if (connection != null) {
connection.sendPacket(msg);
messages.add(connection.getUser() + ":");
messages.add(text);
setListAdapter();
}
}
});
connect();
}
/**
* Called by Settings dialog when a connection is establised with the XMPP
* server
*
* #param connection
*/
public void setConnection(XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
}
});
}
}
}, filter);
}
}
private void setListAdapter() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.listitem, messages);
listview.setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (connection != null)
connection.disconnect();
} catch (Exception e) {
}
}
public void connect() {
final ProgressDialog dialog = ProgressDialog.show(this,
"Connecting...", "Please wait...", false);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// Create a connection
ConnectionConfiguration connConfig = new ConnectionConfiguration(
HOST, PORT, SERVICE);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPChatDemoActivity",
"Connected to " + connection.getHost());
} catch (XMPPException ex) {
Log.e("XMPPChatDemoActivity", "Failed to connect to "
+ connection.getHost());
Log.e("XMPPChatDemoActivity", ex.toString());
setConnection(null);
}
try {
// SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(USERNAME, PASSWORD);
Log.i("XMPPChatDemoActivity",
"Logged in as " + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
setConnection(connection);
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
Log.d("XMPPChatDemoActivity",
"--------------------------------------");
Log.d("XMPPChatDemoActivity", "RosterEntry " + entry);
Log.d("XMPPChatDemoActivity",
"User: " + entry.getUser());
Log.d("XMPPChatDemoActivity",
"Name: " + entry.getName());
Log.d("XMPPChatDemoActivity",
"Status: " + entry.getStatus());
Log.d("XMPPChatDemoActivity",
"Type: " + entry.getType());
Presence entryPresence = roster.getPresence(entry
.getUser());
Log.d("XMPPChatDemoActivity", "Presence Status: "
+ entryPresence.getStatus());
Log.d("XMPPChatDemoActivity", "Presence Type: "
+ entryPresence.getType());
Presence.Type type = entryPresence.getType();
if (type == Presence.Type.available)
Log.d("XMPPChatDemoActivity", "Presence AVIALABLE");
Log.d("XMPPChatDemoActivity", "Presence : "
+ entryPresence);
}
} catch (XMPPException ex) {
Log.e("XMPPChatDemoActivity", "Failed to log in as "
+ USERNAME);
Log.e("XMPPChatDemoActivity", ex.toString());
setConnection(null);
}
dialog.dismiss();
}
});
t.start();
dialog.show();
}
}
Thank you very much.