Hello I try to get data from my oracle database, I use ojdbc14.jar. There is no error in the code but I got this error in the run time 05-17 10:41:06.846: E/dalvikvm(456): Could not find class 'oracle.security.pki.OracleWallet', referenced from method oracle.jdbc.driver.OracleDriver.getSecretStoreCredentials
How to fix this error. This is my code to get data from database
try
{
String username = getDataFromOraDB();
TextView tv = new TextView(this);
tv.setText(username);
}
catch(SQLException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), 1).show();
}
catch(ClassNotFoundException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), 1).show();
}
}
public String getDataFromOraDB() throws SQLException, ClassNotFoundException
{
String name = null;
String jdbcURL = "jdbc:oracle:thin:#localhost:1521:xe";
String user = "SYSTEM";
String password = "radit";
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn;
ResultSet rs;
Statement stmt;
conn = DriverManager.getConnection(jdbcURL, user, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT name FROM IDENTITY");
if(rs.next())
{
name = rs.getString("name");
}
}
catch(java.sql.SQLException e)
{
System.out.println("The exception is " + e.toString());
}
Toast.makeText(getApplicationContext(), name, 1).show();
return name;
}
I'll appreciate any help. Thank you.
Add following permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Related
So I'm back on Android Development, still getting to know stuff again, and this is the first time I make an app that connects to a database in a server.
So far I have used this code to be able to connect to the server and it works by showing that the "connection is true"
The only thing I want to know now is how I can use this same class to throw queries to do things like "SELECT * FROM TABLE" etc.
I know that it bad practice to do what I'm doing by connecting direct to a db, but this is just a very small app that will not do important stuff but just so I can understand things better in Android.
package com.example.databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
private Connection connection;
private final String host = "xxxxx";
private final String database = "xxxx";
private final int port = "xxxx";
private final String user = "xxxx";
private final String pass = "xxxx";
private String url = "jdbc:postgresql://%s:%d/%s";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
connect();
//this.disconnect();
System.out.println("connection status:" + status);
}
private void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
status = true;
System.out.println("connected:" + status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
public Connection getExtraConnection(){
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
}
This is my MainActivity:
package com.example.databasetest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val db = Database()
}
}
Edit:
Ok, so I tried to replicate the "private void connect()" function into a "public void load()" function which sends sql queries to the db.
public void load() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Connection con;
Statement stmt;
String sql = "SELECT * FROM INVENTORY";
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(url, user, pass);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
int id = rs.getInt("ID");
String description = rs.getString("DESCRIPTION");
String amount = rs.getString("AMOUNT");
String local = rs.getString("LOCAL");
System.out.print("ID: "+id);
System.out.print("Description: "+description);
System.out.print("Amount: "+amount);
System.out.print("Local: "+local);
con.close();
}
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
The problem now is that in the Logcat this warning appears:
"I/Choreographer: Skipped 83 frames! The application may be doing too much work on its main thread."
It worked for one time, but then now it just gives me this error. The database doesn't even have that much info, it has like 12 rows.
How can I multithread (?) this function when accessing the database?
This is where I call db.load() in my MainActivity:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = findViewById<EditText>(R.id.ID)
return when (item.itemId) {
R.id.load -> {
val db = Database()
db.load()
true
}
You have got the instance of Connection, does the Connection contain a method to execute SQL queries (or sth. like that)?
public class Database {
...
public Cursor query(String sql) { //cursor is nullable
// TODO connection.xxxx
}
}
In the class MainActivity, you can access the method query to get the Cursor...
[Update]
public class Database {
private Connection connection;
private final String host = "xxxxx";
private final String database = "xxxx";
private final int port = 9999;//needs int
private final String user = "xxxx";
private final String pass = "xxxx";
private final String SQL_DRIVER = "org.postgresql.Driver";
private String url = "jdbc:postgresql://%s:%d/%s";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
System.out.println("the final url is " + this.url);
}
public Connection getConnection() {
Connection c = null;
try {
Class.forName(SQL_DRIVER);
c = DriverManager.getConnection(url, user, pass);
status = true;
System.out.println("connected:" + status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
return c;
}
public void load() {
Thread thread = new Thread(new Runnable() {
Connection con;
#Override
public void run() {
try {
Statement stmt;
String sql = "SELECT * FROM INVENTORY";
Class.forName(SQL_DRIVER);
con = DriverManager.getConnection(url, user, pass);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
status = true;
while (rs.next()) {
int id = rs.getInt("ID");
String description = rs.getString("DESCRIPTION");
String amount = rs.getString("AMOUNT");
String local = rs.getString("LOCAL");
System.out.print("ID: " + id);
System.out.print("Description: " + description);
System.out.print("Amount: " + amount);
System.out.print("Local: " + local);
}
} catch (Exception e) {
try {
con.close();
} catch (SQLException exp) {
exp.printStackTrace();
}
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
// try to comment
//try {
// thread.join();
//} catch (Exception e) {
// e.printStackTrace();
// this.status = false;
//}
}
}
I'm trying to use MySQL while learning Android, but this class not found exception occurs. I have imported the MySQL connecter jar file into my project, and I have set it up. I googled about the problem but only got a tomcat solution of the same problem but I still don't know how to solve this in Android.
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(){
progressTextView.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 medicine";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
Integer ID = rs.getInt("ID");
String name = rs.getString("Name");
Integer date = rs.getInt("Date");
medID.add(ID);
names.add(name);
medDate.add(date);
}
msg = "complete!";
rs.close();
stmt.close();
conn.close();
}catch (SQLException connERROR)
{
msg = "An exception was thrown for JDBC";
connERROR.printStackTrace();
}catch (ClassNotFoundException classERROR)
{
msg = "Class not found exception";
classERROR.printStackTrace();
}finally {
}
return null;
}
}
Don't use JDBC from an android device, just use J2EE servlets (simplest solution if you want to code in JAVA), and call these servlet from android through HTTP (you can use Retrofit Library to make these calls https://square.github.io/retrofit).
I'm working on android login app with online SQL server database that I have to access it from any platform. I opened the 1433 port and and connect with my ip address and did all the configuration in SQL server still cannot connect from my phone while I can connect from the android studio easily.
Please help me, perhaps I'm missing little things.
MainActivity.java
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.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
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) {
Intent i = new Intent(MainActivity.this, attendance.class);
startActivity(i);
finish();
}
}
#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 The server";
} else {
String query = "select * from tablename where id='" + userid + "' and Password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successfull ";
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
}
return z;
}
}
}
ConnectionClass.java
public class ConnectionClass {
String ip = "192.168.....etc";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "dbname";
String un = "sql server login username";
String password = "*****";
#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("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
The DB can be local, but you must configure your network so it can be reach from the outside.
First
If you want to have the DB at your local server, you must ensure to have a fixed IP from you ISP or use other means to ensure that you IP is always reachable even when the IP change (no-ip and such can do this for you).
Second
You must do the Port forward from the router to you DB Server, so when it gets a connection it will redirect to you DB Server.
My advice is to have it in a hosting service
I am working on GCM.
I am able to send notifications to all registered android devices from my local server.
I have saving regid and userid in database. my requirement is send notifications to particular devices.how to do that?
am using java on server side. Any answers will save me..i posted server side code
server side code
public class GCMNotification extends HttpServlet {
private static final long serialVersionUID = 1L;
// Put your Google API Server Key here
private static final String GOOGLE_SERVER_KEY = "AIzaSyDzlDr2viv-EghBFZGpjwXcDoqh24Wt9yE";
static final String MESSAGE_KEY = "message";
static final String TITLE_KEY = "title";
static final String IMAGE_KEY= "image";
static final String ORDER_KEY= "order";
private List<String> androidTargets = new ArrayList<String>();
public GCMNotification() {
super();
// androidTargets.add(re);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//doPost(request, response);
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the particular database
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db","root","root1");
String sql;
sql = "SELECT regid, fname, email FROM my_db.Persons";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("regid");
String first = rs.getString("fname");
String last = rs.getString("email");
androidTargets.add(id);
}
rs.close();
stmt.close();
con .close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
//MulticastResult result = null;
//Result result1=null;
Writer writer=null;
Connection con=null;
PrintWriter out = response.getWriter();
String share = request.getParameter("shareRegId");
// GCM RedgId of Android device to send push notification
String reg = "";
String emailId="";
String fname="";
if (share != null && !share.isEmpty()) {
reg = request.getParameter("regId");
emailId=request.getParameter("email");
fname=request.getParameter("name");
System.out.println("regId: " + reg);
System.out.println("mailid " + emailId);
System.out.println("name "+ fname);
try {
//Load the Driver for connection
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the particular database
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db","root","root1");
PreparedStatement pst=con.prepareStatement("insert into my_db.Persons(regid,email,fname) values(?,?,?)");
pst.setString(1,reg);
pst.setString(2,emailId);
pst.setString(3,fname);
int i = pst.executeUpdate();
if(i!=0){
pw.println("<br>Record has been inserted");
}
else{
pw.println("failed to insert the data");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MulticastResult result1=null;
String userMessage = request.getParameter("message");
String imageUrl = request.getParameter("image");
String order1=request.getParameter("odt");
String titl=request.getParameter("tit");
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(10000)
.delayWhileIdle(false)
.addData(TITLE_KEY, titl)
.addData(MESSAGE_KEY,userMessage)
.addData(IMAGE_KEY, imageUrl)
.addData(ORDER_KEY, order1)
.build();
try {
// use this for multicast messages. The second parameter
HashSet<String> set = new HashSet<String>(androidTargets);
// Create ArrayList from the set.
ArrayList<String> result = new ArrayList<String>(set);
System.out.println("reg2:"+result);
// of sender.send() will need to be an array of register ids.
result1 = sender.send(message, result,1);
/* if (result1.getResults() != null) {
int canonicalRegId = result1.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result1.getFailure();
System.out.println("Broadcast failure: " + error);
}*/
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("pushStatus", result1.toString());
request.getRequestDispatcher("index.jsp")
.forward(request, response);
}
}
Simply add a where clause to your sql query to filter out the exact user you want to deal with. If you want to filter the user by the email then use something like this..
sql = "SELECT regid, fname, email FROM my_db.Persons where email = 'abc#gmail.com'";
public void query2(View V)
{
Log.i("Android"," MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://10.0.2.2:1433/demo;integratedSecurity=true;user=usd;password=dell#123;";
conn = DriverManager.getConnection(connString);
Log.w("Connection","open");
// Statement stmt = conn.createStatement();
PreparedStatement ps;
ps=conn.prepareStatement("insert into UserMaster1 values(?,?)");
//int x=stmt.executeUpdate("insert into UserMaster1 values( 'usaid','mansoori')");
ps.setString(1,un);
ps.setString(2,pwd);
Log.d("exupdt","insertion done");
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
ps.executeUpdate();
Log.d("PreparedStmt","Success");
conn.close();
}
catch (Exception e)
{
Log.w("Error connection","" + e.getMessage()); }
}
}
i am inserting data in sql server by using the interface PreparedStatement by android to sql server but only a blank row inserted not the data how can i insert dynamic values
You cannot directly access your remote database.
You have to write web-service on server side and then send request from your android application to this service.
You can use this tutorial for example of implementing such program.
public class MainActivity extends Activity {
private TextView t1,t2,t3;
private Button b1;
private EditText e1,e2;
String un,pwd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.tv1);
t2=(TextView)findViewById(R.id.tv2);
t3=(TextView)findViewById(R.id.tv3);
b1=(Button)findViewById(R.id.btn);
e1=(EditText)findViewById(R.id.ed1);
e2=(EditText)findViewById(R.id.ed2);
if (android.os.Build.VERSION.SDK_INT> 9){
StrictMode.ThreadPolicy policy =new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
public void query2(View V)
{
un =e1.getText().toString();
pwd =e2.getText().toString();
if(un.equals("")||pwd.equals(""))
Toast.makeText(this,"Above Fields cannot be left blank",Toast.LENGTH_LONG).show();
else
{
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://172.22.0.2:1433/Samay;integratedSecurity=true;user=DBSQL;password=samay#123;";
conn = DriverManager.getConnection(connString);
Log.w("Connection","open");
PreparedStatement ps;
ps=conn.prepareStatement("insert into UserMaster1 values(?,?)");
ps.setString(1,un);
ps.setString(2,pwd);
int x;
x=ps.executeUpdate();
Log.d("exupdt",un);
Log.d("exupdt",pwd);
Toast.makeText(this, "Success"+x, Toast.LENGTH_LONG).show();
Log.d("PreparedStmt","Success");
conn.close();
}
catch (Exception e)
{
Log.w("Error connection","" + e.getMessage()); }
}
}
}
My best friend solve this typical problem very logically i don't understand why you people don't give the exact answer instead of successions
my best friend name is s.(java queen) she simply solve this problem by giving
un =e1.getText().toString();
pwd =e2.getText().toString();
this code after the method query2 and program gives the exact result what i wanted ..i got dynamic insertion android to sql server...