Connecting to an OracleDB via an Android app - android

Thans for looking, I hope you could help me.
Currently, I want to get some data from an OracleDB server (on the LAN) from my Android app. I'm using JDBC with the ojdbc14.jar and the following code in my Android app and the stackTrace I have with the logcat :
http://pastebin.archlinux.fr/432118
As you can see, there is a big exception, and I'm not be able to fix it...
Has someone already succeeded in a OracleDB connection with his Android app and without webservices ?
Could someone help me fixing this Exception ?
For information : I've tried to change the ojdbc driver (the worst thing I've ever done >.>), and I checked the URL validity.
Thanks for helping...
EDIT : The application will have to get data from the OracleDB, and store it on the local SQLite DB of Android, because the Android device will be disconnected of the LAN (and I don't want to make the data accessible from web [3G]). Once disconnected, the app will work with the local data on SQLite. When the user's activity is finished, the device will be reconnected to the LAN and the app syncs the edited SQLite local data with the main Oracle DB server. SQLite <-- local --> App <-- when connected/sync ---> OracleDB

Oracle actually has a product specifically designed for syncing the Oracle Database with mobile devices. It's called mobile server.
However the usage model is slightly different from what you're describing; instead of connecting directly to Oracle Database, you would use a local Berkeley DB or SQLite database, and then mobile server would sync that with the Oracle Database.
It can run as a separate process that automatically handles sync, or you can use API calls to control sync from within your program. If that sounds like something that could be useful to you, check it out here.
You can download it from the download tab and try it out.
Best of luck with solving your problem.
Regards
Eric,
Oracle PM

I've found the answer ! The product Oracle Database Lite is the solution. I explain...
The Oracle Database Lite is a big product, with an unreadable documentation. Impossible for me to understand how it works. But, I've tried to install it. And, in the install folders, there is a jdbc folder.
There, you will find an ojdbc14.jar. Use it in your project instead of the ojdbc14.jar found on the classical Oracle webpage. And it works !
You will be able to connect an Oracle DB via your Android app, using JDBC.
Thanks for all,
Best regards,
Eriatolc

ORACLE DATABASE CONNECTION WITH ANDROID THROUGH LAN
Grant Some Manifest Permissions
<permission
android:name="info.android.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="info.android.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
MainActivity Class
package example.com.myapplication;
import java.sql.Connection;
import java.sql.DriverManager;
import android.os.StrictMode;
public class MainActivity extends AppCompatActivity {
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:#192.168.0.1:1521:xe";
private static final String DEFAULT_USERNAME = "system";
private static final String DEFAULT_PASSWORD = "oracle";
private Connection connection;
#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);
}
TextView tv = (TextView) findViewById(R.id.hello);
try {
this.connection = createConnection();
e.Log("Connected");
Statement stmt=connection.createStatement();
ResultSet rs=stmt.executeQuery("select * from cat");
while(rs.next()) {
System.out.println("hello : " + rs.getString(1));
}
connection.close();
}
catch (Exception e) {
e.Log(""+e);
e.printStackTrace();
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static Connection createConnection() throws ClassNotFoundException, SQLException {
return createConnection(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
}
}
Prerequisite are:
Note there is no need to add dependency lib ojdbc14.jar just copy ojdbc14.jar to your JAVA_HOME jre -> lib -> ext & paste here ojdbc14.jar
then first manually check jdbc connection by cmd/terminal
make any simple java program
http://www.javatpoint.com/example-to-connect-to-the-oracle-database

Related

Xamarin.Android i am getting Soap Service time out exception on my mobile phone

My main purpose is getting data from soap webservice on my android phone. Actually i implemented webservice references correctly. But i want to try some data from soap webservice on my android phone , i am getting time out exception like this ;
System.Net.WebException: The operation has timed out.
Here is my source code ;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
var service = new LifeService.LifeService();
var result = service.LifeService_getPersons("xxx#gmail.com","12345");
}
After adding some email and number to the LifeService_getPersons method it should return PersonList to me . Nevertheless it return an exception what i mentioned above. I run this service at windows form application and xamarin.android by using an emulator. Service works fine . It returns data correctly. However when i try to use it on my self phone , it is not working. Then i thought it might be some permission problem and added permissions to the Manifest.xml file such as ;
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Unfortunately it doesn't change anything.Please help . thanks.

How to implement Android’s Data Backup Service

For my Android Project I tried to follow and implement Android Developers Data Backup Guidelines ( http://developer.android.com/guide/topics/data/backup.html ), but Data Backup and Restore doesn't work. Can someone help with examples?
With further investigation I figured out the steps to implement Android Data Backup and Restore. They are:
Add in Manifest xml file the following:
a. android:allowBackup="true" (This enables Android’s Data Backup Service)
b. meta-data android:name="com.google.android.backup.api_key"
android:value=”{Your unique Registration Key for Android Backup Service}” (You must register your application package name with a backup service. To generate a key, go to http://developer.android.com/google/backup/signup.html )
c. android:backupAgent=”.MyBackupAgent” (This is the name of class that implement’s your declared backup agent class). Note1: The first character of the name is a period for the purpose of a shorthand to locate your “com.example.project.MyBackupAgent”. Note2: If a run time Exception occurs (this may or may not happen depending on your project stucture) such as: java.lang.ClassNotFoundException: Didn’t find class “com.example.project.MyBackupAgent” then I suggest you Decompile your apk (Upload your apk package in http://www.decompileandroid.com/ ) and search for the absolute path to your MyBackupAgent and insert this path for android:backupAgent=”{absolute path}.MyBackupAgent”
Here’s an example of a Manifest xml file with Backup support:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.project">
<application android:allowBackup="true" android:backupAgent="md5f576d3976d691fac04b078d1718cab3.MyBackupAgent">
<meta-data android:name="com.google.android.backup.api_key" >android:value="{Your unique Registration Key}" />
</application>
Add in project your MyBackupAgent class. The BackupAgentHelper class provides a convenient wrapper around the BackupAgent class, which minimizes the amount of code you need to write. In your BackupAgentHelper, you must use one or more "helper" objects, which automatically backup and restore certain types of data, so that you do not need to implement onBackup() and onRestore().
Note: Android currently provides backup helpers that will backup and restore complete files from SharedPreferences and internal storage.
Here’s a Java SharedPreferenceBackupHelper example for MyBackupAgent class:
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
import android.util.Log;
public class MyBackupAgent extends BackupAgentHelper{
static final String PREFS = "myprefs";
static final String PREFS_BACKUP_KEY = "myprefs";
#Override
public void onCreate() {
Log.i("MyFileBackupAgent", "****** Enter BACKUP CLASS *******");
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
Log.i("MyFileBackupAgent", "****** Exit BACKUP CLASS ********");
}
}
Here’s a C# Xamarin FileBackupHelper example for MyBackupAgent class:
public class MyBackupAgent: BackupAgentHelper
{
string myProtectData = "File.bin";
string myPersistentData = "Data.bin";
string myDBase = "Database.db";
public override void OnCreate()
{
Console.WriteLine ("****** Enter Backup Files Helpers *********");
base.OnCreate ();
try
{
FileBackupHelper dbkh = new FileBackupHelper (this, myProtectData);
this.AddHelper ("PROTECT_backup", dbkh);
FileBackupHelper persisth = new FileBackupHelper (this, myPersistentData);
this.AddHelper ("PERSIST_backup", persisth);
FileBackupHelper dbh = new FileBackupHelper (this, myDBase);
this.AddHelper ("DATABASE_backup", dbh);
Console.WriteLine ("********* All 3 files backuped *********");
}
catch {
Console.WriteLine ("******* Backup AddHelper Exception ERROR *********");
}
Console.WriteLine ("******** Exit Backup Files Helpers ********");
}
public override void OnBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState)
{
Console.WriteLine ("****** Override OnBackup called ******");
base.OnBackup(oldState, data, newState);
}
public override void OnRestore (BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState)
{
Console.WriteLine ("****** Override OnRestore called ******");
base.OnRestore(data, appVersionCode, newState);
}
}
To perform a backup, your code should make a backup request by calling the dataChanged(). A backup request does not result in an immediate call to your onBackup() method. Instead, the Backup Manager waits for an appropriate time*, then performs backup for all applications that have requested a backup since the last backup was performed. Note, The Backup Manager Service responds every hour as long as at least one DataChanged() was called in-between the hour since the last data backup request.
For test purposes, an immediate backup can be performed with the Android SDK Command Prompt Tool. Try these commands:
To ensure Data Backup Enabled:
adb shell bmgr enable true
To request a Data Backup:
adb shell bmgr backup
To initiate a Data Backup:
adb shell bmgr run
To uninstall your App:
adb uninstall
Then install your App:
adb install
What about your phone device Backup settings? Make sure a WiFi connection is established. Also, under device Settings, make sure "Back up my data" and "Automatic restore" are checked and you have entered in a valid Backup Account email id.
Lastly, to track your Backup upload time stamps, use www.google.com/settings/dashboard (this is your personal google account that matches your google account in your Android phone device Backup settings)

Android MutlicastSocket constructor problems

I'm writing an app to do some basic communication via multicast. I'm running into a problem and can figure why. I'm defining the socket according to the constructor in the API, yet it's not actually setting the variables as specified. Here is a basic code snippet with a bunch of the extra stuff removed:
import java.net.MulticastSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
...
private InetAddress groupInetAddr = InetAddress.getByName("239.42.42.42");;
private int groupPort = 42000;
private MulticastSocket groupSocket;
netInt = NetInfo.getInterface();
//This is a custom method that chooses a candidate NetworkInterface
//from available options. Returns a NetworkInterface object
try{
groupSocket = new MulticastSocket(groupPort);
groupSocket.setNetworkInterface(netInt);
groupSocket.joinGroup(groupInetAddr);
groupSocket.setTimeToLive(64);
}
catch (Exception e){
Log.i(TAG, "FAILED");
}
I have some test code immediately following this code to confirm that the socket has been created properly, and it isn't...
Log.i(TAG, "groupInetAddr: " + groupInetAddr.toString());
Log.i(TAG, "groupPort: " + groupPort);
Log.i(TAG, "groupSocket.getInetAddress: " + groupSocket.getInetAddress());
Log.i(TAG, "groupSocket.getPort(): " + groupSocket.getPort());
The log results of the test:
GroupSender﹕ groupInetAddr: /239.42.42.42
GroupSender﹕ groupPort: 42000
GroupSender﹕ groupSocket.getInetAddress: null
GroupSender﹕ groupSocket.getPort(): -1
So, as you can see, the InetAddress is being created properly, so that's not the problem, but the socket isn't assigning the InetAddress as the destination. Additionally, when I check Wireshark, there is no IGMP message send out over the LAN to that address.
Additionally, I've added the following permissions to the AndroidManifest.xml to allow access to necessary services.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.wifi" />
Any ideas? Hopefully I'm just missing something small.
The socket has been constructed correctly. You didn't connect it, so its getInetAddress() returns null and its target port is -1.
That doesn't have anything to do with which multicast groups it has joined. Your expectations are at fault.
The IGMP message is only sent if this host isn't already a member of that group.
It turns out that this code works as intended. The problem is with the Android emulator. It doesn't send out the IGMP message as required.
I was trying to communicate between the emulator and an actual device. I installed the app on 2 devices and they are able to communicate between each other.

How to restore database from backup agent saved path android

I am using this code for saving database, using BackupAgent class
public class MyBackupAgent extends BackupAgentHelper {
String DATABASE_NAME = "mydb";
String DATABASE_FILE_NAME = "mydb.db";
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
FileBackupHelper dbs = new FileBackupHelper(this, DATABASE_FILE_NAME);
addHelper("dbs", dbs);
}
#Override
public File getFilesDir() {
File path = getDatabasePath(DATABASE_FILE_NAME);
return path.getParentFile();
}
}
Now after that i want to know how to restore database?
Please help me about this, Thanks in advance
In theory only with that code and changes on AndroidManifest the backup should work as per Android Google page inform.
Please take a look on this page: http://developer.android.com/guide/topics/data/backup.html
For summary from this above page:
To implement a backup agent, you must:
1 - Declare your backup agent in your manifest file with the android:backupAgent attribute.
2 - Register your application with a backup service. Google offers Android Backup Service as a backup service for most Android-powered devices, which requires that you register your application in order for it to work. Any other backup services available might also require you to register in order to store your data on their servers.
3 - Define a backup agent by either: Extending BackupAgent or Extending BackupAgentHelper;

Programmatically Connect and Disconnect Android Device

I need to find a way to (using an Android application) programmatically connect and disconnect an Android device from a host.
I am using a Galaxy Nexus. My goal is to keep everything as close to stock as possible, though I have already enabled verbose debug messages in the kernel and in order to view them have enabled root access on the phone to access /proc/kmsg (and the shell command dmesg).
I am certain that there is a way to leverage root access to do what I need to do, but all of my attempts have lead to nix.
Mess with /proc/bus/usb
Mess with /dev/bus/usb
Change between MTP/PTP (unable to do programatically)
Making the Android USB gadget driver into a module <- ???
I am going to try to figure out how to do the last object on the list, as then I would be able to rmmod and insmod the resulting *.ko in my application and that would connect and disconnect the phone. I am unsure of the feasibility of this option though.
Solution came when close to a deadline, so I am almost sure it is not the best way of doing things, but it met my requirements.
Build Modded kernel (to allow hooking of particular function)
Modify kernel config to support Kprobes (set CONFIG_KPROBES to Y)
Remove "static" keyword from android_setup() definition (driver/usb/gadget/android.c)
Build that kernel
Build kernel module (which gives the actual functionality of connecting and disconnecting)
Use Kallsyms to dynamically pull the absolute address of android_setup()
Using kprobes, hook android_setup()
Set up two timers to execute every time android_setup() is called
First timer set for 2 seconds from now, Second set for 2.005 seconds from now
Both timers take a pointer to the struct usb_gadget as their data
In respective callback functions, call usb_gadget_connect() and usb_gadget_disconnect(), which forces physical disconnect followed by reconnect on the Samsung Galaxy Nexus
Build Application
Gotta have a rooted device
Simply make a shell call with SU privilege - "insmod module_name." Until you call rmmod, the module will force the device into an enumeration cycle, disconnecting and reconnecting continuously.
If you are interested in repeating these results, read the document posted here and feel free to send me any questions.
https://docs.google.com/uc?export=download&id=0B9WchRkSOWwJbi10MGhLWUljT2s
You can try to enable/disable some secured settings like Settings.Secure.USB_MASS_STORAGE_ENABLED or Settings.Secure.ADB_ENABLED (depending on what you call "connect" !)
This code should work (disabling USB mass storage):
Settings.Secure.putInt(getContentResolver(),Settings.Secure.USB_MASS_STORAGE_ENABLED, 0);
Settings.Secure.putInt(getContentResolver(),Settings.Secure.USB_MASS_STORAGE_ENABLED, 0);
InternetControl.java
public class InternetControl {
public static void EnableInternet(Context context)
{
try {
Log.i("Reached Enable", "I am here");
setMobileDataEnabled(context,true);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void DisableInternet(Context context)
{
try {
Log.i("Reached Disable", "I am here");
setMobileDataEnabled(context,false);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void setMobileDataEnabled(Context context , boolean enabled) throws Exception{
final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class connClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = connClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conn);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
}
Manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
Enable or Disable function are static so you can call by using
classname.functionname();

Categories

Resources