Can't get connection from JDBC - java

I have this class on Android Studio:
#SuppressLint("NewAPI")
public void Connect() throws Exception {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connection = null;
String S_url = null;
String driver = null;
try {
driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver);
S_url = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ pass + ";";
connection = DriverManager.getConnection(S_url);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
It's used to connect to my sql server database. Here is a problem, I can't get a connection from this class to use for PreparedStatement eventhough I can connect to my database.
I tried this code on Eclipse and it run perfectly:
My friend run this project on his Android Studio and it also work.
Edit:
This is an example:
public class Account_Control {
Connection connect;
// CONNECT DATABASE
public Account_Control(Connection connection) {
this.connect = connection;
}
public boolean CheckUsername(String username) throws Exception {
try {
PreparedStatement query = connect.prepareStatement("select Username from Account where Username = '" + username + "'");
ResultSet rs = query.executeQuery();
When i call this class on my MainActivity
private DatabaseConnection db;
private Account_Control account_control;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_login);
db = new DatabaseConnection();
try {
db.Connect();
} catch (Exception e) {
e.printStackTrace();
}
account_control = new Account_Control(db.getConnection());
db.getConnection() is not working and it return a null account_control
StackTrace:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.haitr.planed_12062016/com.example.haitr.planed_12062016.LoginActivity}:
java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.PreparedStatement java.sql.Connection.prepareStatement(java.lang.String)' on a null object reference

Related

Java Database Connection Class keeps returning Connection as Null

I have created a Public Class for my Database connection as am running various Database query's throughout the application
Every time i call the Class con always returns Null
But if i use it outside of the Class, and directly in the Activity then it connects and runs.
I have no idea why and would greatly appreciate any pointers in the right direction please.
Here are my ConnectionManager class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
static String serverName ="192.168.1.5";
static String serverPort ="1433";
static String databaseName ="DBNAME";
static String db = String.format("jdbc:jtds:sqlserver://%s:%s/%s", serverName, serverPort, databaseName);
static String un = "sa";
static String pass = "";
static Connection con;
public static Connection getConnection() {
try {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection(db, un, pass);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
}
return con;
}
}
And from within my Activity i am calling it as follow:
try {
con = ConnectionManager.getConnection();
if (con == null) {
z = "Check Your Internet Access!";
Toast.makeText(StockEnquiry.this, z, Toast.LENGTH_LONG).show();
} else {
stmt = con.createStatement();
String query = "select * from Details where ID= '1111' ";
rs = stmt.executeQuery(query);
if (rs.next()) {
String sCode = rs.getString("Short_Code");
String sDesc = rs.getString("Short_Desc");
Toast.makeText(StockEnquiry.this, (sCode + " " + sDesc), Toast.LENGTH_LONG).show();
con.close();
} else {
Toast.makeText(StockEnquiry.this,"Invalid Code!", Toast.LENGTH_LONG).show();
}
Toast.makeText(StockEnquiry.this, "Message1", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
Toast.makeText(StockEnquiry.this, "Appears to have failed in catch", Toast.LENGTH_LONG).show();
}
}
}
So the message i was getting back was: android.os.NetworkOnMainThreadException'
After some digging i believe i am facing the issue because i am not running it as a asynchronous task.
Its possible to remove this restriction
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
So the connection class would look like the following.
import android.os.StrictMode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
static StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
static String serverName ="192.168.1.1";
static String serverPort ="1433";
static String databaseName ="DatabaseName";
static String db = String.format("jdbc:jtds:sqlserver://%s:%s/%s", serverName, serverPort, databaseName);
static String un = "Username";
static String pass = "Password";
static Connection con;
public static Connection getConnection() {
try {
try {
StrictMode.setThreadPolicy(policy);
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection(db, un, pass);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
}
return con;
}
}
Calling the code from within the activity is untouched from the original post.
As a knock-on effect from this, You may get Application Crash / Lock-ups or slowness on poor network connection / coverage.
So its a bit of a sacrifice, but can be handled in other ways.

Can't connect to SQL Database (Java, Android Studio)

I have imported the JDBC library, set it to be compiled, and gave the App permission to access Internet.
When a button on Screen is pressed, it should connect to the database and give me the values to implement in the list.
When I press the button, I can see it giving me the "Connecting to database" text, but after about half a second it says "Exception" as defined in that last catch block.
I commented out the three lines of code in onPostExecute, because when I kept them the App would just crash.
public void retrieveData(View view) {
GetData retrieveData = new GetData();
retrieveData.execute();
}
private class GetData extends AsyncTask<String,String,String> {
String msg = "";
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://" + DbStrings.DATABASE_URL + "/" + DbStrings.DATABASE_NAME;
#Override
protected void onPreExecute() {
progress.setText("Connecting to database");
}
#Override
protected String doInBackground(String... strings) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD);
stmt = conn.createStatement();
String sql = "SELECT * FROM video"; //
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String name = rs.getString("title");
buildNames += name + " ### ";
}
msg = "Process complete.";
rs.close();
conn.close();
stmt.close();
} catch(SQLException connError) {
msg = "An exception was thrown for JDBC.";
connError.printStackTrace();
} catch (ClassNotFoundException e) {
msg = "A Class not found exception was thrown.";
e.printStackTrace();
} catch (java.sql.SQLException e) {
msg = "Exception";
e.printStackTrace();
} finally {
try{
if(stmt != null) {
stmt.close();
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
try{
if(conn != null) {
conn.close();
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String msg) {
progress.setText(this.msg);
//names = buildNames.substring(0,buildNames.length()-5).split(" ### ");
//itemAdapter = new ItemAdapter(thisContext, buildNames.substring(0,buildNames.length()-5).split(" ### ")); //crashes
//namesList.setAdapter(itemAdapter);
}
}
}
After checking the stack trace I found this:
java.sql.SQLException: Unknown initial character set index '192' received from server.
And so I knew what to search for;
I was using an outdated version of JDBC, (3.x). After importing Version 5.1.46, it is now working :).

net.sourceforge.jtds.jdbc.jtdsresultset#1245 gives output for select itemname from oitm where itemcode='dcs1515' on android

I had developed an android app to connect with MS-sql database it is connected but it does not get correct result it gives
net.sourceforge.jtds.jdbc.jtdsresultset#1245
as result for select itemname from oitm where itemcode='dcs1515'
Please help me to solve this issue. I am using android studio-3.1.0 and ms-sql 2008. I connected android with db using jtds-1.3.1.jar for jdbc connection
class Disp extends AsyncTask<String, String, String> {
#Override
protected void onPostExecute(String s) {
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... strings) {
connect con = new connect();
String k=null;
ct = con.connectionclass();
if (ct == null){
k="Check Internet";
}
else{
try {
String st = "select itemname from oitm where itemcode='dcs1515'";
Statement smt = ct.createStatement();
ResultSet resultSet = smt.executeQuery(st);
if(resultSet.next())
{
k = resultSet.toString();//"success ";//+resultSet+" deleted";
}
} catch (SQLException e) {
k=e.getMessage();
}
}
return k;
}
}
}
connection class is
public class connect {
String ip = "192.167.0.7";
String db = "RCCLive";
String un = "artika";
String pass = "Acm#157";
public Connection connectionclass()
{
{
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://" + ip + ";" + db + ";user=" + un+ ";password=" + pass + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
}
k = resultSet.toString();
This should be
k = resultSet.getString(1);
You cannot just take the String value of the ResultSet, you must retrieve the first column of the ResultSet, which is what getString(1) does.

android with JDBC. createStatement() does not exist?

I am trying to create a connection with a database using JDBC on my android project. I am following a tutorial which says to import a jar and then create a connection in the activity. Everything is ok, but in the connection statement i get an error
Cannot resolve method 'createStatement()'
if I try to get into the reference of the method, it says
cannot find decleration to go to
This method comes from the jar i have imported? (jtds-1.3.1)
Is there anything else i am missing here?
#Override
protected String doInBackground(String... params)
{
Connection con;
String usernam = params[0];
String passwordd = params[1];
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
// Change below query according to your own database.
String query = "select * from owner where mail = '" + usernam.toString() + "' and password = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
}
else
{
z = "Invalid Credentials!";
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)
{
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 + ";user=" + user+ ";password=" + password + ";";
connection = (Connection) DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
I got the same problem with the close() method
All you've got to do is specify the class name fully:
java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/product","root","");
No need for a cast, and the error you're reporting will now go away, as the compiler will be looking for the method in the right class.
Or just rename your own class Connection.

Error using JDBC "java.lang.NullPointerException" [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I get error on
java.lang.NullPointerException: Attempt to invoke interface method
'java.sql.Statement java.sql.Connection.createStatement()' on a null
object reference at
com.example.jacquesarroyo.onlinelibrary.suggestions$3.onClick(suggestions.java:81)
Here's the code I used:
add = (Button) findViewById(R.id.btnadd);
errorlbl = (TextView) findViewById(R.id.lblerror);
title = (EditText) findViewById(R.id.txttitle);
author = (EditText) findViewById(R.id.txtauthor);
year = (EditText) findViewById(R.id.txtyear);
location = (EditText) findViewById(R.id.txtlocation);
ipaddress = "10.0.0.5";
db = "SampleDatabase";
username = "admin"
password = "admin";
connect = ConnectionHelper(username, password, db, ipaddress);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
st = connect.createStatement();
preparedStatement = connect
.prepareStatement("Insert into Books(Title,Author,Year) values ('"
+ title.getText().toString()
+ "','"
+ author.getText().toString()
+ "','"
+ year.getText().toString() + "')");
preparedStatement.executeUpdate();
errorlbl.setText("Data Added successfully");
} catch (SQLException e) {
errorlbl.setText(e.getMessage().toString());
}
}
});
#SuppressLint("NewApi")
private Connection ConnectionHelper(String user, String password,
String database, String server) {
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 + ";"
+ "databaseName=" + database + ";user=" + user
+ ";password=" + password + ";" + "ssl=false";
connection = DriverManager.getConnection(ConnectionURL);
} catch (SQLException se) {
Log.e("ERROR", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERROR", e.getMessage());
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
return connection;
}
line 81 is: st = connect.createStatement();
NullPointerException means that the variable you are trying to use is not initialized or is null.
Before calling:
connect.createStatement();
you have to initialize the connect object first by:
Connection connect = ConnectionHelper(user,password,database,server);
Keep in mind scope of the variables.

Categories