App crashes when trying to connect with web service using WebClient

MarinPekoMarinPeko HRMember ✭✭

I'm doing on a Xamarin Android app and I have a class with bunch of methods for interaction with web service. Every of these methods should return something (true/false to be sure if the database transaction is completed or some other data from database). For example, I have a method:

`public bool AddNewUser(User user)
{
WebClient client = new WebClient();
Uri url = new Uri(web + "AddNewUser.php");
NameValueCollection parameters = new NameValueCollection();
bool result = false;

parameters.Add("FirstName", user.FirstName);
parameters.Add("LastName", user.LastName);
parameters.Add("Email", user.Email);
parameters.Add("MobileNumber", user.MobileNumber);

client.UploadValuesAsync(url, parameters);
client.UploadValuesCompleted += (object sender, UploadValuesCompletedEventArgs e) =>
{
      if (Encoding.UTF8.GetString(e.Result) == "true")
      {
           result = true;
      }
};

return result;

}`

This method returns the result as true or false(if the transaction is completed or if the transaction is not completed).

This is my PHP file:

<?php require_once(dirname(__FILE__).'/Connection.php'); if(isset($_POST['FirstName']) && isset($_POST['LastName']) && isset($_POST['Email']) && isset($_POST['MobileNumber'])) { $firstName = $_POST['FirstName']; $lastName = $_POST['LastName']; $email = $_POST['Email']; $mobileNumber = $_POST['MobileNumber']; $connection = new Connection(); $connection->GetConnection(); if(!$connection->conn) { echo 'Error: '.mysqli_connect_error(); } else { $sql = 'INSERT INTO tb_user(name,lastname,mail,phone) VALUES ("'.$firstName.'","'.$lastName.'","'.$email.'","'.$mobileNumber.'")'; $result = mysqli_query($connection->conn,$sql); if(!$result) { echo 'Error: '.mysqli_error($connection->conn); } else { echo true; } } } ?>

App crashes with no error and user is not written to database. Error in UploadValuesCompletedEventArgs is equal to NULL.

Can you tell me what I'm doing wrong?

Answers

  • MarinPekoMarinPeko HRMember ✭✭

    Any suggestions?

  • CheesebaronCheesebaron DKInsider, University mod

    Your method returns before it hits the UploadValuesCompleted event. Hence the result will always be false.

    I suggest you use HttpClient instead of WebClient. So much cleaner and async API.

  • MarinPekoMarinPeko HRMember ✭✭

    Yes but why does the app crashes?

  • MobileAPP415MobileAPP415 USMember

    @Cheesebaron

    where to implement webservice.asmx file for andriod app in real time development.

    Is it in our local iis or else any live server application.
    Please help me
    Thank you.

  • MarinPekoMarinPeko HRMember ✭✭

    You dont need to bother with this type of connecting to web service. Try with httpwebrequest. It's much simpler and easier.

Sign In or Register to comment.