mysql driver class not found exception - android

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).

Related

Android App unable to access Azure database

My android application is supposed to get data from an Azure SQL database, but the queries keep responding with
Reference to database and/or server name is not supported in this
version of SQL Server
On the server side audit log it just states
Reference to database and/or server name in 'delivery.dbo.upload' is
not supported in this version of SQL Server
Code:
public class CheckDeliveries extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
private ArrayList<ModelU> arrayList;
//#Override
protected void onPostExecute(String r) {
if (z == "ok") {
GetDeliveries adapter = new GetDeliveries(ViewUpcoming.this, arrayList);
mRecyclerView.setAdapter(adapter);
}
Context context = getApplicationContext();
CharSequence text = "2 " + z;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
protected String doInBackground(String... strings)
{
try
{
con = connectionclass();
if (con == null)
{
z = "Internet Issue";
}
else
{
String query = "SELECT * FROM [delivery].[dbo].[upload]";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
z = "ok";
if(rs.next()) {
do {
#SuppressLint("Range") ModelU modelu = new ModelU(
"" + rs.getInt(rs.getInt("ID")),
"" + rs.getString(rs.getInt("Name")),
"" + rs.getString(rs.getInt("Address")),
"" + rs.getString(rs.getInt("Status"))
);
arrayList.add(modelu);
}
while (rs.next());
}
else {
z = "Invalid Query";
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
return z;
}
}
#SuppressLint("NewApi")
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://2033051.database.windows.net:1433;database=delivery;user=XXXXXXXX;password=XXXXXXXX;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;ssl=request;loginTimeout=30;";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error 1", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error 2", e.getMessage());
}
catch (Exception e)
{
Log.e("error 3", e.getMessage());
}
return connection;
}
}
Toastbox output
Azure database
Any help is greatly appreciated!
This error occurs because Azure does not allow to alter the master database. To resolve this, you need to connect directly to the Azure database you are going to use.
Delete the SQL Azure linked server that we created and create a new one.
Under the Server type section of the General tab, choose the Other data source radio button. The name for the linked server in the Linked server text box can be, this time, whatever you like (e.g. AZURE SQL DATABASE). Under the Provider drop down box, choose the Microsoft OLE DB Provider SQL Server item. In the Data source text box, enter the name of the SQL Azure (e.g. server.database.windows.net). The most important setting in order to correctly create a linked server to an Azure SQL database is to enter the name in the Catalog text box (e.g. TestDatabase) of an Azure SQL database for which you want to create a linked server to an Azure SQL database. Otherwise, if this field is left empty, we will encounter the same 40515 error when trying to get a list of the tables under the Catalogs folder.
Refer this article by Marko Zivkovic

NetworkOnMainThreadException while executing Sql query using JDBC driver

i am executing sql query using JDBC driver but it gives me NetworkOnMainThreadException.i have used a Asyntask for the network operation and mention Internet permission in the menifest file. below is my code for executing query
public class getLedger extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDlg;
private ResultSet rs;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDlg = new ProgressDialog(LedgerActivity.this);
progressDlg.setMessage("Please wait...");
progressDlg.setIndeterminate(false);
progressDlg.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
progressDlg.setCancelable(false);
progressDlg.show();
}
#Override
protected Void doInBackground(String... strings) {
SharedPreferences pref = getSharedPreferences("Login", Context.MODE_PRIVATE);
String ip = pref.getString("ip", "");
String username = pref.getString("username", "");
String password = pref.getString("password", "");
String dbname = pref.getString("dbname", "");
rs = new ExecuteQuery().selectdata(ip, username, password, strings[0], dbname);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
if (rs != null) {
ArrayList<Ledger> ledgerlist = new ArrayList<>();
while (rs.next()) {
String accode = rs.getString("AC_CODE");
String acname = rs.getString("AC_NAME");
String acaddr = rs.getString("AC_ADD1");
String acmobile = rs.getString("AC_MOBILE");
String actype = rs.getString("AC_TYPE");
String amount = rs.getString("Amount");
String goldwt = rs.getString("GoldWt");
String silverwt = rs.getString("SilverWt");
ledgerlist.add(new Ledger(accode, acname, acaddr, acmobile, actype, amount, goldwt, silverwt));
}
LedgerAdapter adapter = new LedgerAdapter(LedgerActivity.this, ledgerlist);
rcv_ledger.setAdapter(adapter);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Looks like call to ResultSet.next() uses InputStream under the hood to load row value or something like that.
So to avoid exception you need to return ArrayList<Ledger> from doInBackground() instead of parsing ResultSet in onPostExecute()

Android Newbie : couldn't connect to OpenWeatherMap properly

I am following the tutorials from Tutplus and youtube on Android WeatherApp creation. Please find my code below. I am trying to connect to OpenWeatherMap and get JSON weather data. Here are my problems:
Its not working.
Is this the right way to create the URL for accessing OpenWeatherMap.
When I registered with the OpenWeatherMap, it gave me a KEY. I am not sure what to do with that. I used it in my code, after getting the httpurlconnection from the server for setting "x-api-key". Don't know if its needed or am doing it
when i get the inputstream, the reader is null and the application hangs after that.
Here is the code:
public class WeatherGrabber {
private static final String TAG = "WeatherGrabber";
private static final String CURRENT_WEATHER_URL =
"http://api.openweathermap.org/data/2.5/weather?q=%s&mode=json";
private static BufferedReader reader;
private static final String my_key = "307ec986e69c22c9a24a1bcf9edd21ea";
public static String loadCurrentWeather(Context context, String city) {
String data = null;
try{
URL web_url = new URL(String.format(CURRENT_WEATHER_URL, city) );
HttpURLConnection conn = (HttpURLConnection)
web_url.openConnection();
conn.addRequestProperty("x-api-key", my_key);
reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer json = new StringBuffer();
while((inputLine = reader.readLine() )!= null){
json.append(inputLine).append("\n");
}
data = json.toString();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (in != null)
in.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return data;
}// end of loadCurrentWeather() method
}
You can't run network requests directly on the main thread. You need to use AsyncTask class to do this.
Create a class in you activity
private class LoadCurrentWeatherAsync extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
try {
//Call to your function here
return loadCurrentWeather(MainActivity.this, "newyork");
} catch (Exception e){
return e.toString();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Do what ever you what with this output
Log.d("data", s);
}
}
Then call it inside your activity onCreate method
new LoadCurrentWeatherAsync().execute();
Also make sure that you have enabled the internet permissions in AndroidManifest.xml . Inside the manifest tag insert
<uses-permission android:name="android.permission.INTERNET" />
It's ok
They use the api key to track whether request is from free or paid plan.
I suspect that's because you are sending the network request on main thread. Try the above code

how to insert dynamic values in sql server via android

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...

Could not find class oracle.security.pki.oraclewallet

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>

Categories

Resources