android can not connect to MySql - android

When I connect to MySQL in android:
code show as below
protected static void connMysql(){
Connection conn = null;
PreparedStatement pstm = null;
ResultSet res = null;
String openurl_mysql="jdbc:mysql://10.15.26.21:3306/etrack_user&autoReconnect=true&failOverReadOnly=false";
try {
java.sql.Driver.class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(openurl_mysql,"etrack","_etrack_mysql_");
pstm = conn.prepareStatement("select count(*) as count from et_patrol_task");
res = pstm.executeQuery();
while(res.next()){
int count = res.getInt("count");
System.out.println("return success=============="+count);
}
res.close();
pstm.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
When I run the program,I get the following problem:enter image description here
Has anyone encountered a similar problem or solved it?

You can't access a MySQL DB from Android natively.Actually you may be able to use JDBC, but it is not recommended.
JDBC is infrequently used on Android, and I certainly would not recommend it.
IMHO, JDBC is designed for high-bandwidth, low-latency, highly-reliable network connections (e.g., desktop to database server, Web application server to database server). Mobile devices offer little of these, and none of them consistently.

Related

Android Quickly Find All Local Devices on Network

I'm making an Android app that needs to be able to see local network devices (either names or ip's). Currently I can scan the network and find the local IP's of devices. However it takes so long the user sees a black screen loading for a couple minutes while it searches the network.
Here is the code that I'm currently using:
private ArrayList<String> scanSubNet(String subnet) {
ArrayList<String> hosts = new ArrayList<String>();
InetAddress inetAddress = null;
for (int i = 1; i < 100; i++) {
try {
inetAddress = InetAddress.getByName(subnet + String.valueOf(i));
if (inetAddress.isReachable(1000)) {
hosts.add(inetAddress.getHostName());
Log.d("ERRORID", inetAddress.getHostName());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return hosts;
}
There has to be a faster way to search for network for devices right?
Please check Using Network Service Discovery and perform task in AsyncTask. Keep on updating the UI when a new node joins your local network.

Android - Connecting MS SQL Server 2008 R2 - Error Connection NULL - Eclipse

I'm new to android. When I try to connect my android app to MS SQL Server database using eclipse android emulator, the LogCat showed me the exception "Error Connection - NULL". I've searched many posts over the internet related to this issue but yet to get a solution for that.
Here is my code which try to connect to database after i click a button. I have copy jtds-1.2.7.jar into the libs folder. Also, set the permission to INTERNET in my manifest file. Can anyone let me know what's wrong with that? Please ~~
public void onClick1(View view) {
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://serverIP:1435/db_name;encrypt=fasle;user=xxxxxx;password=!xxxxxx;instance=SQLEXPRESS;";
String username = "xxxxxx";
String password = "!xxxxxx";
conn = DriverManager.getConnection(connString,username,password);
Log.w("Connection","open");
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("select * from xxxxxx");
//Print the data to the console
while(reset.next()){
Log.w("Data:",reset.getString(3));
}
conn.close();
} catch (Exception e)
{
Log.w("Error connection","" + e.getMessage());
}
}
LogCat - After throw a lot of garbage, showing Error Connection, NULL

How to insert bulk data in android sqlite database using ormlite efficiently

I'm trying to insert 100000 records in android sqlite database at a time. I'm using following two different methods.
private void bulkInsertDataBySavePoint(final List<User> users) {
log.debug("bulkInsertDataBySavePoint()");
DatabaseConnection conn = null;
Savepoint savepoint = null;
try {
conn = userDao.startThreadConnection();
savepoint = conn.setSavePoint("bulk_insert");
for (User user : users) {
userDao.create(user);
}
} catch (SQLException e) {
log.error("Something went wrong in bulk Insert", e);
} finally {
if (conn != null) {
try {
conn.commit(savepoint);
userDao.endThreadConnection(conn);
} catch (SQLException e) {
log.error("Something went wrong in bulk Insert", e);
}
}
}
}
And
private void bulkInsertDataByCallBatchTasks(final List<User> users) {
log.debug("bulkInsertDataByCallBatchTasks()");
try {
userDao.callBatchTasks(new Callable<Void>() {
#Override
public Void call() throws Exception {
for (User user : users) {
userDao.create(user);
}
return null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Both methods work fine. On average they take 140 seconds and take 60-65% CPU which is not ok, I think.
The idea is, I have to consume an api which will provide json data. I have to parse that json data and then insert into sqlite database for offline usage.
I'm looking for an efficient way to solve this issue.
Any thought?
I'm trying to insert 100000 records in android sqlite database at a time... On average they take 140 seconds and take 60-65% CPU which is not ok in my opinion.
Unfortunately I don't have an easy answer for you. You may have to do this sort of insert directly using raw SQL to achieve faster performance on the limited Android CPU. Once you have the data inserted then you can turn to ORMLite to query or manipulate the data faster.
I've had the same problem, and found a reasonable workaround. This took insert time from 2 seconds to 150ms:
final OrmLiteSqliteOpenHelper myDbHelper = ...;
final SQLiteDatabase db = myDbHelper.getWritableDatabase();
db.beginTransaction();
try{
// do ormlite stuff as usual, no callBatchTasks() needed
db.setTransactionSuccessful();
}
finally {
db.endTransaction();
}
Hrm. Good idea #FarrukhNajmi. I've just added it to trunk. It will be in version 4.49.
#Gray Is it still unstable? when can we see it in maven?
And if com.j256.ormlite.dao.ForeignCollection#addAll make only one request it would be nice too.

accessing asp.net web api http service from android

I have a working ASP.NET Web API service running in Visual Studio on my dev box. I can easily get the proper results from either I.E. or FireFox by entering: http://localhost:61420/api/products. But when trying to read it from my Android Project using my AVD I get an exception thrown saying:
localhost/127.0.0.1:61420 - Connection refused.
I know my Android Java code works because I can access the WCF RESTFul service running on my Website (the URLthat's currently commented out). My Android code is pasted below.
So, why am I getting the error when accessing from my Eclipse project but not when accessing it from a browser?
Thanks
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpURLConnection urlConnection = null;
try
{
//URL url = new URL("http://www.deanblakely.com/myRESTService/SayHello");
URL url = new URL("http://localhost:61420/api/products");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String myString = readStream(in);
String otherString = myString;
otherString = otherString + " ";
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
urlConnection.disconnect();
}
}
private String readStream(InputStream is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
}
catch (IOException e)
{
return "" + e;
}
}
}
Visual Studio development web server will only accept connections from the local host and not over the network or other virtual connection. Sounds like AVD is seen as a remote host.
To access the app from anywhere, change the webserver that should be used. Assuming you're using Windows 7 and Visual Studio 2010, make sure you have IIS and all required features installed and set the local IIS as the webserver in your project settings:
It could be necessary to start Visual Studio as a Administrator to run it with local IIS.
Use the actual IP address of your machine ie, http://192.168.0.xx
Only your local machine can access localhost, and if you are on the emulator or a device, it will have a different IP through either NAT or your DHCP from the router.

Android database connectivity exception

I am trying to make an android (2.3) connection with MySQL. The code is below:
public class ConnectionClass {
static String user = "root";
public static void main() {
String url = "jdbc:mysql://127.0.0.1:3306/mydatabase";
// String url = "jdbc:mysql://10.2.5.69:3306/test";
try {
Class.forName("com.mysql.jdbc.Driver");
***Connection con = DriverManager.getConnection(url, user, "mypassword");***
con.isReadOnly();
System.out.println("success");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from user");
while (rs.next()) {
System.out.println("id" + rs.getInt(1));
System.out.println("data" + rs.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
but at the line Connection con = DriverManager.getConnection(url, user, "mypassword") I get the exception:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Well I didnt find anything wrong with your code..
But if you want to connect to mysql at any cost,I would suggest an alternate method of using php as an mediator, which can do all the operations which is mentioned and accessing this php file though HttpClient in java
ref:http://www.helloandroid.com/tutorials/connecting-mysql-database
Android doesn't support for MySQL database.
See the official documentation here:
http://developer.android.com/guide/topics/data/data-storage.html#db

Categories

Resources