title: Android Login and registration using wamp server, phpmyadmin, eclipse, json
body: <p>I am trying to create a login interface following this tutorial: <a href="http://www.youtube.com/watch?v=etYVqYAhp6w&amp;feature=bf_prev&amp;list=UUnzGVPkz3rZcrLh9jKbKNQw" rel="nofollow">http://www.youtube.com/watch?v=etYVqYAhp6w&amp;feature=bf_prev&amp;list=UUnzGVPkz3rZcrLh9jKbKNQw</a> - Parts 1 to 6.</p>
  
  <p>When I run the application on the Android emulator it returns toast message 'Login Unsuccessful' (a declared exception in Main.java file below).</p>
  
  <p>The main.java file connects to the php file - index.php which I save in directory wamp/www/index.php, which then communicates with the 'mobiledb' stored on the wamp server (on my local machine).</p>
  
  <p>A user has been created in the database and I try to login through the emulator which should validate the login details and give toast message 'Success!'. </p>
  
  <p>If anyone could give any help on what could be the issue, it would be much appreciated. Thanks.</p>
  
  <p>Main.java</p>
  
  <pre><code>package com.kibriaali.logintutorial;
  
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.util.ArrayList;
  
  import org.apache.http.HttpEntity;
  import org.apache.http.HttpResponse;
  import org.apache.http.NameValuePair;
  import org.apache.http.client.HttpClient;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.apache.http.message.BasicNameValuePair;
  import org.json.JSONObject;
  
  import android.app.Activity;
  import android.content.SharedPreferences;
  import android.os.Bundle;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.Toast;
  
  public class Main extends Activity implements OnClickListener{
      EditText etUser, etPass;
      Button bLogin;
  
      //Create string variables that will have the input assigned to them
      String username, password;
  
      //Create a HTTPClient as the form container
      HttpClient httpclient;
  
      //Use HTTP POST method
      HttpPost httppost;
  
      //Create an array list for the input data to be sent
      ArrayList&lt;NameValuePair&gt; nameValuePairs;
  
      //Create a HTTP Response and HTTP Entity
      HttpResponse response;
      HttpEntity entity;
  
  
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
  
          initialise();
      }
  
      private void initialise() {
          // TODO Auto-generated method stub
          etUser = (EditText) findViewById(R.id.etUser);
          etPass = (EditText) findViewById(R.id.etPass);
          bLogin = (Button) findViewById(R.id.bSubmit);
          //Now to set an onClickListener
          bLogin.setOnClickListener(this);
      }
  
      public void onClick(View v) {
          // This is where we will be working now
  
          //Create new default HTTPClient
          httpclient = new DefaultHttpClient();
  
          //Create new HTTP POST with URL to php file as parameter
          httppost = new HttpPost("http://127.0.0.1/wamp/www/index.php"); //92.4.131.132 //127.0.0.1 //10.0.2.2
  
          //Assign input text to strings
          username = etUser.getText().toString();
          password = etPass.getText().toString();
  
  
  
          //Next block of code needs to be surrounded by try/catch block for it to work
          try {
              //Create new Array List
              nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2);
  
              //place them in an array list
              nameValuePairs.add(new BasicNameValuePair("user", "username"));
              nameValuePairs.add(new BasicNameValuePair("pass", "password"));
  
              //Add array list to http post
              httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  
              //assign executed form container to response
              response = httpclient.execute(httppost); //response from the PHP file
  
              //check status code, need to check status code 200
              if(response.getStatusLine().getStatusCode()== 200){
  
                  //assign response entity to http entity
                  entity = response.getEntity();
  
                  //check if entity is not null
                  if(entity != null){
  
  
                      //Create new input stream with received data assigned
                      InputStream instream = entity.getContent();
  
                      //Create new JSON Object. assign converted data as parameter.
                      JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
  
                      //assign json responses to local strings
                      String retUser = jsonResponse.getString("user");//mySQL table field
                      String retPass = jsonResponse.getString("pass");
  
                      //Validate login
                      if(username.equals(retUser)&amp;&amp; password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password 
  
                          //Create a new shared preference by getting the preference
                          //Give the shared preference any name you like.
                          SharedPreferences sp = getSharedPreferences("logindetails", 0);
  
                          //Edit the Shared Preference
                          SharedPreferences.Editor spedit = sp.edit();
  
                          //Put the login details as strings
                          spedit.putString("user", username);
                          spedit.putString("pass", password);//May not need to store password
  
                          //Close the editor
                          spedit.commit();
  
                          //Display a Toast saying login was a success
                          Toast.makeText(getBaseContext(), "SUCCESS!", Toast.LENGTH_SHORT).show();
  
  
                      } else {
                          //Display a Toast saying it failed.
  
                          Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                      }
  
                  }
  
  
              }
  
  
          } catch(Exception e){
              e.printStackTrace();
              //Display toast when there is a connection error
              //Change message to something more friendly
              Toast.makeText(getBaseContext(), "Login Unsuccessful.", Toast.LENGTH_SHORT).show();
          }
  
  
  
  
  
  
      }//END onClick()
  
      private static String convertStreamToString(InputStream is) {
          /*
           * To convert the InputStream to String we use the BufferedReader.readLine()
           * method. We iterate until the BufferedReader return null which means
           * there's no more data to read. Each line will appended to a StringBuilder
           * and returned as String.
           */
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
          StringBuilder sb = new StringBuilder();
  
          String line = null;
          try {
              while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
              }
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              try {
                  is.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          return sb.toString();
      }//END convertStreamToString()
  
  }
  </code></pre>
  
  <p>INDEX.PHP file </p>
  
  <pre><code>&lt;?php
  //turn off error reporting
  error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
  
  //Create fields for the database
  //server, username, password, database
  
  $dbhost = "localhost"; //92.4.131.132 //127.0.0.1 //10.0.2.2
  $dbuser = "root";
  $dbpass = "";
  $dbdb = "mobiledb";
  
  //connect to mySQL
  $connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");
  
  //Select the database
  mysql_select_db($dbdb)or die("database selection error");
  
  //Retrieve the login details via POST
  $username = $_POST['username'];
  $password = $_POST['password'];
  
  //Query the table android login
  $query = mysql_query("SELECT * FROM androidlogin WHERE user='$username' AND pass='$password'");
  
  //check if there any results returned
  $num = mysql_num_rows($query);
  
  //If a record was found matching the details entered in the query
  if($num == 1){
      //Create a while loop that places the returned data into an array
      while($list=mysql_fetch_assoc($query)){
          //Store the returned data into a variable
          $output = $list;
  
          //encode the returned data in JSON format
          echo json_encode($output);
  
      }
      //close the connection
      mysql_close();
  
  
  }
  
  ?&gt;
  </code></pre>
  
  <p>Note: Internet permissions have been enabled in Android manifest file.</p>