title: android studio - login register with php mysql (server connection failed)
body: <p>I can't input data on my server
  I'm using wampp server and every time I run my project and input data, I'm always getting the following error <code>server connection failed</code>.</p>
  
  <p>Can somebody please help me to resolve this issue?</p>
  
  <p><strong>Below is my code:</strong></p>
  
  <pre><code>public class MainActivity extends ActionBarActivity {
  
   protected EditText username;
   private EditText password;
   protected String enteredUsername;
   private final String serverUrl = "url server";
  
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
  
       username = (EditText)findViewById(R.id.username_field);
       password = (EditText)findViewById(R.id.password_field);
       Button loginButton = (Button)findViewById(R.id.login);
       Button registerButton = (Button)findViewById(R.id.register_button);
  
       loginButton.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               enteredUsername = username.getText().toString();
               String enteredPassword = password.getText().toString();
  
               if(enteredUsername.equals("") || enteredPassword.equals("")){
                   Toast.makeText(MainActivity.this, "Username or password must be filled", Toast.LENGTH_LONG).show();
                   return;
               }
               if(enteredUsername.length() &lt;= 1 || enteredPassword.length() &lt;= 1){
                   Toast.makeText(MainActivity.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
                   return;
               }
               // request authentication with remote server4
               AsyncDataClass asyncRequestObject = new AsyncDataClass();
               asyncRequestObject.execute(serverUrl, enteredUsername, enteredPassword);
           }
       });
  
       registerButton.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
               startActivity(intent);
           }
       });
   }
  
   @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_main, menu);
       return true;
   }
  
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
       // Handle action bar item clicks here. The action bar will
       // automatically handle clicks on the Home/Up button, so long
       // as you specify a parent activity in AndroidManifest.xml.
       int id = item.getItemId();
  
       //noinspection SimplifiableIfStatement
       if (id == R.id.action_settings) {
           return true;
       }
  
       return super.onOptionsItemSelected(item);
   }
  
   private class AsyncDataClass extends AsyncTask&lt;String, Void, String&gt; {
  
       @Override
       protected String doInBackground(String... params) {
  
           HttpParams httpParameters = new BasicHttpParams();
           HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
           HttpConnectionParams.setSoTimeout(httpParameters, 5000);
  
           HttpClient httpClient = new DefaultHttpClient(httpParameters);
           HttpPost httpPost = new HttpPost(params[0]);
  
           String jsonResult = "";
           try {
               List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2);
               nameValuePairs.add(new BasicNameValuePair("username", params[1]));
               nameValuePairs.add(new BasicNameValuePair("password", params[2]));
               httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
               HttpResponse response = httpClient.execute(httpPost);
               jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
  
           } catch (ClientProtocolException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
           return jsonResult;
       }
  
       @Override
       protected void onPreExecute() {
           super.onPreExecute();
       }
  
       @Override
       protected void onPostExecute(String result) {
           super.onPostExecute(result);
           System.out.println("Resulted Value: " + result);
           if(result.equals("") || result == null){
               Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
               return;
           }
           int jsonResult = returnParsedJsonObject(result);
           if(jsonResult == 0){
               Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
               return;
           }
           if(jsonResult == 1){
               Intent intent = new Intent(MainActivity.this, LoginActivity.class);
               intent.putExtra("USERNAME", enteredUsername);
               intent.putExtra("MESSAGE", "You have been successfully login");
               startActivity(intent);
           }
       }
       private StringBuilder inputStreamToString(InputStream is) {
           String rLine = "";
           StringBuilder answer = new StringBuilder();
           BufferedReader br = new BufferedReader(new InputStreamReader(is));
           try {
               while ((rLine = br.readLine()) != null) {
                   answer.append(rLine);
               }
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
           return answer;
       }
   }
   private int returnParsedJsonObject(String result){
  
       JSONObject resultObject = null;
       int returnedResult = 0;
       try {
           resultObject = new JSONObject(result);
           returnedResult = resultObject.getInt("success");
       } catch (JSONException e) {
           e.printStackTrace();
       }
       return returnedResult;
   } 
  }
  </code></pre>
  
  <p><strong>user.php</strong></p>
  
  <pre><code> &lt;?php
  
  include_once 'db.php';
  
  class User{
  
      private $db;
      private $db_table = "users";
  
      public function __construct(){
          $this-&gt;db = new DbConnect();
      }
  
      public function isLoginExist($username, $password){     
  
          $query = "select * from " . $this-&gt;db_table . " where username = '$username' AND password = '$password' Limit 1";
          $result = mysqli_query($this-&gt;db-&gt;getDb(), $query);
          if(mysqli_num_rows($result) &gt; 0){
              mysqli_close($this-&gt;db-&gt;getDb());
              return true;
          }       
          mysqli_close($this-&gt;db-&gt;getDb());
          return false;       
      }
  
      public function createNewRegisterUser($username, $password, $email){
  
          $query = "insert into users (username, password, email, created_at, updated_at) values ('$username', '$password', '$email', NOW(), NOW())";
          $inserted = mysqli_query($this-&gt;db-&gt;getDb(), $query);
          if($inserted == 1){
              $json['success'] = 1;                                   
          }else{
              $json['success'] = 0;
          }
          mysqli_close($this-&gt;db-&gt;getDb());
          return $json;
      }
  
      public function loginUsers($username, $password){
  
          $json = array();
          $canUserLogin = $this-&gt;isLoginExist($username, $password);
          if($canUserLogin){
              $json['success'] = 1;
          }else{
              $json['success'] = 0;
          }
          return $json;
      }
  
  }
  ?&gt;
  </code></pre>
  
  <p><em>index.php</em></p>
  
  <pre><code>&lt;?php
  
  require_once 'androidlogin/user.php';
  
  $username = "";
  $password = "";
  $email = "";
  echo "hello";
  if(isset($_POST['username'])){
      $username = $_POST['username'];
  }
  if(isset($_POST['password'])){
      $password = $_POST['password'];
  }
  if(isset($_POST['email'])){
      $email = $_POST['email'];
  }
  
  // Instance of a User class
  $userObject = new User();
  
  // Registration of new user
  if(!empty($username) &amp;&amp; !empty($password) &amp;&amp; !empty($email)){
      $hashed_password = md5($password);
      $json_registration = $userObject-&gt;createNewRegisterUser($username, $hashed_password, $email);
  
      echo json_encode($json_registration);
  }
  
  // User Login
  if(!empty($username) &amp;&amp; !empty($password) &amp;&amp; empty($email)){
      $hashed_password = md5($password);  
      $json_array = $userObject-&gt;loginUsers($username, $hashed_password);
  
      echo json_encode($json_array);
  }
  
  ?&gt;
  </code></pre>
  
  <p><em>db.php</em></p>
  
  <pre><code>&lt;?php
  include_once 'config.php';
  
  class DbConnect{
  
  
      private $connect;
  
  
      public function __construct(){
  
          $this-&gt;connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
  
          if (mysqli_connect_errno($this-&gt;connect))
          {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();  
          }
      }
  
      public function getDb(){
  
          return $this-&gt;connect;
      }
  
  }
  </code></pre>