I'm using this tutorial to establish a connection between my android app to MS database 1.http://ift.tt/1nLn2ZH
2.http://ift.tt/13uVEal
I downloaded everything, did basically everything it says.. Now, everything works till I press Register button in the registration activity layout, nothing happens actually, it shows no errors nothing.. but it directs to next activity which means that it is ok.. but when i check the database nothing is added!
I used both emulators: the android studio emulator and genymotion.. and I checked the url strings for both emulators and they work fine in their broswers
How can I track the program when it goes out from the android studio so I can know where is the error?
Register.java
package hamadk.car_care;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.os.Build;
public class Register extends Activity {
EditText regName, regPhone, regPassword, regEmail;
Button btnCreateUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Show the Up button in the action bar.
// setupActionBar();
regName =(EditText) findViewById(R.id.reg_name);
regPhone = (EditText) findViewById(R.id.reg_phone);
regPassword = (EditText) findViewById(R.id.reg_password);
regEmail = (EditText) findViewById(R.id.reg_email);
btnCreateUser=(Button) findViewById(R.id.btn_createuser);
btnCreateUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name, password, email;
int phonenumber;
name = regName.getText().toString();
phonenumber = Integer.parseInt(regPhone.getText().toString()) ;
password = regPassword.getText().toString();
email = regEmail.getText().toString();
UserDetailsTable userDetail = new UserDetailsTable(name,
phonenumber, password, email);
new AsyncCreateUser().execute(userDetail);
}
});
}
protected class AsyncCreateUser extends
AsyncTask<UserDetailsTable, Void, Void> {
@Override
protected Void doInBackground(UserDetailsTable... params) {
RestAPI api = new RestAPI();
try {
api.CreateNewAccount(params[0].getName(),
params[0].getPhoneNumber(), params[0].getPassword(),
params[0].getEmail());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
Intent i = new Intent(Register.this, MainActivity.class);
startActivity(i);
}
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_register, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://ift.tt/1c7OZSR
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
RestAPI.java
/* JSON API for android appliation */
package hamadk.car_care;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONArray;
public class RestAPI {
private final String urlString = "http://ift.tt/1IVX1xz";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
}
else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date)o);
}
else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String Name,int phoneNumber,String password,String email) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "CreateNewAccount");
p.put("Name",mapObject(Name));
p.put("phoneNumber",mapObject(phoneNumber));
p.put("password",mapObject(password));
p.put("email",mapObject(email));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
System.out.println("GOOD SO FAR, AFTER CREATE");
return result;
}
public JSONObject UserAuthentication(String phoneNumber,String email) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "UserAuthentication");
p.put("phoneNumber",mapObject(phoneNumber));
p.put("email",mapObject(email));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
public JSONObject CreateAppointment(String appointmentType,Date appointmentIssuedDate,Date appointmentDate,String licencePlate,String clientComment,String issuerName,String appointmentMethod,String lineName,Date reminderDate,int phoneNumber,String clientFirstName,String email,int vehicleModel,String vehicle_name,String clientLastName) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "CreateAppointment");
p.put("appointmentType",mapObject(appointmentType));
p.put("appointmentIssuedDate",mapObject(appointmentIssuedDate));
p.put("appointmentDate",mapObject(appointmentDate));
p.put("licencePlate",mapObject(licencePlate));
p.put("clientComment",mapObject(clientComment));
p.put("issuerName",mapObject(issuerName));
p.put("appointmentMethod",mapObject(appointmentMethod));
p.put("lineName",mapObject(lineName));
p.put("reminderDate",mapObject(reminderDate));
p.put("phoneNumber",mapObject(phoneNumber));
p.put("clientFirstName",mapObject(clientFirstName));
p.put("email",mapObject(email));
p.put("vehicleModel",mapObject(vehicleModel));
p.put("vehicle_name",mapObject(vehicle_name));
p.put("clientLastName",mapObject(clientLastName));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
public JSONObject deleteClient(int phone) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "deleteClient");
p.put("phone",mapObject(phone));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
public JSONObject checkAvailableLines(int service_type_ID,Date Appointment_Date) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "checkAvailableLines");
p.put("service_type_ID",mapObject(service_type_ID));
p.put("Appointment_Date",mapObject(Appointment_Date));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
}
UserDetailsTable.java
package hamadk.car_care;
public class UserDetailsTable {
String name, password, email;
int phonenumber;
public UserDetailsTable(String name, int phonenumber, String password,
String email) {
super();
this.name = name;
this.phonenumber = phonenumber;
this.password = password;
this.email = email;
}
public UserDetailsTable() {
super();
this.name = null;
this.phonenumber = 0;
this.password = null;
this.email = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhoneNumber() {
return phonenumber;
}
public void setPhoneNumber(int phonenumber) {
this.phonenumber = phonenumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
ServiceAPI.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace JSONWebAPI
{
public class ServiceAPI : IServiceAPI
{
void main()
{
}
SqlConnection dbConnection;
public ServiceAPI()
{
dbConnection = DBConnect.getConnection();
}
public void CreateNewAccount(string Name, int phoneNumber, string password, string email)
{
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "INSERT INTO Clients (client_firstName, client_phone_No, client_password, client_email_address) VALUES ('" + Name + "','" + phoneNumber + "','" + password + "','" + email + "');";
SqlCommand command = new SqlCommand(query, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
public bool UserAuthentication(string phoneNumber, string email)
{
bool auth = false;
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT client_ID FROM dbo.Clients WHERE client_phone_No='" + phoneNumber + "' AND client_email_address='" + email + "';";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
auth = true;
}
reader.Close();
dbConnection.Close();
return auth;
}
public void CreateAppointment(string appointmentType, DateTime appointmentIssuedDate, DateTime appointmentDate, string licencePlate, string clientComment, String issuerName, String appointmentMethod, String lineName, DateTime reminderDate, int phoneNumber, String clientFirstName, String email, int vehicleModel, String vehicle_name, String clientLastName)
{
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "INSERT INTO dbo.Appointment_Types (appointment_type_name) VALUES ('" + appointmentType + "'); INSERT INTO Appointments (appointment_issued_date, appointment_date, licence_plate, client_comment, issuer_name, appointment_method, line_name, reminder_date, mobile_No, client_firstName, email_address, vehicle_model, vehicle_name, client_lastName) VALUES ('" + appointmentIssuedDate + "','" + appointmentDate + "','" + licencePlate + "','" + clientComment + "','" + issuerName + "','" + appointmentMethod + "','" + lineName + "','" + reminderDate + "','" + phoneNumber + "','" + clientFirstName + "','" + email + "','" + vehicleModel + "','" + vehicle_name + "','" + clientLastName + "');";
SqlCommand command = new SqlCommand(query, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
public void deleteAppointment(int ID)
{
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "DELETE FROM dbo.Appointments WHERE appointment_ID='" + ID + "' ; ";
SqlCommand command = new SqlCommand(query, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
public DataTable displayAppointment(int ID)
{
DataTable appointmentTable = new DataTable();
appointmentTable.Columns.Add("Appointment Date", typeof(DateTime));
/* appointmentTable.Columns.Add("Service Name", typeof(String)); this is from Appointment Types */
appointmentTable.Columns.Add("Vehicle Name", typeof(String)); // this is from Appointments
appointmentTable.Columns.Add("Maintenance Status", typeof(String));
appointmentTable.Columns.Add("Engineer Comment", typeof(String));
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT appointment_date,vehicle_name,Maintenance_progress_status,engineer_comment FROM dbo.Appointments WHERE client_ID='" + ID + "'; ";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
appointmentTable.Rows.Add(reader["Appointment Date"], reader["Vehicle Name"], reader["Maintenance Status"], reader["Eningeer Comment"]);
}
}
reader.Close();
dbConnection.Close();
return appointmentTable;
}
public DataTable displayUserProfile(int ID)
{
DataTable clientTable = new DataTable();
clientTable.Columns.Add("First Name", typeof(String));
clientTable.Columns.Add("Last Name", typeof(String));
clientTable.Columns.Add("Phone Number", typeof(int));
clientTable.Columns.Add("Email ", typeof(String));
clientTable.Columns.Add("Points ", typeof(int));
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT client_firstName,client_lastName,client_phone_No,client_email_address,clientpoints FROM dbo.Clients WHERE client_ID='" + ID + "'; ";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
clientTable.Rows.Add(reader["First Name"], reader["Last Name"], reader["Phone Number"], reader["Email"], reader["Points"]);
}
}
reader.Close();
dbConnection.Close();
return clientTable;
}
public void deleteClient(int phone)
{
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "DELETE FROM dbo.Clients WHERE client_phone_No='" + phone + "' ; ";
SqlCommand command = new SqlCommand(query, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
public DataTable checkAvailableLines(int service_type_ID, DateTime Appointment_Date)
{
DataTable availableReservationTime = new DataTable();
DataTable availableLinesTable = new DataTable();
availableLinesTable.Columns.Add("Line Name", typeof(String));
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT line_name FROM dbo.Lines WHERE appointment_type_ID='" + service_type_ID + "'; ";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
availableLinesTable.Rows.Add(reader["Line Name"]);
}
}
reader.Close();
dbConnection.Close();
availableReservationTime=checkAvailableTime(availableLinesTable);
return availableReservationTime;
}
public DataTable checkAvailableTime(DataTable availableLinesTable)
{
DataTable availableLinesTable2 = availableLinesTable;
DataTable availableReservationTime=new DataTable();
availableLinesTable.Columns.Add("Reservation Time", typeof(DateTime));
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
Array availableTimes = availableLinesTable2.Select();
for (int i = 0; i <= availableTimes.Length;i++ )
{
string query = "SELECT reservation_time FROM dbo.VW_Connected_Reservations WHERE line_name='" + availableTimes.GetValue(i) + "'; ";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
availableReservationTime.Rows.Add(reader["Reservation Time"]);
}
}
reader.Close();
}
dbConnection.Close();
return availableReservationTime;
}
}
}
DBConnect.cs
using System.Configuration;
using System.Data.SqlClient;
namespace JSONWebAPI
{
///
/// This class is used to connect to sql server database
///
public class DBConnect
{
private static SqlConnection NewCon;
private static string conStr = ConfigurationManager.ConnectionStrings["HondaDB"].ConnectionString;
public static SqlConnection getConnection()
{
NewCon = new SqlConnection(conStr);
return NewCon;
}
public DBConnect()
{
}
}
}
Web.config
<!--
For more information on how to configure your ASP.NET application, please visit
http://ift.tt/1eW0XAj
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
<connectionStrings>
<add name="HondaDB" connectionString="Data Source=HAMAD; Initial Catalog=Honda_DB;Integrated Security=True " providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>