Problems with database connection

2

I'm developing a test program for integration with webservice . webservice itself was developed in Eclipse . It is a simple user registration and login service. When I run the program on Android and try to register a new user, it appears that it is not recognizing the database.

Below is the code for Activity that is giving Android error.

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;
/**
 * 
 * Register Activity Class
 */
public class RegisterActivity extends Activity {
// Progress Dialog Object
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Name Edit View Object
EditText nameET;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);
    // Find Error Msg Text View control by ID
    errorMsg = (TextView)findViewById(R.id.register_error);
    // Find Name Edit View control by ID
    nameET = (EditText)findViewById(R.id.registerName);
    // Find Email Edit View control by ID
    emailET = (EditText)findViewById(R.id.registerEmail);
    // Find Password Edit View control by ID
    pwdET = (EditText)findViewById(R.id.registerPassword);
    // Instantiate Progress Dialog object
    prgDialog = new ProgressDialog(this);
    // Set Progress Dialog Text
    prgDialog.setMessage("Please wait...");
    // Set Cancelable as False
    prgDialog.setCancelable(false);
}

/**
 * Method gets triggered when Register button is clicked
 * 
 * @param view
 */
public void registerUser(View view){
    // Get NAme ET control value
    String name = nameET.getText().toString();
    // Get Email ET control value
    String email = emailET.getText().toString();
    // Get Password ET control value
    String password = pwdET.getText().toString();
    // Instantiate Http Request Param Object
    RequestParams params = new RequestParams();
    // When Name Edit View, Email Edit View and Password Edit View have values other than Null
    if(Utility.isNotNull(name) && Utility.isNotNull(email) && Utility.isNotNull(password)){
        // When Email entered is Valid
        if(Utility.validate(email)){
            // Put Http parameter name with value of Name Edit View control
            params.put("name", name);
            // Put Http parameter username with value of Email Edit View control
            params.put("username", email);
            // Put Http parameter password with value of Password Edit View control
            params.put("password", password);
            // Invoke RESTful Web Service with Http parameters
            invokeWS(params);
        }
        // When Email is invalid
        else{
            Toast.makeText(getApplicationContext(), "Please enter valid email", Toast.LENGTH_LONG).show();
        }
    } 
    // When any of the Edit View control left blank
    else{
        Toast.makeText(getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_LONG).show();
    }

}

/**
 * Method that performs RESTful webservice invocations
 * 
 * @param params
 */
public void invokeWS(RequestParams params){
    // Show Progress Dialog 
    prgDialog.show();
    // Make RESTful webservice call using AsyncHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
    client.get("http://localhost:8080/useraccount/register/doregister",params ,new AsyncHttpResponseHandler() {
        // When the response returned by REST has Http response code '200'
         @Override
         public void onSuccess(String response) {
            // Hide Progress Dialog
             prgDialog.hide();
             try {
                     // JSON Object
                     JSONObject obj = new JSONObject(response);
                     // When the JSON response has status boolean value assigned with true
                     if(obj.getBoolean("status")){
                         // Set Default Values for Edit View controls
                         setDefaultValues();
                         // Display successfully registered message using Toast
                         Toast.makeText(getApplicationContext(), "You are successfully registered!", Toast.LENGTH_LONG).show();
                     } 
                     // Else display error message
                     else{
                         errorMsg.setText(obj.getString("error_msg"));
                         Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
                     }
             } catch (JSONException e) {
                 Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                 e.printStackTrace();

             }
         }
         // When the response returned by REST has Http response code other than '200'
         @Override
         public void onFailure(int statusCode, Throwable error,
             String content) {
             // Hide Progress Dialog
             prgDialog.hide();
             // When Http response code is '404'
             if(statusCode == 404){
                 Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
             } 
             // When Http response code is '500'
             else if(statusCode == 500){
                 Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
             } 
             // When Http response code other than 404, 500
             else{
                 System.out.println(statusCode);
                 Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running] " + statusCode, Toast.LENGTH_LONG).show();
             }
         }
     });
}

/**
 * Method which navigates from Register Activity to Login Activity
 */
public void navigatetoLoginActivity(View view){
    Intent loginIntent = new Intent(getApplicationContext(),LoginActivity.class);
    // Clears History of Activity
    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(loginIntent);
}

/**
 * Set degault values for Edit View controls
 */
public void setDefaultValues(){
    nameET.setText("");
    emailET.setText("");
    pwdET.setText("");
}

}
When I run Activity , I type the data in the forms and click the button to register, the program drops in onFailure and shows the following message: "Unexpected Error occcured!" [Most common error: Device may not be connected to Internet or remote server is not up and running] "+ statusCode

That is, it is falling on the else that is at the end of onFailure . I tried to put + statusCode  at the end to see which error code is being returned, but the value is zero. I researched the internet and said there is no zero code.

I'm also using a plugin from Google Chrome that executes URLs when passed with parameters. In this program, when I run the following line, it inserts new records as usual: link . I do not know why I can not contact the server when I run Android.

I'm using MySql as the database and Tomcat as the server.

I do not know, but I'm posting the AndroidManifest.xml of the project.

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

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

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.prgguru.example.RegisterActivity"
        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.prgguru.example.LoginActivity"
        android:label="@string/title_activity_login" >
    </activity>
    <activity
        android:name="com.prgguru.example.HomeActivity"
        android:label="@string/title_activity_home" >
    </activity>
</application>

</manifest>

I'm also posting the Eclipse code where the connection to the bank is made

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

import com.mysql.jdbc.Constants;

public class DBConnection {
/**
 * Method to create DB Connection
 * 
 * @return
 * @throws Exception
 */
@SuppressWarnings("finally")
public static Connection createConnection() throws Exception {
    Connection con = null;
    try {
        Class.forName(Constatnts.dbClass);
        con = DriverManager.getConnection(Constatnts.dbUrl, Constatnts.dbUser, Constatnts.dbPwd);
    } catch (Exception e) {
        throw e;
    } finally {
        return con;
    }
}
/**
 * Method to check whether uname and pwd combination are correct
 * 
 * @param uname
 * @param pwd
 * @return
 * @throws Exception
 */
public static boolean checkLogin(String uname, String pwd) throws Exception {
    boolean isUserAvailable = false;
    Connection dbConn = null;
    try {
        try {
            dbConn = DBConnection.createConnection();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Statement stmt = dbConn.createStatement();
        String query = "SELECT * FROM user WHERE username = '" + uname
                + "' AND password=" + "'" + pwd + "'";
        //System.out.println(query);
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            //System.out.println(rs.getString(1) + rs.getString(2) + rs.getString(3));
            isUserAvailable = true;
        }
    } catch (SQLException sqle) {
        throw sqle;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        if (dbConn != null) {
            dbConn.close();
        }
        throw e;
    } finally {
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return isUserAvailable;
}
/**
 * Method to insert uname and pwd in DB
 * 
 * @param name
 * @param uname
 * @param pwd
 * @return
 * @throws SQLException
 * @throws Exception
 */
public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception {
    System.out.println("entrei no insertuser");
    System.out.println(name + "  " + uname + "  " + pwd);
    boolean insertStatus = false;
    Connection dbConn = null;
    try {
        try {
            System.out.println("estou no try do insertuser");
            dbConn = DBConnection.createConnection();
            System.out.println(dbConn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("continuando...");
        Statement stmt = dbConn.createStatement();
        String query = "INSERT into user(name, username, password) values('"+name+ "',"+"'"
                + uname + "','" + pwd + "')";
        System.out.println(query);
        int records = stmt.executeUpdate(query);
        System.out.println(records);
        //When record is successfully inserted
        if (records > 0) {
            insertStatus = true;
        }
    } catch (SQLException sqle) {
        //sqle.printStackTrace();
        throw sqle;
    } catch (Exception e) {
        //e.printStackTrace();
        // TODO Auto-generated catch block
        if (dbConn != null) {
            dbConn.close();
        }
        throw e;
    } finally {
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return insertStatus;
}
}

In the code are passed some variables to make the connection with the bank. Values are as follows. These values I've left declared in another file:

public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName;

public static String dbUser = "root";

public static String dbPwd = "";

I hope for answers and thank everyone for posting some suggestion or solution.

    
asked by anonymous 01.10.2016 / 03:12

1 answer

3
  • Verify that port 3306 is not busy on the server unpredictable can block such as Skype).

  • Verify that MySQL is configured to allow a string (I've already been through this. Try changing the password for a with characters to see if it works).

  • Finally, the most obvious: Verify that the device really is connected to the internet and if MySQL really is on: p

01.10.2016 / 09:53