179 thoughts on “How to create Simple Login form using php in android? – Connect php with android.

  1. Rash

    I’m new in android.This post is very usefull for me.I’ve run this,but it is showing a error like…….

    Response from PHP:

    ::PETROBANGLA

    Company:-

    …..
    …..
    …..

    thus with login form of android in emulator….
    what is the problem,I can’t understand….
    Looking forward your reply,thank’s…

    Reply
    1. James Post author

      So your php call is returning something, then what is your problem?

      Reply
      1. Rash

        Thank’s for your reply.But I’m not clear about is it working or not?I’m sending my demo site where i wanna login.If you can,you will check this please…Again thank’s for your reply….

        Reply
    2. Jovan

      Hi ,good example !
      But I can not login on other websites where I know the username and password ..
      How to do that ? Is it a problem on url ? php side I don’t know

      Reply
  2. ayesha

    hello i am having little problem here , i have download your code run it on an emmulator but as i login it does nothin i think my url to php file is wrong or what i am using wamp.
    Please help!

    Reply
    1. James Post author

      Hi Ayesha, are you getting any error or something. I dont know about how to place url in wamp. First try your url in the browser after putting an echo in the page and if it is working then place the url in android, that is what I am suggesting.

      Reply
      1. Arunjayaprakash

        Hi sir
        I write the code without error and i get internet permission also. i enter userid and password also right but the program not display the result. what is my problem?

        Reply
  3. Rohit

    I am new in android world. I have implemented your code successfully but problem is that even if I login successfully still it gives me an error like “User Not Found” and on text it shows “User Found”.

    Reply
    1. James Post author

      This will not happen, because “user found” and “user not found” are inside if and else respectively. Please recheck your logic.

      Reply
  4. ellie

    Hi, I’m having a problem with the php file it self. When I run it on its own in firefox I get errors:

    Notice: Undefined index: username in C:\xampp\htdocs\my_folder_inside_htdocs\check.php on line 12

    Notice: Undefined index: password in C:\xampp\htdocs\my_folder_inside_htdocs\check.php on line 13
    No Such User Found

    And when i run the app, validating user pops up for a second then closes. Is this because my php is not working. If so how do i fix my php..

    Ellie

    Reply
    1. James Post author

      Dont browse the url directly it will not work, because I am using post to send the data. you could have browsed directly if I was using GET.

      Reply
  5. Tashu

    Hi,
    This is a good example! Can you give me a hint with simple example of how to connect with SQL Server and fetch the data in android.

    Thanks

    Reply
    1. James Post author

      In this example also you are fetching the data from a SQL Server. The data here is – whether the user is present or not. If you want some other data then edit the php file to return the data you want. Any data from the server will be a string which we can get it in the android side.

      Reply
  6. ABC

    This article is very helpful and easy to understand for beginners. I am
    trying to implement this code, but facing one error on “span” tag.

    error is:

    Multiple markers at this line
    – Syntax error on token “<", delete this token
    – The left-hand side of an assignment must be a
    variable
    – Syntax error on token "/", delete this token

    how do I solve it??? Kindly guide me…
    Thanks in advance

    Reply
    1. James Post author

      Sorry, that’s the problem with my syntax highlighter. please remove those HTML span tags and proceed.

      Reply
  7. Fai

    hi, i’m facing a little problem here. everything works fine for me except when the user found, it will not direct me to UserPage. It just close the alertdialog and show back the login form.

    how to solve this?
    thanks

    Reply
    1. James Post author

      Please paste here the code how you are checking when the user is found.

      Reply
    2. Harsh

      Apparently there needs to be an entry in the manifest file for the second page, i.e.

      and permission for the app to use internet

      Reply
  8. surendra

    Warning: Activity not started, its current task has been brought to the front

    Reply
    1. James Post author

      Simply edit some code and run the project. This is not an error. This comes before you have already ran the same code and recompiling is not needed.

      Reply
  9. surendra

    everything works fine for me except when the user found, it will not direct me to UserPage. It just close the alertdialog and show back the login form.

    Reply
  10. Barbara

    Apparently there needs to be an entry in the manifest file for the second page, but I don’t see what that should be in the tutorial

    Reply
  11. BC

    Hello,

    First I want to say great tutorial. Such resources are hard to find. However, I came across a problem on my end. When I run the code and click log-in it doesn’t do anything. The dialog for “Validating user…” doesn’t even show up. There’s absolutely no effect after I click / select log in. Am I missing something? Please help. Thank you very much 🙂

    Reply
    1. James Post author

      Did you add the internet permission in the Manifest file. Also check the Logcat.

      Reply
  12. B

    OK! A third post 🙂
    I thought i’d share my solution in case some others made the same mistake as myself. I created a new activity in Eclipse. However, the XML code I copied from the beginning of the tutorial was placed in the MAIN xml (activity). Thus the two were not working together. The layout and class code weren’t communicating. So if the button doesn’t respond for you please advise.

    However I still have a problem. I’ve tested this on my s3 and Kindle Fire. When I try to login I get this error: “The application MySQL (process com.example.mysql) has stopped unexpectedly. please try again.”

    Why would it crash? I’ve tested a script on my server and everything checks out ok, but the app just crashes.

    Reply
    1. James Post author

      Hello B : Please check the LogCat for the error and Paste that error here.

      Reply
    2. James Post author

      Hello B : Please check the Eclipse LogCat for the error and Paste that error here.

      Reply
    3. James Post author

      Hello B : I have edited the code for All versions. Now it will not crash. PLease check it again.

      Reply
    4. James Post author

      Hello B : I have edited the code for All versions. Now it will not crash. PLease check it again. ok

      Reply
    5. James Post author

      Hello B : I have edited the code for All versions.Now it will not crash. PLease check it again. ok

      Reply
    6. James Post author

      Hello B : I have edited the code for All versions.Now it will not crash.PLease check it again. ok

      Reply
  13. Anita

    After validating user message its showing message as Unfortunately phpconnection stopped. Plz give me solution

    Reply
  14. dalijo

    hi..i want to ask, when i create the database in xampp, i didnt find the folder inside the htdocs..what happen? is iam create manualy the folder or its generated automaticalyy when i create the database?

    and when i click the login button, the device didnt show anything..is it because not connected to database?where my problem?thanks..

    best regards..

    Reply
    1. James Post author

      You have to manullay create the folder inside htdocs and put your php files in it. There you have to write the php code to connect with the database.

      Reply
  15. Nikhil

    I tried your tutorial but when i click on login button then it shows validating input and then does not thing and it again shows normal login screen..Plz help

    Reply
    1. James Post author

      Did you add the internet permission in the AndroidManifest file.

      Reply
      1. ishaque

        hi james
        me too have the same problem and i add the user permission in my android manifest file…but there is no any change…..

        Reply
        1. James Post author

          The post was posted in Android 2.1 so Please do the network operation inside a thread if you are working in Android > 2.1.

          Reply
        2. James Post author

          Please paste the error that is coming in the LogCat.

          Reply
  16. Leong

    This is great for app with a single activity
    but how about if I want to use php session.
    I know that should be something to work with cookies

    Reply
  17. Sridhar

    i am not getting error and i gave exact username and password. A dialog
    opens and says validating user and it disappear in few seconds….then it stands in login.java………
    waiting for reply sir……………thank you

    Reply
    1. James Post author

      First check whether your username and password are reaching the server, then check the response from the server.

      Reply
        1. James Post author

          Try echo “yoursentusername” and echo “yoursentpassword” from the php server side after getting these values as POST. if you are getting the values together with response in the android side, then your values are reaching the server else check the android side.

          Reply
          1. Sridhar

            I did as u said php code is correct..and still remains same………

  18. sct

    My problem is when i click login, it keeps validating then it goes back to the login page, nothing happens. I have already add internet permission

    Reply
    1. James Post author

      Check the result from your server. Check whether there is any exception is not.

      Reply
      1. Sct

        Sorry that I am new to the android development..how to check those exception in server? Thanks

        Reply
        1. James Post author

          I am telling to check exceptions in android itself. print out the error message inside the try-catch and then you can know whether there is any problem with the server.

          Reply
  19. tkang

    hi , i trying to debug this application through USB to my phone . My computer IP is 192.168.1.4 …so , i charged to httppost= new HttpPost(“http://192.168.1.4/my_folder_inside_htdocs/check.php”); // make sure the url is correct. In the same time , i using in same network …Anyone know how to solve it and connect it ?

    Reply
    1. James Post author

      For testing in your phone you need to install it in a public domain, the Localhost is for the system you are using not for the phone.

      Reply
  20. Rasool Bux

    I am trying to run this code from 2 hours and after validating dialog app show no response and these are logcat errors as under.
    Exception : Connection to http://localhost refusing

    these are erros and done uses-permission and also using Emulator having api level 10.
    Please help I have need of this example.

    Reply
  21. Gyanendra

    Hi James,

    I have pasted all the codes as directed by you. But still my app is not giving result. When i give the username and password and click login after it, it only shows a pop up “validating user” and then nothing happens.The same login screen is shown.I have given the URL as follows:

    http://192.168.0.168/android/check.php. First is one my pc’s IP and the android is my folder name inside htdocs of xampp in which i have kept the check.php file. The logcat is showing following

    “unexpected value from nativeGetEnabledTags”.
    Please help me out of this situation.

    Reply
  22. Gyanendra

    After few try now it is always saying Login Error. When i am entering correct user name and password also it saying Login Error.
    The php response is showing User Found but android side showing login error. it is not redirecting to login success page.

    What can be the error? suggest.

    Reply
  23. Sanjay

    I have pasted all the codes as directed by you. But still my app is not giving result. When I give the username and password and click login after it, it only shows a pop up “validating user” and then nothing happens.

    URL as follows: http://127.0.0.1/my/check.php (I keep my check.php file under my folder, I have got wamp server)

    Reply
  24. hishamsharawneh

    hello.. first thing thx for this examples very useful but i have little problem i think there is something is missing to connect login button to php interface give mee “no such user” so i think maybee if wee add onclick in button login i think will work … what u think??

    Reply
    1. James Post author

      try printing out the count from the php file and check the result in the php side.

      Reply
  25. monica

    Hye.
    First of all thanks for the great tutorial!!
    It works well but there is only a single problem.

    In Android activity – it shows the php respone that i have a valid user (n thats right) but the progress dailogbox shows me that i have a invalid user inspeat of having a valid user in database!
    I am stuck and i dont know why it is causing this probs!!

    It would great if i get respone as soon as possible!!

    Thankyou n Best Regards!!

    Reply
    1. James Post author

      Please check your php side script and check the response from php side in the Android side according to the parameters sent.

      Reply
  26. Maciej

    Hello,

    I have the same problem as few users:
    “My problem is when i click login, it keeps validating then it goes back to the login page, nothing happens. I have already add internet permission”

    Error from the LogCat:
    Exception : Connection to http://127.0.0.1 refused

    I’m using a XAMPP 1.8.1. When I checking check.php file in the browser, everyting works fine I can get a name and password from the database, but in android app, nothing is going fine.
    Apache Ports: 80, 443
    What I need to change?
    Could You help me? Thank You.
    Sorry for my English.

    Reply
    1. James Post author

      Use 10.0.2.2 instead of 127.0.0.1 if you are testing in the emulator and server is your system itself.

      Reply
      1. Maciej

        Thanku you for your reply.
        One more thing
        If I would like to launch an application on an external device (not emulator), then how address looks like?

        Reply
  27. kaarthik

    i have interested in learning for creating the mobile apps in android so please guide me so that i can became a android developer i can understand the program but some terms i cant understand.
    So mail some of the PDF files basics of learning the android application development so that i can learn thank u

    Reply
  28. priyanka singh

    Hi james.I really appreciate that from your busy schedule activities, you are giving us time to solve our issue.I am new to android development and as suggested by your article, if you will send me code to fill spinner with mysql table records using php and mysql.I have a project in which i have to implement this.Your current reply will help me a lot.Thanks in advance.

    Reply
  29. priyanka singh

    Respected sir
    Thanks for your quick reply,but I have already tried to fill spinner with sqlite database and i have succeeded in that.Actually I want fill spinner from mysql database.I will really be very greatful to you if you send me code realted to ‘Fill spinner with mysql’.

    Reply
  30. Adi

    Hello Sir…my code runs just fine when the correct username password combo are entered in the android app…but on entering incorrect values, the application force closes..i have tried in vain to solve this error..even replaced the alert dialog with a simple toast message..but still fails to work.can you help me out? Thanks in advance.

    Reply
    1. James Post author

      Try to run it inside a thread because from 2.3 onwards network operations need to be run inside a thread.

      Reply
  31. C

    Hi great tute….

    But what can I do if the values are NOT reaching the server… The URL when i run .php on browser is what i used in httpPost but still not reaching the server please help…

    Reply
    1. James Post author

      Check the important things to note that I have posted in this article. Make sure you have done those correct.

      Reply
  32. potboiler

    Where to put the database files? I have sql query browser on my computer. Can i use this for creating the database?

    Reply
    1. James Post author

      What are u looking for? a online database or Local database.? if it is a Local database then you should try SQLite database. Check out other posts about SQLite in Coderzheaven.com

      Reply
  33. potboiler

    My code is not running properly. As i click on signin, validating user comes for few secs and then nothing happens.

    Reply
    1. James Post author

      print you username and password in the LogCat and also print the reponse from server in the Logcat and check it.

      Reply
      1. potboiler

        solved it! Adjusted some permissions in the apache files, and it worked fine.

        Reply
        1. Birey

          Potboiler what did you adjust to allow permissions in the apache files. I’m getting the same problem you had as well?

          Reply
  34. Ranjan

    hii..
    code is working properly but it is not validating my userid and pass..

    Reply
  35. Rohit Hazra

    Had no problem in running just one that in one of your screenshot you showed a page with only text [login success] i hope that after login that page should not open.
    And also tell me that after logging in how can i redirect to another page?

    Reply
  36. roshan dallakoti

    Connection error is my problem?
    what is the cause and possible solution

    Reply
    1. James Post author

      Check your file exists in the server and you have internet connection. Also you should have INTERNET PERMISSION in the Manifest.

      Reply
  37. paeh

    Hi,,nice tutorial..i can run this tutorial..but after i click log in, the toast said user found..but it dont go to the userpage..i already add internet permission in the manifest..hope someone can help me..thank u..

    Reply
  38. pia

    Hi james… I am getting many errors in eclipse with this code.. please help..

    Reply
  39. sara

    hello James,

    I copied the entire code and compiled it without errors but when i ran it there are several null pointer exceptions and also fatal errors and zygote errors. could you tell me how to solve them?

    Sara

    Reply
    1. James Post author

      May be it is due to my syntax highlighter problem. Check for spelling mistakes and case mistakes.

      Reply
  40. gigi

    Hi James, i encountered some problem with the login page. when i type either the correct or incorrect username and password it does not bring me to the respective pages. when i clicked login, it just stays at validating user, thats all.
    can you help me. thanks.

    Reply
  41. Angel M.

    Hi!

    First I want to thank you for your tutorial. It is very informative although as a novice Android programmer I’m not able to take full advantage of it. I tried implementing your codes to the best of my abilities however I’m having problems making it work. I am currently trying to work it with my Android phone and changed the 10.0.2.2 with my own IP address. I made sure I also included the internet permission on the Android manifest. However, when I run it on my device, the following error message shows up:

    Response from PHP :
    Notice: Undefined index: username in /Applications/XAMPP/xamppfiles/htdocs/my_folder_inside_htdocs/check.php on line 13

    Notice: Undefined index: password in /Applications/XAMPP/xamppfiles/htdocs/my_folder_inside_htdocs/check.php on line 14
    No Such User Found

    Can you please tell me how I could fix this? Thanks in advance!

    Reply
  42. ron

    i copied the javacode to my eclipse i got two error they are..
    main cannot be resolved or is not a field
    UserPage cannot be resolved to a type
    can u help me to solve this??

    Reply
  43. swalih

    Exception : android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

    Reply
  44. Faisal

    For those complaining about two problems: 1). cannot connect to your database and 2). cannot show the new activity page after login successful. Please read on for the solutions.

    1). if you cannot connect to the database (assuming you have setup the database correctly). the url in android should be httppost= new HttpPost(“http://xxx.xxx.x.xxx/check.php”); // where all the x’s are ure IP address of your computer or server. remember to put the check.php file in the htdocs folder in xampp

    2). for the second problem, u must add the activity in androidManifest.xml like this (bold):

    and finally James thx for the tutorial !!!! excellent !

    Reply
  45. jagan

    Hello James,

    Really it’s helpful to me.I wasted my 2 days time to connect Mysql DB from android using JSON+ php. This is very simple way to achieve this.Your post is simply Super.

    thanks for your good work.keep it Up.

    Reply
  46. ffml

    Hi James,
    My login is working, PHP is return true to me.
    But after, when I call another method, I do a session verification for know if the user is logged. How can I get and set this session through the android app?

    Thanks!

    Reply
  47. Pingback: How to create Simple Login form using php in android? – Connect php with android. | Techno Fusions

  48. smily

    Though i know it’s not possible but thought i am getting the problem of one same person that is at the same time text view of id tv shows me ‘user found’ and dialogue box shows me ‘user not found’.
    If you wish i can mail u my code.

    Reply
  49. Ashikur rahman

    hello james thnx for ur nice Article..its help me a lot.. this login tutorial helps me a lot ..but i face some problem…
    My project run properly in localhost i mean in xamp but not works with my webserver url.. i check several times of my url but didnt get any sol8n. itz not take input from username and password i mean submitt button didnt work.. can u give me some proper idea..

    httppost= new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/index.php”);
    here i use
    httppost= new HttpPost(“http://mywebsite.co/my_folder_inside_htdocs/index.php”);
    and my subfolder also named my_folder_inside_htdocs.
    thank you

    Reply
    1. James Post author

      Did you give the internet permission in the android manifest file.

      Reply
  50. saurabh

    i am trying to execute a simple demo android app which shows the db connect using php from past 10days i am trying i dont know why people are giving wrong code and do not know who are commenting all this fake id’s in this code first time i found this some span and all thing which is clearly showing error in xml file i am trying to remove but errors are not going….. totally i hate all this wrong ………….things

    Reply
  51. saurabh

    yeah i have resolved the problem its working can you show a demo to storing the things in list view and after clicking on particular item it should fetch some data from database and display in another screen if you then please its very urgent for me have to do project.. please if u can… between thanks a looot for perfect code…

    Reply
  52. Aditya Bhardwaj

    when i click on login . progress dialog appears thats it.. no toast meassage…i have give 127.0.0.1

    Reply
  53. Aditya Bhardwaj

    when i open check.php it shows error Undefined index: username and password line 12 and 13

    Reply
  54. zulkifli

    hai master..
    nice tutorial..
    but i get an error
    i have insert data to the table
    when i open check.php file it shows “No Such User Found”

    sorry for bad english 🙂
    thanks for ur reply

    Reply
  55. nelson

    im having some difficulties, when i log in nothing happens. please help.
    package com.fits;

    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class FinalITSActivity extends Activity {
    Button b;
    EditText et,pass;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List nameValuePairs;
    ProgressDialog dialog = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    b = (Button)findViewById(R.id.Button01);
    et = (EditText)findViewById(R.id.username);
    pass= (EditText)findViewById(R.id.password);
    tv = (TextView)findViewById(R.id.tv);

    b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    dialog = ProgressDialog.show(FinalITSActivity.this, “”,
    “Validating user…”, true);
    new Thread(new Runnable() {
    public void run() {
    login();
    }
    }).start();
    }
    });
    }

    void login(){
    try{

    httpclient=new DefaultHttpClient();
    httppost= new HttpPost(“http://10.0.2.2/Aconnect/check.php”); // make sure the url is correct.
    //add your data
    nameValuePairs = new ArrayList(2);
    // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
    nameValuePairs.add(new BasicNameValuePair(“username”,et.getText().toString().trim())); // $Edittext_value = $_POST[‘Edittext_value’];
    nameValuePairs.add(new BasicNameValuePair(“password”,pass.getText().toString().trim()));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    //Execute HTTP Post Request
    response=httpclient.execute(httppost);
    // edited by James from coderzheaven.. from here….
    ResponseHandler responseHandler = new BasicResponseHandler();
    final String response = httpclient.execute(httppost, responseHandler);
    System.out.println(“Response : ” + response);
    runOnUiThread(new Runnable() {
    public void run() {
    tv.setText(“Response from PHP : ” + response);
    dialog.dismiss();
    }
    });

    if(response.equalsIgnoreCase(“User Found”)){
    runOnUiThread(new Runnable() {
    public void run() {
    Toast.makeText(FinalITSActivity.this,”Login Success”, Toast.LENGTH_SHORT).show();
    }
    });

    startActivity(new Intent(FinalITSActivity.this, verfiycourse.class));
    }else{
    showAlert();
    }

    }catch(Exception e){
    dialog.dismiss();
    System.out.println(“Exception : ” + e.getMessage());
    }
    }
    public void showAlert(){
    FinalITSActivity.this.runOnUiThread(new Runnable() {
    public void run() {
    AlertDialog.Builder builder = new AlertDialog.Builder(FinalITSActivity.this);
    builder.setTitle(“Login Error.”);
    builder.setMessage(“User not Found.”)
    .setCancelable(false)
    .setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    }
    });
    AlertDialog alert = builder.create();
    alert.show();
    }
    });
    }
    }

    this is my code. its looks exactly the same but there are some modifications.

    and this is my php codes.

    Reply
  56. Anusha V

    i have added internet permission to my manifest file but still i get errors in my log cat.
    1) once i press the login button in the emulator there is no navigation to login success page and there is no change as the login form remains the same. I only get validating user and no change happens.
    2) the error reported in the logcat is ” skipped 66 frames, the application is doing too much work on its main thread”
    3) what should be the android manifest file?
    4) i have done certain modifications in the code and i shall mail you the code.

    Please suggest some solution as soon as possible, as i am doing my project on android and having a bad deadline to submit it.

    Reply
    1. James Post author

      Please do the network operations in a new thread instead of main thread from android 2.3 onwards, otherwise it will not work.

      Reply
  57. Yazzne

    Thanks for the tutorial, I had not found a good tutorial like yours. I had no problems, everything works. Greetings.

    Reply
  58. Seif

    Can I ask you why didn’t you use Jsonparser .I didn’t even know that it’s possible to connect without it.

    Reply
    1. James Post author

      you can use json parser also, this is just another example.

      Reply
  59. gh_ez

    Hi james great tuto,but i’ve got some problems :s
    when i press the login button it says :
    “user not found” although i entered the right values.
    response from php : no database selected.
    any

    Reply
    1. James Post author

      Please check your database name and logic you have changed.

      Reply
  60. Carissa

    Hi, I’m new to android. I’m attempting to understand this code; however I can’t to seem to fully apprehend how you came up with this piece of code
    httppost= new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/check.php”);
    Can you please explain what exactly was placed in the brackets?

    Reply
    1. James Post author

      Its the server address where your server side code is located. 10.0.2.2 means it is localhost or your system is your server.

      Reply
  61. jagveer

    i m trying to runn this appplication at my local hpst..with this refferece in this index.php is name of table

    is is right,? because i m not getting output of this application
    httppost= new HttpPost(“http//localhost/index.php”);

    Reply
  62. Pingback: How to create Simple Login form using php in android? – Connect php with android. | nileshtpatil

  63. Sanal

    Hi,

    where i paste these codes

    “package pack.coderzheaven;

    import java.util.ArrayList;
    import java.util.List;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class AndroidPHPConnectionDemo extends Activity {
    Button b;
    EditText et,pass;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List nameValuePairs;
    ProgressDialog dialog = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    b = (Button)findViewById(R.id.Button01);
    et = (EditText)findViewById(R.id.username);
    pass= (EditText)findViewById(R.id.password);
    tv = (TextView)findViewById(R.id.tv);

    b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, “”,
    “Validating user…”, true);
    new Thread(new Runnable() {
    public void run() {
    login();
    }
    }).start();
    }
    });
    }

    void login(){
    try{

    httpclient=new DefaultHttpClient();
    httppost= new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/check.php”); // make sure the url is correct.
    //add your data
    nameValuePairs = new ArrayList(2);
    // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
    nameValuePairs.add(new BasicNameValuePair(“username”,et.getText().toString().trim())); // $Edittext_value = $_POST[‘Edittext_value’];
    nameValuePairs.add(new BasicNameValuePair(“password”,pass.getText().toString().trim()));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    //Execute HTTP Post Request
    response=httpclient.execute(httppost);
    // edited by James from coderzheaven.. from here….
    ResponseHandler responseHandler = new BasicResponseHandler();
    final String response = httpclient.execute(httppost, responseHandler);
    System.out.println(“Response : ” + response);
    runOnUiThread(new Runnable() {
    public void run() {
    tv.setText(“Response from PHP : ” + response);
    dialog.dismiss();
    }
    });

    if(response.equalsIgnoreCase(“User Found”)){
    runOnUiThread(new Runnable() {
    public void run() {
    Toast.makeText(AndroidPHPConnectionDemo.this,”Login Success”, Toast.LENGTH_SHORT).show();
    }
    });

    startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
    }else{
    showAlert();
    }

    }catch(Exception e){
    dialog.dismiss();
    System.out.println(“Exception : ” + e.getMessage());
    }
    }
    public void showAlert(){
    AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() {
    public void run() {
    AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
    builder.setTitle(“Login Error.”);
    builder.setMessage(“User not Found.”)
    .setCancelable(false)
    .setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    }
    });
    AlertDialog alert = builder.create();
    alert.show();
    }
    });
    }
    }”

    on mainactivity.java ?? comming 20 errors

    Reply
    1. James Post author

      The error might have came when you copied the code from my site. please check each line.

      Reply
  64. ohail

    thank you , for this useful tutorial but i got problemin “org.apache.http.meesage.BasichttpResponse@242a8890”

    please Help??

    Reply
  65. prathima

    Hi,
    I downloaded the code. there is no errors in the code but if i click on login button its not getting or starting the UserPage.java. Can anyone pls do help me out in this what i have to do.

    Regards,
    Prathima

    Reply
    1. James Post author

      You may have to change the code according to the instruction in the tutorial.

      Reply
  66. Ayan

    Whenever I try to login its showed ‘login error’ and show the line of php which written on php file.

    Reply
  67. fahad

    Thank for your tutorial
    i did same what you did from mysql to php and android
    and i insert from phpmysql username and passowrd

    but when i run the app on emulator
    i got this error message

    ” Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use musql or PDO instead in ”

    what i should do ?

    note : im using wamp so i set my_folder_inside_htdocs under this root

    C:\wamp\www\my_folder_inside_htdocs

    looking forward to hear from you

    Reply
    1. James Post author

      Please use the latest version of the function
      mysql_connect() may be deprecated…so there will be another method similar to it. Use that.
      This should not cause any problem.

      Reply
  68. JIWOOK

    Dear Author
    Thanks for your good examples and tutorials!
    By the way,
    I did all the processes you wrote down in article,
    I corrected URL in AndroidPHPConnectionDemo.java and PHP file.
    but when I execute this program on my android device,
    Login button does not work.
    It do not retrieve any validating messages and fail messages,
    remaining only login front page.
    What should I do?

    Reply
    1. James Post author

      Could you please check the Logcat and see what is happening when you click Login Button.

      Reply
  69. Sadia

    I downloaded the code. there is no errors in the code but if i click on login button it gives error user not found and at login page it displays message Response from PHP: NO databasse selected … waiting for your reply thanks …

    Reply
  70. fahad

    Hello this is useful it works with me but i need to add one more thing and i tried many times but i couldn’t make it

    the access is happening from one table form mysql and it navigate me to one page
    i added one field to that database which is “role”

    if the “role” is a “student” it will navigate me to page1
    and if the “role” is a ” faculty” it will navigate me to page2

    how i can apply this ?

    looking forward to hear from you

    Reply
    1. fahad

      sorry didn’t complete my previous post well
      here is extended post

      what i would to achieve as i said i added one more field to that table i call it “role”

      the purpose for this is that i would like to have a navigation according to “role”

      for example
      if the user enters his username and password and clicks on login button it will check that username and password if it is available and his role is “student” it will navigate him to page1
      and if the “role” is “faculty”it will navigate him to page2

      how i can achieve this ?

      looking forward to hear from you

      Reply
      1. James Post author

        Did you managed to connect to PHP and authenticate?
        If yes, then pass the “role” as parameter along with the intent for navigation to the next page and get it there and do accordingly.
        Check this post

        Reply
  71. fahad

    yes i could connect with php
    i guess my problem comes in if statement

    i will mail you the code there

    Reply
  72. Mayur Thole

    I import the project into eclipse. and trying to run on emulator but after entering the data into text field . when i click on login button . only validating user is come .. and then after some time nothing will happen on screen.
    I also added internet permission in manifest file. and also but i am not connected to internet. i just want it add check the user exist or not without internet on localhost xampp server. i have added the url
    http://localhost/my_folder_inside_htdocs/check.php but still not working. ..

    Reply
  73. anand

    where to create the check.php file?

    do i need to create php project using eclipse (file->new->PHP project) or
    directly create a notepad file with .php extension.

    By doing what u have told , after entering username, password while i click login its says validating user and stays in the login page itself. there is no response.

    Note: i have created database with sample values and connected through java http connection

    Reply
    1. James Post author

      since we are calling a script in the server, check.php should be in the server.

      Reply
      1. anand

        httppost = new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/check.php”);

        is this statement right. i am using xampp server and AVD for launching in eclipse. what would supposedly be the IP address i need to refer is it 10.0.0.2 or 127.0.0.1

        Reply
  74. anand

    Response from php: parse error:
    syntax error:unexpected mysql_select_db

    i think i am almost there , but i cant understand this error in android emulator

    note: log cat and console are free of errors

    Thanks in advance!!!!

    Reply
  75. yogesh

    hi james..i am copy ur code and some place i currect the my relavent code..but that time i am insert currect username or wrong username password that time same error is shown user not found…so why waht is the problem..

    Reply
  76. ayse

    Hi, I want to make session control with php and android .Could you help me about this subject?

    Reply
  77. Pingback: Php Program For Login Form

  78. Aditya

    Sir, the code opens debug perspective on button click and the logcat error shows—> skipped 103 frames..the application may be doing too much work on the main thread….pls help me sir as my complete BE project depends on it.

    Reply
  79. Shierbon

    sir James what is the 10.0.2.2 is this a server or an ip address thanks for your reply

    httppost= new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/check.php”);

    Reply
    1. James Post author

      10.0.2.2 is the localhost for Android. If you are using your developments system;s localhost as Host, then you should use this.

      Reply
  80. Anonymous

    This tutorial is very helpful but there is a problem in my php file.
    It is giving my error that variable in which i am taking input from the user is undefined index.
    I m taking phoneNumber as a input.
    The id of the TextField in xml file is textView1 and the MainActivity I defined a String of “PhoneNumber”.
    This “PhoneNumber” is giving error in the lines below
    $PhoneNum=$_POST[‘PhoneNumber’];
    $query=”INSERT INTO phonebook(PhoneNumber) values(‘{$PhoneNum}’)”;

    Reply
    1. James Post author

      $query=”INSERT INTO phonebook(PhoneNumber) values(‘$PhoneNum’)”;

      Check the “Case” also.

      Reply
  81. Jana

    You need to register the activity in AndroidManifest.xml to make it go to UserPage after login.

    Reply
  82. Anonymous

    this code is giving me this error when i run it
    AndroidPHP does not specify a android.test.InstrumentationTestRunner instrumentation.

    Reply
  83. Kiran

    On Click login button , it is just showing validating user, rest all is not coming up.

    Reply
  84. kyun

    Hi James, i have this error.
    Notice: Undefined index: user_login in C:\xampp\htdocs\check\check.php on line 12

    Notice: Undefined index: user_pass in C:\xampp\htdocs\check\check.php on line 13
    No Such User Found

    this my check.php

    when i login in my android. android studio log error :
    Exception : Connection to http://127.0.0.1 refused

    how can i fix it, sorry my english so bad. thx u so much for tutorial, ^^

    Reply

Leave a Reply

Your email address will not be published.