0

When i use local Database server it is connecting.If i use online Database server i am not able to connect though i have given permissions to access internet in manifest.xml. In dbconctfun(View v ) function i am making connection to Database using threads.

con = DriverManager.getConnection("jdbc:mysql://localhost:9503/dyne", "toot", "tent") this is online Database connection



    package com.example.loginandroid;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

import java.sql.SQLException;
import java.sql.Statement;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Looper;

public class MainActivity extends Activity{
    String username,password;     ResultSet rs =null;
    boolean temcfag=false;
    static boolean temqfag=true;
    public static String tag="Lifecycle activity";
    EditText user,pass;
    AlertDialog.Builder dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dialog=new AlertDialog.Builder(this);
        dialog.setNeutralButton("OK", null);


        user=(EditText)findViewById(R.id.editText1);
        pass=(EditText)findViewById(R.id.editText2);

    }

    Thread  thrd1,thrd2,thrd3;
    Connection con;
      String result ="",queryexct;

    public void dbconctfun(View v )  throws SQLException {

        try {
            temqfag=true;
            Class.forName("com.mysql.jdbc.Driver");
           // Log.v("test#######","multiple class.forname");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        }

        thrd1 = new Thread(new Runnable() {
            public void run() {
                while (!Thread.interrupted()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e1) {

                    }
                    if (con == null) {
                        try {


                           // con = DriverManager.getConnection("jdbc:mysql://111.111.11.11:6666/dyne", "root", "mysql");
                             con = DriverManager.getConnection("jdbc:mysql://localhost:9503/dyne", "toot", "tent");
                          //  Log.v("test#######","multiple con");
                        } catch (SQLException e) {
                            e.printStackTrace();
                            con = null;
                        }

                        if ((thrd2 != null) && (!thrd2.isAlive()))
                            thrd2.start();

                    }
                }

            }
        });
        if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();

        thrd2 = new Thread(new Runnable() {
            public void run() {
                while (!Thread.interrupted()) {

                    if (con != null) {
                        if (temqfag) {
                        try {
                         //   con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
                            Statement st = con.createStatement();


                           // st.execute("SELECT user_name FROM super_admin s");
                            username=user.getText().toString().trim();
                            password=pass.getText().toString().trim();
                            queryexct="SELECT * FROM  `user_registration` WHERE  `email_id` =  '"+username+"' AND  `password` =  '"+password+"'";
                             rs = st.executeQuery(queryexct);

                            Log.v("queryexct",queryexct);
                       //     MainActivity.this.setContentView(R.layout.activity_main1);
                            temqfag=false;

                            if (rs.next()) {
                               Looper.prepare();
                              // Thread.interrupted();

                               Message msgObj = handler.obtainMessage();
                               msgObj.arg1 = 1;
                               handler.sendMessage(msgObj);
                            } else {

                               Looper.prepare();
                               Thread.interrupted();
                               Message msgObj = handler.obtainMessage();
                               msgObj.arg1 = 0;
                               handler.sendMessage(msgObj);
                           }
                        } catch (SQLException e) {
                            e.printStackTrace();
                            con = null;
                        }

                        try {
                       Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }}
                    } else {
                        try {
                        Log.v("test#######","errorrrrrrrrrrr4");
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
         private final Handler handler = new Handler() { 

             public void handleMessage(Message msg) {
                                      if (msg.arg1 == 1) {
                          setContentView(R.layout.activity_main1);
                      } else {

                          dialog.setMessage("Your username and password are not valid");
                          dialog.show();
                      }

             }
    };
        });
    }
}






//Androidmanifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.motalsquarea"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.motalsquarea.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.motalsquarea.LoginActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.example.motalsquarea.Index"
            android:label="@string/title_activity_index" >
        </activity>
    </application>

</manifest>









//error message
** BEGIN NESTED EXCEPTION ** 
 java.net.SocketException
 MESSAGE: java.net.ConnectException: failed to connect to localhost/111.0.0.1 (port 9703): connect failed: ECONNREFUSED (Connection refused)
W/System.err(1060): STACKTRACE:
 W/System.err(1060): java.net.SocketException: java.net.ConnectException: failed to connect to localhost/111.0.0.1(port 9703): connect failed: ECONNREFUSED (Connection refused)
 W/System.err(1060):    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
W/System.err(1060):     at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
 W/System.err(1060):    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2666)
03-11 08:59:49.400: W/System.err(1060):     at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
W/System.err(1060):     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
 W/System.err(1060):    at java.sql.DriverManager.getConnection(DriverManager.java:179)
 W/System.err(1060):    at java.sql.DriverManager.getConnection(DriverManager.java:213)
 W/System.err(1060):    at com.example.motalsquarea.MainActivity$2.run(MainActivity.java:108)
    at java.lang.Thread.run(Thread.java:841)
 ** END NESTED EXCEPTION **
Last packet sent to the server was 750 ms ago.
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2741)
    at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
    at java.sql.DriverManager.getConnection(DriverManager.java:179)
    at java.sql.DriverManager.getConnection(DriverManager.java:213)
    at com.example.desisquarea.MainActivity$2.run(MainActivity.java:108)
    at java.lang.Thread.run(Thread.java:841)
Mitul Nakum
  • 5,514
  • 5
  • 35
  • 41
PRK449
  • 113
  • 3
  • 11

2 Answers2

0

You should never connect directly to a server database from your Android application. Use a Web Service on your server which allows you to connect to your database. That way you just ask the server for information and the server is the one which accesses the database and sends back the data you requested.

Hbibna
  • 568
  • 7
  • 11
0

I found two problems in your code:

  Class.forName("com.mysql.jdbc.Driver");

As far as i know, android does not support mysql.jdbc. do you have a special android-jdbc-mysql driver? [update]your stacktrace shows that your android system has a mysql-jdbc driver. (sorry)[/update]

  con = DriverManager.getConnection(
          "jdbc:mysql://localhost:9503/dyne", "toot", "tent")

localhost is the android device. do you really have a mysql database running on your android device? you probably need a server-url or ip-address that can be reached via the internet or wlan.

Instead of directly accessing the database you can implement a webservice as described in how-to-connect-android-app-to-mysql-database

Community
  • 1
  • 1
k3b
  • 14,517
  • 7
  • 53
  • 85
  • thanks for your reply but i am connecting to local MySQL DB using same code.Its working fine in android virtual device.Yes i have a mysql database running on my computer – PRK449 Mar 11 '14 at 13:14