2
I’m developing a test program for integration with webservice. The webservice in itself was developed in the Eclipse. It is a simple service of registration and login of users. When I run the program on Android and try to register a new user, it seems that it is not recognizing the database.
Below follows the code of Activity
that is giving error on 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("");
}
}
When I perform the Activity
, type the data in the forms and click on the button to perform the registration, the program falls on onFailure
and displays the following message :"Unexpected Error occcured! [Most common Error: Device Might not be Connected to Internet or remote server is not up and running] " + statusCode
That is, he is falling into the One who is at the end of the onFailure
. I tried to put the + statusCode
in order to see which error code is being returned, but the value is zero. I searched the internet and they say there is no zero code.
I’m also wearing one plugin of Google Chrome that executes the Urls when they are passed with parameters. In this program, when I run the following line, it normally inserts new records : http://localhost:8080/useraccount/Register/doregister? [email protected]&password=test . I don’t know why I can’t contact the server when running on Android.
I’m using the Mysql as a database and the Tomcat as a server.
I don’t know if it’s necessary, but I’m posting 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 performed
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 some variables are passed to make the connection with the database. The values are as follows. These values I left declared in another file :
public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName;
public static String dbUser = "root";
public static String dbPwd = "";
I wait for answers and I thank all who post any suggestions or solutions.
Ericson, it wasn’t one of the three possibilities you suggested, but I figured out what it was. The third option you suggested was that it made me find the solution. It was the device’s IP address. As I am using the Android emulator, it cannot be localhost:8080, it has to be a specific address for Android emulators. In my case, it was 10.0.2.2:8080
– postgisBeginner