2

Estou desenvolvendo um programa teste para integração com webservice. O webservice em si foi desenvolvido no Eclipse. É um simples serviço de cadastro e login de usuários. Quando executo o programa no Android e tento registrar um novo usuário, parece que ele não está reconhecendo o banco de dados.

Abaixo segue o código da Activity que está dando erro no Android.

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("");
}

}

Quando executo a Activity, digito os dados nos formulários e clico no botão para realizar o registro, o programa cai no onFailure e mostra a seguinte mensagem :"Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running] " + statusCode

Ou seja, ele está caindo no else que está no fim do onFailure. Tentei colocar o + statusCode no fim para ver que código de erro está sendo retornado, mas o valor é zero. Pesquisei na internet e falam que não existe código zero.

Eu também estou usando um plugin do Google Chrome que executa as URLs quando são passadas com parâmetros. Neste programa, quando executo a seguinte linha, ele insere novos registros normalmente : http://localhost:8080/useraccount/register/[email protected]&password=teste . Não sei por que não consigo me contatar com o servidor quando executo pelo Android.

Estou usando o MySql como banco de dados e o Tomcat como servidor.

Não sei será necessário, mas estou postando o AndroidManifest.xml do projeto.

<?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>

Também estou postando o código do Eclipse onde é realizada a conexão com o banco

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;
}
}

No código são passadas algumas variáveis para realizar a conexão com o banco. Os valores são os seguintes. Esses valores eu deixei declarados em outro arquivo :

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

public static String dbUser = "root";

public static String dbPwd = "";

Espero por respostas e agradeço a todos que postarem alguma sugestão ou solução.

1 Resposta 1

3
  • Verifique se a porta 3306 não está ocupada no servidor (Coisas
    imprevisíveis podem bloquear, como o Skype).

  • Verifique se o MySQL está configurado para permitir uma string vazia como senha (Já passei por isso. Tente trocar a senha por uma com caracteres pra ver se funciona).

  • Por fim, o mais óbvio: Verifique se o dispositivo realmente está conectado à internet e se o MySQL realmente está on :p

1
  • 2
    Ericson, não era nenhuma das três possibilidades que você sugeriu, mas descobri o que era. A terceira opção que você sugeriu foi que me fez achar a solução. Era o endereço IP do dispositivo. Como eu estou usando o emulador de Android, não pode ser localhost:8080, tem que ser um endereço específico para os emuladores de Android. No meu caso, foi 10.0.2.2:8080 1/10/2016 às 19:54

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .