Android Studio to SQL Server - the SQL data is not displaying - android

package com.example.connectandroid_sql;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionHelper {
String uName, pass, iP, port, database;
#SuppressLint("NewAPI") //This syntax will be able to stop the app from crashing
public Connection connectionClass() {
iP = "136.158.28.124";
database = "ExperimentTable";
uName = "sa";
pass = "admin";
port = "1433";
Connection connection = null;
String ConnectionURL = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc;jtds:sqlserver://" + iP + ":" + port
+ ";" + "databasename =" + database + ";user=" + uName
+ ";password= " + pass+ ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (Exception ex){
Log.e("Error",ex.getMessage());
}
return connection;
}
}
The SQL data is not displaying, the error I kept receiving is the
"E/Error: net.sourceforge.jtds.jdbc.Driver")
Here is my Connector Syntax
package com.example.connectandroid_sql;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
Connection connect;
String ConnectionResult ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getTextFromSQL(View v){
TextView tx1 = findViewById(R.id.textView);
TextView tx2 = findViewById(R.id.textView2);
try{
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connectionClass();
if (connect != null){
String query = "Select * from ExperimentTable";
Statement st = connect.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()){
tx1.setText(rs.getString(2));
tx2.setText(rs.getString(3));
}
}
else{
ConnectionResult = "Check Connection";
}
}
catch (Exception ex){
Log.e("Error", ex.getMessage());
}
}
}
I did create a new port "1433", I did install an older version of the JDBC Driver.
There are a few more errors that says
Invalid File Path for libcolorx-loader.so
E/Perf: perftest packageName : com.example.connectandroid_sql App is allowed to use Hide APIs
But overall it runs all good, the only problem that I am encountering is that it does not display the data.

Related

Android+mysql : Connection class returns a Null object

I am trying to connect my android login app to XAMP server(an Apache is running in local machine) through jtds jdbc. It seems the code fails to connect the server. Here's the code:
ConnectionClass.java
package com.ercess.databaseconnection;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.os.Bundle;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
public String driver = "net.sourceforge.jtds.jdbc.Driver";
String url = "jdbc:mysql://localhost/events-test";
//String url = "jdbc:mysql://127.0.0.1/events-test";
public String un = "root";
public String password = "password";
public String db = "users";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
java.sql.Connection conn = null;
String ConnURL = null;
try{
Class.forName(driver);
ConnURL = "jdbc:jtds:sqlserver://" + "127.0.0.1" +";databaseName="+ db + ";user=" + un+ ";password=" + password + ";";
conn = DriverManager.getConnection(ConnURL);
}catch (SQLException se){
Log.e("ERROR", se.getMessage());
}catch (ClassNotFoundException e){
Log.e("ERROR", e.getMessage());
}catch(Exception e){
Log.e("ERROR", e.getMessage());
}
//Log.d("conn",conn.toString());
return conn;
}
}
MainActivity.java
package com.ercess.databaseconnection;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
public class MainActivity extends AppCompatActivity {
EditText email, password;
Button login;
ProgressDialog progressDialog;
ConnectionClass connectionClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
login = findViewById(R.id.login);
connectionClass = new ConnectionClass();
progressDialog = new ProgressDialog(this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dologin dologin = new Dologin();
dologin.execute();
}
});
}
public class Dologin extends AsyncTask<String, String, String>{
String emailstring = email.getText().toString();
String passstring = password.getText().toString();
String z = "";
boolean isSuccess = false;
String em, pass;
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading...");
progressDialog.show();
super.onPreExecute();
}
protected String doInBackground(String... params){
if(emailstring.trim().equals("") || passstring.trim().equals(""))
z = "Please enter all fields........";
else
{
try{
Connection con = connectionClass.CONN();
if(con == null){
z="Please, check your internet connection....";
}else{
String query = "select * from users where user='"+emailstring+"'and password='"+passstring+"'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
em = rs.getString(0);
pass = rs.getString(1);
if(em.equals(emailstring) && pass.equals(passstring))
{
isSuccess = true;
z = "Login successful...";
}
else isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions"+ex;
}
}
return z;
}
#Override
protected void onPostExecute (String s){
Toast.makeText(getBaseContext(),""+z, Toast.LENGTH_LONG).show();
progressDialog.hide();
}
}
}
I am getting this output: "Please, check your internet connection...." .
This message should fire up only when con = null.
How to resolve?
Android does not support MySQL OR SQL Server : -
You can Use Sqllite
https://www.tutorialspoint.com/android/android_sqlite_database.htm
Or you can Access MySQL by PHP :-
https://www.tutorialspoint.com/android/android_php_mysql.htm
I faced the same problem...
The main problem is in your ConnectionClass.
String url = "jdbc:mysql://localhost/events-test";
public String un = "root";
public String password = "password";
public String db = "users";
this was your code, well, when you are using root and localhost, it's creating the check your internet connection problem. so to solve it, you have to create a new user and instead of localhost, use the IP Address of your internet.
To create new user, if you are using phpmyadmin, click the privileges tab, there you see add user option. Create user there, give all database privileges to that user and save it. Then use the username and password instead of "root"and "password".
Now to get your IP address, go to command prompt, type ipconfig, you will find ip address. In your above code, instead of localhost, type your ip address, for example,
String url = "jdbc:mysql://192.168.0.12/events-test";
And you have to give internet access in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
This should solve your problem.

jdbc driver Android studio net.sourgeforge.jtds.jdbc.Driver

I've been sitting with this problem for 2 weeks now and I hope 1 of you can help me with this.
The following code I have for connecting with out database.
package com.example.sunapp;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "xxx.xxx.xxx.xxx";
String classs = "net.sourgeforge.jtds.jdbc.Driver";
String db = "xxxx";
String un = "xxxx";
String password = "xxxx";
#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(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO1", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO2", e.getMessage());
} catch (Exception e) {
Log.e("ERRO3", e.getMessage());
}
return conn;
}
}
When I hit 'Inloggen' I get the following error
"02-19 15:15:02.679 8488-10423/com.example.sunapp E/ERRO2: net.sourgeforge.jtds.jdbc.Driver"
Below the code of the login activity of the application
package com.example.sunapp;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.os.AsyncTask;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class LoginActivity extends AppCompatActivity {
//Declaring connection
ConnectionClass connectionClass;
EditText etGebruikersnaam, etWachtwoord;
CardView cvInloggen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
connectionClass = new ConnectionClass();
final EditText etGebruikersnaam = findViewById(R.id.etGebruikersnaam);
final EditText etWachtwoord = findViewById(R.id.etWachtwoord);
final CardView cvInloggen = findViewById(R.id.cvInloggen);
final TextView RegistreerLink = findViewById(R.id.tvRegistreren);
RegistreerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registreerIntent = new Intent(LoginActivity.this, RegistryActivity.class);
LoginActivity.this.startActivity(registreerIntent);
}
});
cvInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSucces = false;
final EditText etGebruikersnaam = findViewById(R.id.etGebruikersnaam);
final EditText etWachtwoord = findViewById(R.id.etWachtwoord);
String userid = etGebruikersnaam.getText().toString();
String password = etWachtwoord.getText().toString();
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Vul hier uw gebruikersnaam en wachtwoord in";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
String query = "select * from compose.tblGebruikers where Gebruikersnaam='" + userid + "' and Wachtwoord='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next())
{
z = "Login succesfull";
isSucces = true;
}
else
{
z = "Invalid Credentials";
isSucces = false;
}
}
}
catch (Exception ex)
{
isSucces = false;
z = "Exceptions";
}
}
return z;
}
}
}
I must be doing something wrong but, what is the question. the message I'm getting comes from the classnotfoundexception. I still not managed to make it work.

Android Database Select Query - Does not show all records

Hello I am beginner to android.I want to make a database connection to mssql server in my pc. I found example on the net.
I think I have something wrong in connection. Because I have two records in my User table. But this code only gives me first record in table.
Here is ConnectionClass.java :
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "127.0.0.1:1433";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "DBAndroid1";
String un = "TestUser";
String password = "123";
#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(classs).newInstance();
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO0", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO1", e.getMessage());
} catch (Exception e) {
Log.e("ERRO2", e.getMessage());
}
return conn;
}
}
Here is my MainActivity.java.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ConnectionClass connectionClass;
EditText edtuserid, edtpass;
Button btnlogin;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.et_username);
edtpass = (EditText) findViewById(R.id.et_password);
btnlogin = (Button) findViewById(R.id.btn_Login);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String userid = edtuserid.getText().toString();
String password = edtpass.getText().toString();
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select Username from [User]";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
int columnCount = rs.getMetaData().getColumnCount();
System.out.println("Eleman sayisi: "+ columnCount);
if(rs.next())
{
String lastName = rs.getString("Username");
z = "Login successfull";
z = z + " " + lastName;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions burda mi "+ ex;
}
}
return z;
}
}
}
I hope you can help. Thank you.
You have two records in table but you are using if(rs.next()) to fetch record which will return only single record.
Use for loop or while loop to get all records and iterate resultset in loop.

(Socket Closed) exception in Android when receiving a string from python server

I am trying to communicate between my python server and android client. I setup a connection between them and that works fine, then i send a string to the server from my android app and that works fine as well. The server receives the string and then sends a string in reply to the client but at that time the my code catches an exception. The exception is "Socket Closed" and I've set the ex.getMessage() to my textView to see it.
I've set the port number 12345 for it and got a domain ijaw.ddns.net from noip.com which is live.
I've gone through stackover flow many times but cant seem to find the problem. PLease help me with this.
This is my android client code.
package com.example.ozair.ports;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//Java imports
//import android.util.Log;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends Activity{
private Button ligar;
private EditText text1;
private TextView text2;
static Socket cSocket;
static PrintWriter out;
static BufferedReader in;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ligar = (Button) findViewById(R.id.Ligar);
text1 = (EditText) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
ligar.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
connect();
}
});
}
public void connect() {
cSocket = null;
out = null;
in = null;
dis = null;
try{
cSocket = new Socket("ijaw.ddns.net",12345);
out = new PrintWriter(cSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
final String message = text1.getText().toString();
out.write(message + "\r");
out.flush()
out.close();
char[] buff = new char[1024];
int i = in.read(buff);
in.close();
out.close();
cSocket.close();
text2.setText(buff.toString());
//cSocket.close();
}
catch (IOException ex) {
//Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
text2.setText(ex.getMessage());
}
}
//
}
And this is my python server code.
#!/usr/bin/python # This is server.py file
import time
import threading
import _thread
import socket # Import socket module
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# Create a socket object
s.settimeout(1000)
host = '' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
BUFFER_SIZE = 1024
def clientthread(c):
print ('Got connection from', addr)
threadid=threading.current_thread().name
print(threadid)
data = c.recv(BUFFER_SIZE).decode()
#time.sleep(1)
c.sendall(b'Thank you for connecting')
#u = unicode(data, "utf-8")
print("received [%s]" % data)
c.close()
#print ("received data: ", data)
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
_thread.start_new_thread(clientthread,(c,))
#print 'Got connection from', addr
#c.send('Thank you for connecting')
c.close() # Close the connection
sock.close()

Python server Android client

I want to make simple communication between python server running on a pc and android client. I tested it with python client program and it worked well but in android it's not working .Here is my python server side code:
import socket
import sys
HOST = '192.168.1.102'
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'socket created'
#Bind socket to Host and Port
try:
s.bind((HOST, PORT))
except socket.error as err:
print 'Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1]
sys.exit()
print 'Socket Bind Success!'
#listen(): This method sets up and start TCP listener.
s.listen(10)
print 'Socket is now listening'
while 1:
conn, addr = s.accept()
print 'Connect with ' + addr[0] + ':' + str(addr[1])
buf = conn.recv(64)
print buf
s.close()
This is my MainActivity.java code :
package com.example.tjsiledar.sendmessage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new SendMessage().execute(editText.getText().toString());
editText.getText().clear();
}
});
}
}
and this is my SendMessage.java code :
package com.example.tjsiledar.sendmessage;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class SendMessage extends AsyncTask<String, Void, Void> {
private Exception exception;
#Override
protected Void doInBackground(String... params) {
try {
try {
Socket socket = new Socket("192.168.1.102",8888);
PrintWriter outToServer = new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()));
outToServer.print(params[0]);
outToServer.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
this.exception = e;
return null;
}
return null;
}
}

Categories

Resources