Disclaimer: I know people don't typically do this, I am using an SQL database for cost reasons, also I am relatively new to programming.
I am trying to send SQL scripts to my MariaDB database from my Android Studio application. I am currently working to implement a Java Database Connectivity (JDBC) driver for MariaDB however I'm not sure what I need to include.
I went to the download website for the JDBC MariaDB driver however there are many jar files which I have the option of downloading. How do you know which one you need and how do you know how to install it/where for Android? (https://downloads.mariadb.org/connector-java/2.3.0/)
As a note, my Java code is as follows, for which I get the error message "No suitable driver found for .... ":
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents() == null) {
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
}
else {
// Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
String host = "jdbc:mariadb://HOST:PORT/DBNAME";
String username = "UNAME";
String password ="PWD";
try {
Connection con = DriverManager.getConnection( host, username, password );
Toast.makeText(this, result.getContents() + " - Success!", Toast.LENGTH_LONG).show();
} catch (Exception err) {
Toast.makeText(this, err.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
You need to make sure to use the correct driver (connector). Download it and then you import it into Android Studio (libs folder) and then add the following to your app build gradle:
implementation files('libs/mariadb-java-client-1.8.0.jar')
This is the Connector/J that I use (V1.8.0) ... the newer ones don't seem to be compatible. Sample code:
// Create a connection
val myConn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/DB?user=username&password=myPassword")
Class.forName("org.mariadb.jdbc.Driver") // Initialize it
// Now you create SQL statements
val sql01 : PreparedStatement? = (myConn!!.prepareStatement(getString(R.string.sql01)))
// Submit the query
reset = sql01.executeQuery()
Related
This question is specific to a lately strange behavior of the Azure mobile Apps Android sdk. Everything was working fine for weeks. Now, my android client app suddenly can't connect to my web app any more. A Toast says "Error while processing request". In Android Studio debugger, I found the exception inside the SDK file MobileServiceConnection.java.
java.io.IOException: stream was reset: PROTOCOL_ERROR
In Azure Portal, my app shows "Healthy" status, but I can see the HTTP errors. Please help.
Following is my code, which was working fine and now throws error.
// Create the Mobile Service Client instance, using the provided mobile app URL.
try {
mClient = new MobileServiceClient(mMobileBackendUrl, activityContext).withFilter(
new ServiceFilter() {
#Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilter) {
// Get the request contents
String url = request.getUrl();
String content = request.getContent();
if (url != null) {
Log.d("Request URL:", url);
}
if (content != null) {
Log.d("Request Content:", content);
}
// Execute the next service filter in the chain
ListenableFuture<ServiceFilterResponse> responseFuture = nextServiceFilter.onNext(request);
Futures.addCallback(responseFuture, new FutureCallback<ServiceFilterResponse>() {
#Override
public void onFailure(Throwable exception) {
Log.d("Exception:", exception.getMessage());
}
#Override
public void onSuccess(ServiceFilterResponse response) {
if (response != null && response.getContent() != null) {
Log.d("Response Content:", response.getContent());
}
}
});
return responseFuture;
}
}
);
setAzureClient(mClient);
}catch(MalformedURLException e){
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}catch(Exception e){
createAndShowDialog("There was an error creating the Mobile Service. "+ e.toString(), "Error");
}
Toast.makeText(context, context.getString(R.string.online_authentication), Toast.LENGTH_SHORT).show();
authenticate();
}
private void authenticate() { // give access only to authenticated users via Google account authentication
HashMap<String, String> parameters = new HashMap<>();
parameters.put("access_type", "offline");//use "Refresh tokens"
//login with the Google provider. This will create a call to onActivityResult() method inside the context Activity, which will then call the onActivityResult() below.
mClient.login(MobileServiceAuthenticationProvider.Google, url_scheme_of_your_app, GOOGLE_LOGIN_REQUEST_CODE, parameters);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When request completes
if (requestCode == 1) {
try {
MobileServiceActivityResult result = mClient.onActivityResult(data);
if (result.isLoggedIn()) {
Toast.makeText(context, context.getString(R.string.azure_auth_login_success) /*+ " " + mClient.getCurrentUser().getUserId()*/, Toast.LENGTH_SHORT).show();
mUserId = mClient.getCurrentUser().getUserId();
} else {//>>>>THIS IS WHERE I AM GETTING THE ERROR
String errorMessage = result.getErrorMessage();
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();// Error While processing request (it comes form the MobileServiceConnection.java file inside sdk)
}
}catch(Exception e){
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
I found the answer myself. The error was due to an Azure App Service HTTP2 connection issue. It has nothing to do with the app code. For anyone facing the same problem, here is the solution.
Go to https://resources.azure.com/
Make sure you are in Read/Write mode by clicking in the option to the left of your name.
From the left column, browse to: https://resources.azure.com/subscriptions/yourSubscriptionId/resourceGroups/yourWebAppResourceGroup/providers/Microsoft.Web/sites/yourWebAppName/config/web
Find and Change the property: "http20Enabled": from true to false by clicking EDIT, Update value to “false” and then clicking in Save or PATCH.
Currently I have google's signin API working flawlessly through the Android Studio Debugger, and when I install the APK onto my Samsung S6. But when I try to debug connected via USB, GoogleSignInResult.isSuccess() always returns false.
This is mildly infuriating because I need to debug another feature that appears to work just fine when debugging through Android studio but not on my device and i'm unable to get past my login screen. -_-
Here is the block of code that fails, and i can provide more chunks of code if needed.
// [START handleSignInResult]
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
myIntent.putExtra("account", acct);
startActivity(myIntent);
finish();
}
}
// [END handleSignInResult]
// [START signIn]
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// [END signIn]
// [START onActivityResult]
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
// [END onActivityResult]
Thanks!
I'm experiencing a problem connecting between Lotus Domino 9.0.1FP3 and a MSSQL database using the MS JDBC driver the same issue detailed in this question. Everything was fine in 9.0.1 but the applicaiton of FP3 has broken the link.
The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "SSLv3 SSLContext not available". SSLv3 SSLContext not available
I've tried an upgrade of JDBC driver which didn't seem to make any difference like it seems to have for TomSta in his comments
I've tried setting encrypt=true & trustServerCertificate=true which didn't seem to make any difference either.
Is there a change to the Domino / SQL / Windows servers that I need to make with to resolve this issue?
My code and the location of the error is shown below:
public static ResultSet executeQuery(String connString, String userName, String pwd, String query) {
//example connString: "jdbc:sqlserver://10.203.32.16;DatabaseName=DBTest";
ResultSet rs = null;
Statement st = null;
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection(connString, userName, pwd); //Error occurs here
st = conn.createStatement();
rs = st.executeQuery(query);
} catch (Exception e) {
if ( query != null ) {
System.out.println("Failed SQL query: " + query);
}
try {
if (rs != null) { rs.close(); }
} catch (SQLException sqlEx) { rs = null; }
try {
if (st != null) { st.close(); }
} catch (SQLException sqlEx) { st = null; }
try {
if (conn != null) { conn.close(); }
} catch (SQLException sqlEx) { conn = null; }
e.printStackTrace();
return null;
}
return rs;
}
Upgrading to a Fixpack also causes the
<DominoBinary>\jvm\lib\security\java.policy
file to be changed to the default one, so if you changed something here (like for using Class.forName) you should add access granted to the class loader to work.
I don't know if that's a cause but sometimes error messages are not referring to the root cause.
By the way: we experienced that the jDTS driver has a better performance (and less bugs) than the Microsoft driver. You may have a look at it despite your problem. http://jtds.sourceforge.net/
This might have roots in SSLv3/TLS changes. Check this out:
http://support.microsoft.com/kb/2653857
Does my JDBC connection to the database use SSL or not?
In my android app that I want to develope, I would like the users can find their position. To do this I have this code in the MainActivity but on the device (when i run it) it can't find latitute longitude and the address.Why?
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
addressField = (TextView) findViewById(R.id.TextView05); //Make sure you add this to activity_main
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress); //This will display the final address.
} catch (IOException e) {}
catch (NullPointerException e) {}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Note: This is an old answer which did not help solve the particular problem. However, it is valuable information so I don't delete it.
The blinking GPS icon is a good sign. It means that your app is asking the operating system for the location and the operating system tries to fetch it.
The blinking indicates that the operating system did not complete fetching the location via GPS. If this problem persists for, e.g. more than 1 or 2 minutes, it can have the following reasons:
You do not receive the GPS signal (e.g. because you are in a building with too thick walls).
You do not have a data connection to the internet (on some versions of phones and/or android, GPS doesn't work without data connection. Sounds stupid, but it's true. I am a proud owner of such a phone.)
There is some other bug that causes your GPS to be in a state where it does not generate any more location updates. This happened for me sometimes and I do not know any more background info. After a reboot of the phone, it always worked again.
My guess would be that the best provider is not enabled.
try calling getBestProvider(criteria, true)
also Log.d the provider and you can use isProviderEnabled(provider) to see if the provider is enabled.
I've compiled your example and tested it on a Galaxy S2. Here are my findings:
You have code in your examples for two different approaches of getting the location. One approach is to use LocationManager.getLastKnownLocation(...) to fetch the location directly and the other approach is to implement the LocationListener interface and registering for location updates to get notified about new location updates later.
Upfront info: I got the second approach work fine, but I did not get the approach with the getLastKnownLocation method to work reliably.
The location fetching does not work because as provider, "network" is returned. This happens although GPS is on. The subsequent effect is that, because I have the network location provider switched off, the getLastKnowLocation method returns null as documented there: "If the provider is currently disabled, null is returned." (from getLastKnownLocation )
You can fix this by changing
provider = locationManager.getBestProvider(criteria, false);
to
provider = locationManager.getBestProvider(criteria, true);
.
This will give you the GPS provider, if it is available (switched on). However, the getLastKnownLocation(...) method still returns null for me, although the correct provider (gps) is selected and the provider is available. That means that the documentation of the getLastKnownLocation method is lacking information about another case when it returns null. This seems to be because no last known location was saved for this provider. You can not know if this is the case when starting your application, so you can not rely on this method returning a non-null value at application startup.
And here is the good news: Now that we got the correct location provider, the location updates through the second approach (the registering for future location update notifications) works as expected through the gps provider. Updates are coming in and the locations are shown and updated in the textfields on my test phone.
When I run following code on my phone I get black screen saying there was uncaught exception but whole block is wrapped in try/catch block so it is weird, anyway when I proceed with execution code just gets to "Getting device.." so it obviously fails on this line:
LocalDevice local = LocalDevice.getLocalDevice();
Here is whole method:
public void startBT()
{
try
{
f.append("Getting device..");
LocalDevice local = LocalDevice.getLocalDevice();
f.append("Got local device..");
DiscoveryAgent agent = local.getDiscoveryAgent();
f.append("Got local discovery agent..");
connString = agent.selectService(new UUID(
"86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
f.append("Got connection string - >" + connString);
}
catch (Exception ex)
{
Alert message = new Alert("info");
message.setString(ex.getMessage());
Display.getDisplay(this).setCurrent(message);
}
}
Any ideas?
It looks like device I used doesn't support JSR-82 which is J2ME Bluetooth API(this is built into phone, no way of "installing" it) required to use Bluetooth from J2ME Midlets,here is snippet which should check for JSR-82 support:
public static boolean IsBtJsrComaptible() {
try {
Class.forName("javax.bluetooth.LocalDevice");
return true;
} catch (Exception e) {
return false;
}
}
Please note that I got uncaught exception trying to run above snippet, but maybe it would work on some other device.