by clicking a button, i want to execute a select query to show some results,i used the Internet permission and the AsyncTask and the address ip of my PC to perform this call but it didn t work for me,Also the Log doesn't show me Anything to figure out the issue,this is the code:
in Manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
Android programm:
package com.ammach.oraclecon;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
class Task extends AsyncTask<Void,Void,String>{
#Override
protected String doInBackground(Void... params) {
String param="mal9a walou";
String driver="oracle.jdbc.driver.OracleDriver";
String bd="ORCL";
String user="SYSTEM";
String passwd="SYSTEM";
String port="1521";
String ip="192.168.1.7";
String url="jdbc:oracle:thin:#"+ip+":"+port+":"+bd;
Connection con=null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, passwd);
Log.e("coooon", "coooon");
Statement st=con.createStatement();
Log.e("Statement", "Statement");
ResultSet resultSet = st.executeQuery("select * from auteur");
Log.e("ResultSet", "ResultSet");
Log.e("con", "You made it, take control your database now!");
if(resultSet.next()){
param=resultSet.getString("nom");
Log.e("dkhal", "rah dkhal");
}else{
Log.e("walou", "walou");
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return param;
}
#Override
protected void onPostExecute(String param) {
super.onPostExecute(param);
textView.setText(param);
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT).show();
}
}
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.txt);
}
public void fetchOracle(View view) {
new Task().execute();
Toast.makeText(MainActivity.this, "starting", Toast.LENGTH_SHORT).show();
}
}
i Also run the same procedure in a simple java project(void main) in Netbeans, and it works perfectly,i tried so many times the Android application but i failed ,could someone help me to solve this issue.
this is the java programm:
String param = "nothing";
String driver = "oracle.jdbc.driver.OracleDriver";
String bd = "ORCL";
String user = "SYSTEM";
String passwd = "SYSTEM";
String port = "1521";
String ip = "localhost";
String url = "jdbc:oracle:thin:#" + ip + ":" + port + ":" + bd;
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, passwd);
Statement st = con.createStatement();
ResultSet resultSet = st.executeQuery("select * from auteur");
if (resultSet.next()) {
param = resultSet.getString("nom");
} else {
System.out.println("no result");
}
System.out.println("nom: "+param);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
Your catch clause with the only statement e.printStackTrace(); makes the trick. It just swallows the exception and you, of course, unable to see it. It is much better to use the Log class to report the caught exception. Insert there something like Log.e("tag", e.toString()); and you'll see the problem.
Next you should always close all the resources you have used. In your case it's the Connection, the Statement and the ResultSet. The correct place to close them is in your (missed) finally clause.
But anyway, if you want to work with Oracle from Android device then you should ensure the network 192.168.1.* is reachable from your device and the address (192.168.1.7) at least can be pinged successfully (from your device). Have you managed to somehow test the connection? And there can be much more reasons to get an exception (which is silently swallowed in your code), it means the first thing you should do is to change your code and to log exception properly. Next it can be a missing JDBC driver library, it can be a network configuration problem which makes the database unreachable (most probable), it can be the problem on the side of the Oracle if you have no permission to read from "auteur", etc.
Related
I've made a SQL Server and managed to form a database. Implemented everything in my Android Studio app and opened the app on my phone.
When I access the database from the same WiFi network where the database is formed, everything works, but when I access the database from another WiFi network I get the exception:
java.sql.SQLException: Network error IOException: Host unreachable
Can you make the server accessible from every other network apart from the network that the database is connected to? Or do I have to do something else to make it accessible from everywhere?
Things I've already done:
Every SQL services are up and running.
Shared Memory, Named Pipes and TCP/IP are enabled.
Remote server connections is Allowed on my database.
New account is created (I don't use the sa account).
I've made an exception in the firewall for the port (1433).
I will add the code from my app if that helps in any way.
import android.Manifest;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
TextView moreGames;
String b;
private static String ip = "xxx.xxx.x.x";
private static String port = "1433";
private static String Classes = "net.sourceforge.jtds.jdbc.Driver";
private static String database = "xxxx";
private static String username = "xxxxxx";
private static String password = "xxxx";
private static String url = "jdbc:jtds:sqlserver://" + ip + ":" + port + "/" + database;
private Connection connection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
moreGames = findViewById(R.id.moreGames);
ActivityCompat.requestPermissions(this, new String[]{(Manifest.permission.INTERNET)}, PackageManager.PERMISSION_GRANTED);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Class.forName(Classes);
connection = DriverManager.getConnection(url, username, password);
moreGames.setText(R.string.NewGame);
} catch (ClassNotFoundException e){
e.printStackTrace();
Toast.makeText(this, "Error somewhere.", Toast.LENGTH_SHORT).show();
} catch (SQLException e){
b = String.valueOf(e);
Toast.makeText(this, b, Toast.LENGTH_LONG).show();
}
I've recently tried to connect Android Studio with an OracleDB through ojdbc driver without success.
I'm using ojdbc8.jar, Oracle Database 19c and jdk1.8.0_241 on Windows10.
I tried to do the exact same thing with the same code and components in Intellij and everything went well.
When I try to connect to the database I received the following error:
see_error_print "java.lang.NoClassDefFoundError: Failed resolution of: Ljava/sql/DriverAction;" in the line Class.forName.
I have installed Android 28 and my gradle version is 3.6.2.. I tried to clean project, and invalidate caches/restart, but nothing seems to work.
In fact, in Android28 (Sdk) at java.sql, indeed the missing file isn't there, but exists in jdk.
I appreciate any help I can get, thank you!
P.S.: english is not my mother language, sorry if there are any mistakes.
Here is the code I used:
package com.lamtias.isplit.ActivityLogin;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import com.lamtias.isplit.Logic.ISplit;
import com.lamtias.isplit.R;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class SignUpActivity extends AppCompatActivity {
private ISplit iSplit;
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:#localhost:1521:ISplitDB";
private static final String DEFAULT_USERNAME = "c##marcia";
private static final String DEFAULT_PASSWORD = "marcia";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
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);
}
JDBCexample(DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
}
public static void JDBCexample(String dbid, String userid, String passwd)
{
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:ISplitDB", userid, passwd);
if(conn!=null)
System.out.println ("oiiiiiiiiiiiiiiiiiiiiiiiiiiii");
else
System.out.println ("oeeeeeeeeeeeeeeeeeeeeeeeeeeee");
Statement stmt = conn.createStatement();
//stmt.executeUpdate( "insert into users values ('1', 'Perryridge')");
stmt.close();
conn.close();
}
catch (SQLException sqle) {
System.out.println("SQLException : " + sqle);
} catch (Exception e){
System.out.println("Exception : " + e);
}
}
}
I have fixed the same problem using ojdbc8.jar from Oracle OJDBC 18.3:
https://www.oracle.com/database/technologies/appdev/jdbc-ucp-183-downloads.html
I am new to Java and Servlet Programming. I am trying to host a simple application which is working successfully in localhost. but when i host it to Openshift, it says No suitable driver found for jdbc:mysql://127.12.204.2:3306/shifar .
All i want to do is to save a string into the database.
Here is my code
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String
HOST = System.getenv("OPENSHIFT_MYSQL_DB_HOST"),
PORT = System.getenv("OPENSHIFT_MYSQL_DB_PORT"),
USERNAME = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME"),
PASSWORD = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD"),
DB_NAME = "shifar";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("userName");
PrintWriter pw = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
pw.println("Error while loading driver: "+e.getMessage());
}
try {
String url = "jdbc:mysql://" + HOST + ":" + PORT +
"/" + DB_NAME;
Connection con = DriverManager.getConnection(url, USERNAME, PASSWORD);
PreparedStatement prep = con.prepareStatement("INSERT INTO names (name) VALUE (?)");
prep.setString(1, name);
int rc = prep.executeUpdate();
pw.println("Name saved !:"+name+" # "+ rc);
} catch (SQLException e) {
pw.println("Error while connecting: "+e.getMessage());
}
}
}
I can't figure out the error :(. The deployment of the application is done through Git as .WAR
Live Preview - (Enter something in the edittext and submit)
Your servlet container needs access to the jar file its way. For instance Tomcat might want something like mysql-connector-java-5.1.35-bin.jar
in the web-inf folder under the application. You need to focus on your classpath and the setup of your servlet container, regardless of what that is.
If you need further assistance hang a question under this with more details.
I am a beginner to Android Eclipse. However, I have a project to do an Android application. I am unable to connect to the Android emulator using the MySQL connector to create a login page. Am I missing an important file?
Loginpage
package com.example.logininterface;
import com.example.logininterface.R.menu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtUserName = (EditText)this.findViewById(R.id.txtUname);
txtPassword = (EditText)this.findViewById(R.id.txtPwd);
btnLogin = (Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if ((txtUserName.getText().toString()).equals(txtPassword.getText().toString())) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this, "Invalid Login", Toast.LENGTH_LONG).show();
}
}
});
}
}
MySQLConn
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Main {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mobiledb", "teddy", "password");
PreparedStatement statement = con.prepareStatement("select * from androidlogin");
ResultSet result = statement.executeQuery();
while(result.next())
{
System.out.println(result.getString(1) + "" + result.getString(2));
}
}
}
I don't think accessing any database directly from the Android layer is a good idea. It would be better if you could pass required parameters to a server page (PHP, JSP, etc.) and database connections could be done from server pages.
Coming to your question, localhost means Android in this case, so it will be looking for a MySQL database inside your emulator. Instead, you need to use your computer's IP address. Go to a terminal and type ipconfig or ifconfig if you are on *nix/Macintosh machine to get the IP address.
I suggest to use JSON with PHP to connect to the MySQL database. It is just an opinion.
It is better that you use JSON to communicate with the PHP script and within the PHP script to communicate with your localhost MySQL database. And you may try this to connect to your PHP script.
Example:
public class Login {
...
private static final String LOGIN_URL = "http://XXX.XXX.X.XX/Example/login.php";
...
// Invoke by Intent activity by Login class
class AttemptLogin extends AsyncTask<String, String, Integer> {
...
protected void onPreExecute() {
....
}
protected Integer doInBackground() {
....
// Getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
....
}
protected void onPostExecute() {
....
}
}
The XXX.XXX.X.XX is the local IP address of your computer, which means when your mobile is connected on the same network as your computer, the IP address is the computer local IP address. Do not put in localhost. It won't work.
Instead of using "Localhost" use 10.0.2.2. Hope it helps!
am successfully finished login form in android using mysql connection via jdbc in java...its successfully worked in my localhost...but development site its not worked...the following error is displyed.
java.sql.SQLException: Unable to connect to any hosts due to exception: java.net.SocketException: java.net.ConnectException: Connection timed out: connect
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.net.ConnectException: Connection timed out: connect
STACKTRACE:
java.net.SocketException: java.net.ConnectException: Connection timed out: connect
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:143)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:225)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1805)
at com.mysql.jdbc.Connection.<init>(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.retrieve.retrieve.main(retrieve.java:15)
** END NESTED EXCEPTION **
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1875)
at com.mysql.jdbc.Connection.<init>(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.retrieve.retrieve.main(retrieve.java:15)
why dis error is occurred.give me some solutions.
if am running localhost means my sql query is
package com.example.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginLayoutActivity extends Activity {
EditText username,password;
TextView error;
Button ok;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username=(EditText)findViewById(R.id.et_un);
password=(EditText)findViewById(R.id.et_pw);
error=(TextView)findViewById(R.id.tv_error);
ok=(Button)findViewById(R.id.btn_login);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable user = username.getText();
Editable pass = password.getText();
try {
**Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/people", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT password FROM customers where login='"+user+"'");**
if(rs.next())
{
String dbpass = rs.getString(1);
if(dbpass.equals(pass)){
error.setText("Correct Username or Password");
}
else
{
error.setText("Sorry!! Incorrect Username or Password");
}
}
}
catch (SQLException e) {
username.setText(e.toString());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
if am running development site means my query is:
package com.example.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginLayoutActivity extends Activity {
EditText username,password;
TextView error;
Button ok;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username=(EditText)findViewById(R.id.et_un);
password=(EditText)findViewById(R.id.et_pw);
error=(TextView)findViewById(R.id.tv_error);
ok=(Button)findViewById(R.id.btn_login);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable user = username.getText();
Editable pass = password.getText();
try {
**Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://dev.xxxxx.com/xxx", "xxxx", "xxxx");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT password FROM customers where login='"+user+"'");**
if(rs.next())
{
String dbpass = rs.getString(1);
if(dbpass.equals(pass)){
error.setText("Correct Username or Password");
}
else
{
error.setText("Sorry!! Incorrect Username or Password");
}
}
}
catch (SQLException e) {
username.setText(e.toString());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
dis development site username,password,database name and url all r correct only...then why dis error is occured....give me solutions...
If you are trying to connect your mysql in the localhost from an android application, it may not get communication, refer this.
This exception seems like the mysql doesn't have public access.
Make your mysql available in a remote system and give the remote system's ip. Let 192.168.1.102 be its ip, then change this statement as jdbc:mysql://192.168.1.102:3306/people.
You have to modify the mysql configuration file. It may be /etc/mysql/my.cnf (in linux) or \xampp\mysql\bin\my.ini (depends on mysql refer more).
By default it contains bind-address = 127.0.0.1, change it as bind-address = 0.0.0.0. When this change is made, then the mysql is available publicaly i.e. it can be accessed remotely. Now your application can access this mysql.
Sounds like a network problem. Verify if you can access the Database host and port from the device you're making the connection, and if the DBMS is up and running.
The key question is whether or not the mobile device is on the network when you try to connect to the database. If you're on the network, you'll need to talk to the MySQL database administrator to see if you have permission to access that database. I'm guessing that you do not, because you're trying to log in as root without a password. No administrator in their right mind would allow you to do that.
If you're the administrator, please call your therapist of pharmacist.
If the mobile device is not on the network, I'm guessing that the database is behind a firewall of some kind. At best you'll have to talk to some administrator to get firewall rules set up to allow access from the mobile device. Those usually require some information about the device. Firewall rules won't be practical if you intend to release an app for several users.
A better solution would be to set up a proxy that would authenticate incoming mobile devices and communicate with the database on their behalf.
I would not have a mobile device connecting directly to a database, especially the way you're trying to do it.
Who else knows about what you're trying to do? It looks to me like you're trying to connect to a database, but that fact isn't widely known. Who else knows about your project?
If you use en emulator use a special IP to your localhost.
10.0.2.2
jdbc:mysql://10.0.2.2:3306/people