Debbie
Debbie

Reputation: 969

Android+mysql : Connection class returns a Null object

I am trying to connect my android login app to XAMP server(an Apache is running in local machine) through jtds jdbc. It seems the code fails to connect the server. Here's the code:

ConnectionClass.java

package com.ercess.databaseconnection;

import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.os.Bundle;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionClass {

    public String driver = "net.sourceforge.jtds.jdbc.Driver";

    String url = "jdbc:mysql://localhost/events-test";
    //String url = "jdbc:mysql://127.0.0.1/events-test";
    public String un = "root";
    public String password = "password";
    public String db = "users";

    @SuppressLint("NewApi")
    public Connection CONN() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        java.sql.Connection conn = null;
        String ConnURL = null;
        try{
            Class.forName(driver);
            ConnURL = "jdbc:jtds:sqlserver://" + "127.0.0.1" +";databaseName="+ db + ";user=" + un+ ";password=" + password + ";";

            conn = DriverManager.getConnection(ConnURL);



        }catch (SQLException se){
            Log.e("ERROR", se.getMessage());
        }catch (ClassNotFoundException e){
            Log.e("ERROR", e.getMessage());
        }catch(Exception e){
            Log.e("ERROR", e.getMessage());
        }
        //Log.d("conn",conn.toString());
        return conn;
    }
}

MainActivity.java

    package com.ercess.databaseconnection;

    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.ResultSet;
    public class MainActivity extends AppCompatActivity {
        EditText email, password;
        Button login;
        ProgressDialog progressDialog;
        ConnectionClass connectionClass;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            email = findViewById(R.id.email);
            password = findViewById(R.id.password);
            login = findViewById(R.id.login);
            connectionClass = new ConnectionClass();
            progressDialog = new ProgressDialog(this);
            login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Dologin dologin = new Dologin();
                    dologin.execute();
                }
            });
        }
        public class Dologin extends AsyncTask<String, String, String>{
            String emailstring = email.getText().toString();
            String passstring = password.getText().toString();
            String z = "";
            boolean isSuccess = false;
            String em, pass;
            @Override
            protected void onPreExecute() {
                progressDialog.setMessage("Loading...");
                progressDialog.show();
                super.onPreExecute();
            }
            protected String doInBackground(String... params){
                if(emailstring.trim().equals("") || passstring.trim().equals(""))
                    z = "Please enter all fields........";
                else
                {
                    try{
                        Connection con = connectionClass.CONN();
                        if(con == null){
                            z="Please, check your internet connection....";
                        }else{
                            String query = "select * from users where user='"+emailstring+"'and password='"+passstring+"'";
                            Statement stmt = con.createStatement();
                            ResultSet rs = stmt.executeQuery(query);
                            while(rs.next())
                            {
                                em = rs.getString(0);

                                pass = rs.getString(1);

                                if(em.equals(emailstring) && pass.equals(passstring))
                                {
                                    isSuccess = true;
                                    z = "Login successful...";
                                }
                                else isSuccess = false;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        isSuccess = false;
                        z = "Exceptions"+ex;
                    }
                }
                return z;
            }
            @Override
            protected void onPostExecute (String s){
                Toast.makeText(getBaseContext(),""+z, Toast.LENGTH_LONG).show();
                progressDialog.hide();
            }
        }
}  

I am getting this output: "Please, check your internet connection...." .

This message should fire up only when con = null. How to resolve?

Upvotes: 2

Views: 1203

Answers (2)

I faced the same problem... The main problem is in your ConnectionClass.

String url = "jdbc:mysql://localhost/events-test";
    public String un = "root";
    public String password = "password";
    public String db = "users";

this was your code, well, when you are using root and localhost, it's creating the check your internet connection problem. so to solve it, you have to create a new user and instead of localhost, use the IP Address of your internet.

  1. To create new user, if you are using phpmyadmin, click the privileges tab, there you see add user option. Create user there, give all database privileges to that user and save it. Then use the username and password instead of "root"and "password".

  2. Now to get your IP address, go to command prompt, type ipconfig, you will find ip address. In your above code, instead of localhost, type your ip address, for example,

    String url = "jdbc:mysql://192.168.0.12/events-test";

  3. And you have to give internet access in the AndroidManifest.xml

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

This should solve your problem.

Upvotes: 0

Abdullah Hassan
Abdullah Hassan

Reputation: 197

Android does not support MySQL OR SQL Server : - You can Use Sqllite https://www.tutorialspoint.com/android/android_sqlite_database.htm Or you can Access MySQL by PHP :- https://www.tutorialspoint.com/android/android_php_mysql.htm

Upvotes: 2

Related Questions