150 thoughts on “Android phpMysql connection

  1. Pingback: ANDROID - Upload an image to a server | Coderz Heaven

    1. subhash

      public void Move_to_next()
      {

      // startActivity(new Intent(this, zzz.class));
      }

      in my case my new activity is not started plaese help me anyone ?

      Reply
  2. Anubhav

    can you pls tell me what permissions to write in manifest.xml????

    and the namevaluepair is giving error……. I dont know why????

    Reply
    1. James

      Did you import this one “import org.apache.http.NameValuePair“, Check whether your case is correct or not. This is the permission you need to set in androidmanifest.xml

      android:name=”android.permission.INTERNET

      Place this before or after the application tag.

      Reply
  3. Soorya Post author

    It is a collection…..No need to add permission in the Manifest. Only Internet Permission is required…Can you specify the details of the error.

    Reply
  4. Pingback: Android « thomastka

  5. nik

    I also have error in my eclipse in the following line:

    nameValuePairs = new ArrayList(2);

    how do i fix it?

    import org.apache.http.NameValuePair is already insert.

    Reply
    1. James

      Hi nik……
      I think there is some problem in the case. change the “namevaluepair” to “nameValuePairs” in the error line.
      I think this will work.

      Reply
  6. Soorya Post author

    sorry friends…..use “NameValuePair” instead of “namevaluepair”………
    It might have occured when i copied the code…….

    Reply
    1. Milind

      plz…..can you post your enyire code…i’m trying get conn.btween mysql database in android app.for many days but i failed….!!

      Reply
  7. peter

    hello….i try this .. i dont know implement this ……..
    httpclient = new DefaultHttpClient();
    httppost = new HttpPost(“http://10.0.2.2/android/user_validate.php”);

    What is this ? ….is it connect to php “validate.php”

    http://10.0.2.2/ /// is it local host …….

    already everthing i done ….base on ur tutorial…….i use eclipe java ……it how to connect with php file……

    Reply
    1. James

      Hello Peter 10.0.2.2 is the localhost…
      If you want to try it in a remote domain then change it to http://yourdomain.com/your_folder/your_phpfile
      Try creating a sample file in the localhost and a simple echo inside it. then connect using the above code.
      For eg: your file name is test.php and you have a folder named test_folder then change the URL to http://10.0.2.2/test_folder/test.php
      This will work. make sure you are printing out the output. The output will be a stream, make sure to convert it to a string..
      There is a sample post for that also . Let us know if you have any more doubts. Also while connecting to localhost make sure your server is running

      Reply
  8. uly

    I got lost somewhere here… how do you use connection.php and user_validate.php. are you referring to a one file sir? I got invalid user response and when i check the logcat it says something like no window to dispatch pointer action 1.

    Reply
    1. James

      Those are two files, the connection.php is used for connecting to mySQL database and other file you can use as you wish , you can have anything inside it. The error you got is not due to these files.
      If you have any doubt, send your project to coderzheaven@gmail.com

      Reply
  9. webhostingpad coupon

    Thanks for another informative website. Where else could I get that kind of info written in such an ideal way? I’ve a project that I am just now working on, and I’ve been on the look out for such information.

    Reply
  10. alaa

    i tried to implement code but when i try to run it always say invalid password it not check buffer why this the code after edit

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

    app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
    username = (EditText) findViewById(R.id.editText1);
    password = (EditText) findViewById(R.id.editText2);
    login = (Button) findViewById(R.id.button1);
    check = (CheckBox) findViewById(R.id.check);

    b2 = (Button) findViewById(R.id.button2);
    String Str_user = app_preferences.getString(“username”,”0″ );
    String Str_pass = app_preferences.getString(“password”, “0”);
    String Str_check = app_preferences.getString(“checked”, “no”);
    if(Str_check.equals(“yes”))
    {
    username.setText(Str_user);
    password.setText(Str_pass);
    check.setChecked(true);
    }

    b2.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v)
    {
    startActivity(new Intent(“ied.Graduationproject.TUTORIALONE”));

    }
    });

    login.setOnClickListener(new View.OnClickListener()
    {

    public void onClick(View v)
    {
    name = username.getText().toString();
    pass = password.getText().toString();
    String Str_check2 = app_preferences.getString(“checked”, “no”);
    if(Str_check2.equals(“yes”))
    {
    SharedPreferences.Editor editor = app_preferences.edit();
    editor.putString(“username”, name);
    editor.putString(“password”, pass);
    editor.commit();
    }
    if(name.equals(“”) || pass.equals(“”))
    {
    Toast.makeText(Graduationproject.this, “Please Enter your Information”, Toast.LENGTH_LONG).show();
    }
    else
    {
    try {
    httpclient = new DefaultHttpClient();
    httppost = new HttpPost(“http://10.0.2.2/brca/check.php”);
    // Add your data
    nameValuePairs = new ArrayList(2);
    nameValuePairs.add(new BasicNameValuePair(“username”, name.trim()));
    nameValuePairs.add(new BasicNameValuePair(“assword”, pass.trim()));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    response = httpclient.execute(httppost);
    inputStream = response.getEntity().getContent();
    String res=inputStream.toString();
    data = new byte[256];

    buffer = new StringBuffer();
    int len = 0;
    while (-1 != (len = inputStream.read(data)) )
    {
    buffer.append(new String(data, 0, len));
    }

    inputStream.close();
    }

    catch (Exception e)
    {
    Toast.makeText(Graduationproject.this, “error”+e.toString(), Toast.LENGTH_LONG).show();
    }

    if(buffer.charAt(0)==’Y’)
    {
    Toast.makeText(Graduationproject.this, “login successfull”, Toast.LENGTH_LONG).show();

    Move_to_next();

    }

    else
    {
    Toast.makeText(Graduationproject.this, “Invalid Username or password”, Toast.LENGTH_LONG).show();
    }

    }

    }

    });
    check.setOnClickListener(new View.OnClickListener()
    {
    public void onClick(View v)
    {
    // Perform action on clicks, depending on whether it’s now checked
    SharedPreferences.Editor editor = app_preferences.edit();
    if (((CheckBox) v).isChecked())
    {

    editor.putString(“checked”, “yes”);
    editor.commit();
    }
    else
    {
    editor.putString(“checked”, “no”);
    editor.commit();
    }

    }

    });

    }
    public void Move_to_next()
    {

    startActivity(new Intent(this, Wellcom.class));

    }

    }

    Reply
    1. Soorya Post author

      frind…this is the same code…….i think there must be error in the php file….may be the mysql query not returning the correct value

      Reply
    2. Priya

      Thanks for your tutorial .this was really helpful.
      But i need a favor , can u show me how to insert values of radio button , check box and dropdown list into mysql using php.
      If you could help me through this then i would be really thankfull to you.

      Reply
      1. James

        identify each values with a key. Like if there are two radio buttons like male and female, then add to the database as 0 or 1 and then while retreiving from the database just check whether it is 0 or 1 and check the radio button. Do the same with other controls also.

        Reply
  11. alaa

    i want to ask another question can i get sample code for insert to mysql

    Reply
  12. Pankaj Doshi

    I am getting errors in these lines :

    setContentView(R.layout.login);
    app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

    //error is : ‘login’ can’t be resolved or is not a field

    login = (Button) findViewById(R.id.login);
    //error is : ‘id’ can’t be resolved or is not a field

    Reply
    1. Soorya Post author

      Its not due to the code…..May be your project do not have the “gen” folder…..thas why this error.Try clean the project.If that doesnt work then right click(project)–>properties–>android–>check any target and click ok

      Reply
    2. James

      Login is the layout xml file. Rename your main.xml to login.xml

      Reply
  13. Pankaj Doshi

    dude thanks for the reply

    i do have a gen folder with R.java file in it
    R.java cannot be modified so despite doing the quick fix in eclipse i cant solve the errors

    i must say the AndroidManifest.xml is proper with no errors..i have put the reqd permission only the error is what i have mentioned above

    Reply
    1. Soorya Post author

      k frnd…..bt usually this error occur in above mentioned situations…thas why…Have you tried creating a new project and then copying the contents..

      Reply
  14. Pankaj Doshi

    yes yes i created a new android project
    then entered the following as per ur code:
    project name:mydatabaseProject
    package name: com.ar.mydatabaseProject.pack
    activity name : mydatabaseProject
    application name : mydatabaseProject

    and then i inserted that permission in manifest.xml and also copied same code in main.xml as what is provided in this page

    if ur online rite now , can u just do a teamviewer session …dat will help solve problems quickly i guess

    Reply
  15. Pankaj Doshi

    My problem are those errors that I have mentioned above , i m running the code in eclipse … i have all the android sdk installed ( no issues with that and the ADK plugin is also der..all pre requisites reqd for android coding are present )

    but however i am getting those errors mentioned above..so i cant run my code…please help

    Reply
  16. Pankaj Doshi

    yup sent a mail to ur given address ..thnx for immediate reply and please reply back soon

    and btw u dnt need to have an account for teamviewer..it’s an open source software ..google for teamviewer …it’s a cool way to remote access someone’s machine

    Reply
    1. James

      Sorry pankaj, U can send us emails. We will reply as fast as we can.

      Reply
  17. Pankaj Doshi

    hey thanks a lot for the quick reply guys !! I just have one problem more which i hv mailed u ..please check it and tell me asap

    thanks once again !!

    Reply
  18. Anthony

    Great tutorial, but lets just say that I wanted to have a home page after a successful login. How do I go about that? Point me in the right direction.

    Reply
    1. James

      Create a new class that extends activity and call this class using startActivity.

      Reply
  19. Jeba

    i have did every thing as per the instruction…. and its really happy for me to se such an awesome tutorial…

    nw my problem is, i have insterted values fr username and password… but then what ever the valued i give in the emulator and press Login Button it says
    “The Application Has Stopped UnExpectedly, Pls Try Again ”
    Im facing this repeatedly…. but there is no error shown in the java as well as xml code.

    is there any problem with php?
    im using xampp and ive changed the host address… i got a folder inside it and saved those two php. in the java file also i have provided the link for php.
    Pls reply. Thanx in Advance.

    Reply
    1. Jeba

      And also i need to know…. how to get redirected to another page after that validation…. thanx fr ur support….

      Reply
      1. James

        Create another class that extends activity. here I name it secondActivity.java that extends activity. Note that It should have onCreate function like anyother activity.
        After that call this function.
        startActivity(new Intent(your_activity.this,secons_activity.class));
        call finish() on second_activity to close the activity.

        Reply
    2. James

      Hello Jeba :- No, that problem is probably not from the php side. When you get this Force Close open the Logcat window from the “window->show View-> Logcat. You will be seeing the error in the red color.
      Paste that error( (first two lines) here then only I can help you. Did you put the “http://” in the url.

      Reply
  20. Jeba

    Thank u fr d prompt reply sir…. i have put http already.

    here is the report from log cat… kindly resolve this issue for me.
    07-17 21:06:02.406: WARN/dalvikvm(402): threadid=1: thread exiting with uncaught exception (group=0x40015560)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): FATAL EXCEPTION: main
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): java.lang.NullPointerException
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at encore.bankdroid.bankdroid$1.onClick(bankdroid.java:107)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.view.View.performClick(View.java:2485)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.view.View$PerformClick.run(View.java:9080)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.os.Handler.handleCallback(Handler.java:587)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.os.Handler.dispatchMessage(Handler.java:92)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.os.Looper.loop(Looper.java:123)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.app.ActivityThread.main(ActivityThread.java:3683)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at java.lang.reflect.Method.invokeNative(Native Method)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at java.lang.reflect.Method.invoke(Method.java:507)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    07-17 21:06:02.436: ERROR/AndroidRuntime(402): at dalvik.system.NativeStart.main(Native Method)
    07-17 21:06:02.476: WARN/ActivityManager(60): Force finishing activity encore.bankdroid/.bankdroid

    Reply
    1. Jeba

      Thats Ok Sir….. in the previous post i have just copied the error from the logcat. could you pls resolve me? Still im facing the error message
      “Application has stopped un expectedly… ” then Force Close Button….
      pls sir….

      Reply
  21. Jeba

    Dear sir James, currently i.ve started to do a Simple Mobile Banking App as assignment to collg. it will be realy helpful if u send me any sample codes of any simple mobile banking with basic functionalities…. thanx in advance.

    Reply
    1. James

      Sorry Jeba, I can only help you if you have any doubts. Ask your doubts and I will clear that.

      Reply
      1. Jeba

        dear sir…. as u hav asked i hav pasted the first two lines of the error frm the Log Cat….

        Pls help me….

        07-18 20:18:25.795: ERROR/AndroidRuntime(326): FATAL EXCEPTION: main
        07-18 20:18:25.795: ERROR/AndroidRuntime(326): java.lang.NullPointerException

        Reply
        1. James

          Oh Jeba, this is not enough. My suggestion is try commenting each like inside onclick function and see which line has the problem.
          Or Can you see the a line starting with “cause” in the Logcat when the app crashes. Paste that line.

          Reply
          1. Jeba

            sir…. unexpectedly i have deleted that database… and now created another one similiar to that , i hav configured the php file. and inserted username and password admin admin

            and now its saying Invalid Username/password

          2. James

            Hi Jeba: Print out the username and a password you are sending from android from php file and see.

          3. Jeba

            I cant undrstnd that…. hw to do?
            u mean to echo in php? wil u pls giv me an example ? pls….
            thanx…

          4. Soorya Post author

            NO frind…..In java print the result from the php script using LOG.D, the result you can see in the logcat…or use TOAST to display .

          5. Jeba

            dear sir…
            i’m sory … i ve tried .. im nt able to find…. will u show me hw to do that ? im a very started to android and programming….

  22. Max

    I’m getting an error with

    “setContentView(R.layout.login);”
    It says layout.login isn’t in my R file, now there is a layout.main and since R is the autogenerated file, it deletes any manual alterations to it.

    So my question is, what/where do I need to insert/edit my files to find what adds layout.login

    (I already copied the xml file above to my main xml)

    Reply
    1. Max

      NVM my original Post, I fixed that (it was quite simple, I simply changed layout to main but you can probably alternatively rename main to layout)

      When ever I try to launch this program in my emulator, it just force closes, I can’t seem to find any error messes or anything. So I’m a little lost as to why this won’t atleast open.

      Reply
  23. Pingback: Android phpmySQL connection redone. | Coderz Heaven

  24. datadiary

    i like this most and it’s really nice site and good content it had and above script will help me lot thanks for it…..

    Reply
  25. jaymo

    Hi james,loved the tutorial,my code has no error in it,I have even got the emulator to run the code however no matter what password and username pair i use it still displays the error login Toast,I have gone through it,and am sure it doesnt have any syntax error,what could be the problem,or cant it acess the (xampp server).But if i ping 10.0.2.2 from the emulator terminal it can see the server

    Reply
    1. James

      Are you getting any response from the server side while running the code. Try to echo back the values you are sending from the android side(eg. Username and password).
      Or try this code. we have redone this code to help it understand more easily.

      Reply
  26. Karthy

    Hi
    Im getting following exception in Android

    ================================================
    FATAL EXCEPTION: main
    java.lang.NullPointerException
    at com.loginapp.LoginAppActivity$1.onClick(LoginAppActivity.java:121)
    at android.view.View.performClick(View.java:2408)
    at android.view.View$PerformClick.run(View.java:8817)
    at android.os.Handler.handleCallback(Handler.java:587)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:143)
    at android.app.ActivityThread.main(ActivityThread.java:4914)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    at dalvik.system.NativeStart.main(Native Method)
    Force finishing activity com.loginapp/.LoginAppActivity
    ================================================

    Reply
  27. RYS

    Hi James, I’m new to android, I already search and trying many example on how to retrieve data from Mysql to android but seem no one success. :<"

    Reply
  28. Reval

    Hi guys

    Nice Tut, there is only one problem I am stuck!

    I am using IntelliJ Idea as an IDE and Android Version 2.3.3

    I copyied and pasted your code but I get the following error:

    error: cannot find symbol variable login

    It doesnt even open in the AVD I get the error in the error console after the code suddenly stops while compiling.

    Please help me. I am researching for my final year project and I really need my android app to connect to a MySQL server.

    Help will be much appreciated
    Thanks in Advance

    Reply
  29. sds65805

    the android code is great, but your explination of what to do with mySQL and PHP lost me somewhere. What php files need to be created? I see reference to “connection.php”, ‘Connections/localhost.php’, ‘the main PHP file’, and “user_validate.php”. But I only see code for two php files. Am I suppose to create a ‘localhost.php’ file?

    Reply
    1. James

      There is no localhost.php file, there is only connection.php which contains the code for connection with the database. You can connect to ant php file if the path is correct and the server is running,

      Reply
      1. sds65805

        I was able to get it working.
        In the first line of your “user_validate.php” you reference ‘Connections/localhost.php’, which I believe should be ‘connection.php’.
        To get things working I replaced the first line of the “user_validate.php” with the code needed to connect login to the host server.
        $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost).
        I understand that proper mysql coding suggests having a separate file with he login credentials, but I was shooting for simplicity.
        Solid information on the android side. Best code I have seen with regards to this.

        Reply
  30. mak

    hello there and thanks for the post!

    i have a problem in compering buffer.charAt(0) with either the ‘Y’ or ‘N’ character…it drives me crazy

    i can see that the php file returned Y/N but i cannot compare it with ‘Y’/’N’ in order to make a Succesful/unsuccesfull toast

    Reply
      1. mak

        thanks for your quick response james!!
        i am new in android developing and it is very beautiful to see a solidarity like this

        Reply
  31. krishnaveni

    hi…i have did every thing as per the instruction…. and its really happy for me to se such an awesome tutorial…

    nw my problem is, i have insterted values fr username and password… but then what ever the valued i give in the emulator and press Login Button it says
    “The Application Has Stopped UnExpectedly, Pls Try Again ”
    Im facing this repeatedly…. but there is no error shown in the java as well as xml code.

    is there any problem with php?
    im using xampp and ive changed the host address… i got a folder inside it and saved those two php. in the java file also i have provided the link for php.
    FATAL EXCEPTION: main
    java.lang.NullPointerException
    at com.loginapp.LoginAppActivity$1.onClick(LoginAppActivity.java:121)
    at android.view.View.performClick(View.java:2408)
    at android.view.View$PerformClick.run(View.java:8817)
    at android.os.Handler.handleCallback(Handler.java:587)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:143)
    at android.app.ActivityThread.main(ActivityThread.java:4914)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    at dalvik.system.NativeStart.main(Native Method)
    Force finishing activity com.loginapp/.LoginAppActivity
    Pls reply. Thanx in Advance.

    Reply
  32. Pingback: MySql connection - Android Forums

  33. krishnaveni

    Hi james..
    nw my problem is, i have insterted values for username and password… but then what ever the valued i give in the emulator and press Login Button it says
    “The Application Has Stopped UnExpectedly, Pls Try Again”
    Im facing this repeatedly…. but there is no error is displayed in logcat..how it is cleared..help me ….

    Reply
  34. shan

    How to get the response from the php……
    The buffer.charAt(0)==’Y’ is not working for string..
    Please slove the problem ASAP……….

    Reply
  35. krishnaveni

    hi james,
    I am getting this error frequently when making HTTPConnection.
    The error is :
    Error in http connection java.net.SocketException: The operation timed out

    Sometimes it connects and sometimes not connected and displayed above timeout message…

    I have tried with various link.It behaves same with all.
    Why dis error is displayed…help me….

    Reply
  36. Orif

    Hi James,

    Your job is very helpful, thank you. Just wanted to clarify it’s important to run .php file in Xampp or Wampp? Because I have Vertrigo and during running the application by clicking login button I got a dialog box “Unfortunately, application has stopped” and program terminated. I tried several times, but result is the same. Here is the LogCat:

    01-09 19:57:35.046: D/gralloc_goldfish(556): Emulator without GPU emulation detected.
    01-09 19:57:54.166: D/AndroidRuntime(556): Shutting down VM
    01-09 19:57:54.166: W/dalvikvm(556): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
    01-09 19:57:54.195: E/AndroidRuntime(556): FATAL EXCEPTION: main
    01-09 19:57:54.195: E/AndroidRuntime(556): java.lang.NullPointerException
    01-09 19:57:54.195: E/AndroidRuntime(556): at jku.project.kusss.KusssActivity$1.onClick(KusssActivity.java:114)
    01-09 19:57:54.195: E/AndroidRuntime(556): at android.view.View.performClick(View.java:3480)
    01-09 19:57:54.195: E/AndroidRuntime(556): at android.view.View$PerformClick.run(View.java:13983)
    01-09 19:57:54.195: E/AndroidRuntime(556): at android.os.Handler.handleCallback(Handler.java:605)
    01-09 19:57:54.195: E/AndroidRuntime(556): at android.os.Handler.dispatchMessage(Handler.java:92)
    01-09 19:57:54.195: E/AndroidRuntime(556): at android.os.Looper.loop(Looper.java:137)
    01-09 19:57:54.195: E/AndroidRuntime(556): at android.app.ActivityThread.main(ActivityThread.java:4340)
    01-09 19:57:54.195: E/AndroidRuntime(556): at java.lang.reflect.Method.invokeNative(Native Method)
    01-09 19:57:54.195: E/AndroidRuntime(556): at java.lang.reflect.Method.invoke(Method.java:511)
    01-09 19:57:54.195: E/AndroidRuntime(556): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    01-09 19:57:54.195: E/AndroidRuntime(556): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    01-09 19:57:54.195: E/AndroidRuntime(556): at dalvik.system.NativeStart.main(Native Method)
    01-09 19:59:06.487: I/Process(556): Sending signal. PID: 556 SIG: 9

    Reply
  37. krishnaveni

    Hi….am finished ur login page successfully completed..now i like to need next activity..that next activity having logged in user firstname and lastname detail…so i wrote one query..

    $q=mysql_query(“SELECT firstname,lastname FROM customers WHERE (usertype =’A’)”);

    while($e=mysql_fetch_assoc($q))
    {
    $row[]=$e;
    }
    print(json_encode($row));

    here more number of admin user r logged in login page…that means admin users having permission… so here all admin user firstname and lastname displayed…but i need which admin person loged in login page that particular person detail only displayed…

    $q=mysql_query(“SELECT firstname,lastname FROM customers WHERE ((usertype =’A’)&&(‘krishnaveni’))”);
    itz not valuable coding…

    so plz give me some solutions…(i.e)krishnaveni,kannan,hariprasad r admin user means when krishnaveni loged means krishnaveni detail ly displayed…kannan logged means kannan details only displayed..i dono how it is do???? plz give me solutions….thanks in advance…

    Reply
    1. James

      This is really easy save the logged in username in a global variable or preferences or extras in the activity.Then get it in the next activity and query again the database with this username. that’s all.
      check these links for setting the global variable and for passing the extras in the intent.

      Reply
  38. krishnaveni

    hi james…stillnow i tried it…but i can’t do it…plz u r write the sample code for my requrirement and send me…plz help me james…

    Reply
  39. jenny

    Hi….v tried ur code…in the login page what username and pwd shld v giv….whatever we give its showing as “invalid username and password”….pls help us…we are new to android

    Reply
    1. James

      Hey jenny:- you decide your username and password. This question is irrelevant. Ur username and password should match the fields in the database, that’s all.

      Reply
  40. jenny

    Thank u james…we tried ur code tat u posted later(AndroidPHPConnectionDemo)…v gt the excat response in emulator…but in php side it s showing as undefined index:EditText_value….vat else shld v add in php side other than these 2 lines…..pls help us……

    Reply
    1. James

      ‘EditText_value’ should match the same variable that u use to send the parameters in the namevalue pairs. It is also case sensitive.

      Reply
  41. jenny

    Thank u so much 4 ur code…we gt the o/p…in our project v shld insert the data from android to server….in tat v hav several forms…in each form there are 3 pages…only if v click the save button in the 3rd page all the data in the 3 pages shld b saved together….4 tis v hav cookies concept in java…in android vat can v use….if u hav any sample code regarding tis can u pls mail me….pls help me…

    Reply
  42. jenny

    hi james,how to insert spinner(combobox) and checkbox values from android to mysql..please send d syntax also sample code if u have…v used scrollview 4 joining all those forms.. ur info s really helpful…please help us….

    Reply
    1. James

      Hay jenny:- First make a string with comma seperated with all the values in the spinner( like this “value1,value2,….”). Now send this to the mysql database ans store it there.
      Now when you want this , send this string from the mysql database and split it in the android side and repopulate the spinner. that’s all. Please leave comments if you have any doubt.
      You can send me messages on facebook, twitter and G+ also.

      Reply
      1. Jenny

        Hey james Thank u,….we tried as u said using the following code…

        static final String[] Places=new String[]{“india”,”australia”,”america”,”southafrica”};

        ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,Places);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        etPlaceofvisit.setAdapter(adapter);

        in the onclick() try block,i hav tis line
        nameValuePairs.add(new BasicNameValuePair(“Placeofvisit”,Places.toString().trim()));

        In the php side,
        $sql=mysql_query(“insert into countries(Placeofvisit) values(‘”.$_REQUEST[‘Placeofvisit’].'”)”);

        we are getting the error as [Ljava.lang.String;@412a9750
        vat changes i shld make in this code……..and if the chechbox is clicked how can i store the changes in mysql….
        could u pls make the changes in tis code & clarify our doubt regarding checkbox….Thanks 4 ur help…..

        Reply
  43. Jenny

    we are getting the error as [Ljava.lang.String;@412a9750 in the column of the table..

    Reply
  44. jenny

    hi James,
    v got d o/p for spinner…thank u… if the chechbox is clicked how can i store the changes in mysql…. if u have sample code for retrieving data from mysql in JSON format,can u pls send us…thank u soo much ..

    Reply
  45. jenny

    Hi james,
    can u pls help us on how to store the changes in mysql if checkbox is clicked….can u pls tell us the syntax….waiting 4 ur reply

    Reply
  46. Jenny

    Hi james,
    can u pls help us on how to store the changes in mysql if checkbox is clicked….can u pls tell us the syntax….waiting 4 ur reply

    Reply
    1. James

      Jenny : to Listen to checkbox add a listener to the checkbox and on isChecked() option run the code to update the SQL. I will put a simple post on this soon.

      Reply
  47. jenny

    hello James,
    pls send some sample code using javascripts in android…..
    like if weight is greater than 120,the textbox colour has to be changed….pls help…..send for checkbox also..pls reply james sir ..

    Reply
  48. jenny

    Hello James,
    Thank u so much ….for validation purposes in android what can we use….for ex if weight is less than 20 and greater than 120,the textbox colour has to be changed while we type that value…..how can we do this….Thank u so much for ur help

    Reply
  49. Jenny

    Hi James,
    We hav some doubts in the following program….this s for higligting the values if the value is 120….bt the color s nt getting changed…can u pls tell us vat modifications i shld make in tis code…pls help…v already posted u tis bt it was nt copied properly…..

    package org.example.act;

    import android.app.Activity;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.widget.EditText;
    import android.text.Editable;
    import android.text.TextWatcher;

    public class ActActivity extends Activity implements TextWatcher {
    private EditText et;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    et=(EditText)findViewById(R.id.etx);
    et.addTextChangedListener(this);

    }

    @Override
    public void afterTextChanged(Editable arg0) {
    // TODO Auto-generated method stub

    if(et.getId() 120)
    et.setHighlightColor(getResources().getColor(R.color.mycolor));

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
    int after) {
    // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub

    }

    }

    in string.xml,
    i added the line,
    #F5DC49

    Reply
    1. James

      hey jeni : –
      Change “et.getId() ” to Integer.parseInt(ed.getText().toString()).
      ie.

      if( Integer.parseInt(ed.getText().toString()) > 120){
      // do the highlighting.
      }

      Jeni Dont paste the full code here. instead send the code as attachment to coderzheaven@gmail.com

      Reply
  50. ebtehal

    Hi James
    very nice tutorial 🙂
    but i have this problem
    after clicking sign in button it displays a message unfortunatly database has stopped

    Reply
  51. Pingback: Using SQLite in ANDROID, A really simple example. | Coderz Heaven

  52. Pingback: ANDROID - Upload an image to a server | Coderz Heaven

  53. dan

    I am new to android apps, php, and sql. The main PHP code, is that a part of the connection.php file? If not, where do you create one? Can it be created in Eclipse? If yes, what folder should it reside under (e.g., res, assets). Any help is appreciated. Thank you.

    Reply
    1. admin

      yes create two php files connections.php and the other file. Then include the connections.php in the second file.
      OR you can put the two codes in the same file also.

      Reply
      1. Dan

        I created one php file named connection.php, which includes the code below and I saved it under C:….xampp/htdocs/test/connection.php

        0) { echo “Y”; }
        else {echo “N”; }

        Do I have to move this file to my Android app as well? If yes, in which folder do I save it?

        Reply
      2. Dan

        The php code in my previous post didn’t paste in its entirety. Anyway, I have one php file named connection.php, which contains both codes. The one below your comments: “For this create a “Connections.php” page as shown below” and the other one below “Then the main PHP file is to be created”. I really appreciate your help. It’s been a frustrating two week for me as I can’t seem to get passed the Login page point let alone do something else.

        Reply
  54. Dan

    I am getting syntax errors on token “>” in span class line in my .java file – expression expected after this token and reference type expected instead

    Reply
    1. admin

      Hello Dan, by including I meant including the ‘incude’ statement in php. Create two files inside your xampp/htdocs/test/ folder and that’s all. then call this php file from the android side using my example.
      If you want another simple explanation then see this post Android phpmySQL connection redone.

      Reply
      1. Dan

        Would you mind sending the entire code including php files to my email? I am showing a whole bunch of syntax errors that I can’t figure out how to to fix.

        Reply
          1. Dan

            One of the messages I am getting in my Eclipse Console after pressing the Login button….ActivityManager: Warning: Activity not started, its current task has been brought to the front

          2. James

            Hello Dan, These are not errors. Activity not started…. means you have run the code once and you are trying to run the code without editing anything(means no build change).

          3. Dan

            after entering user name and password and hitting Login, I get “Validating user…” message and then nothing. The screen doesn’t change to userpage.xml. Even when enter incorrect user name and password I get the same. Is it possible that my app is not talking to “mydatabase”?

          4. James

            Are you getting anything in the LogCat. First check whether you have internet connection in the emulator and check the important points I have written in the post. If you follow the steps exactly it will work for sure.

          5. Dan

            My LogCat says (after pressing the Login button)

            Connection to http:/…. refused.

            Error reading data file

            request time failed: java.net.SocketException: Address family not supported by protocol

          6. James

            check whether your emulator has internet connection and also check whether the server is running.

          7. Dan

            OK, so I finally got it to work!!! The only unknown is in the userpage.xml, which is supposed to replace the main screen if the login is successful, but it doesn’t. I see the Login Success after the validation process is complete, but the screen doesn’t change. Here is my code in

            MydatabaseActivity.java

            //there is some code here after which I have this code

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

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

            any ideas as to why userpage.xml doesn’t kick in?

          8. James

            Check the logcat. You may not have decalred the UserPage activity in the AndroidManifest.xml.

          9. Dan

            I got it to work. Finally!!! I had my UserPage activity in the Mainfest file in the wrong spot! What I am trying to do next (now that the user is logged in) is to have the android client pull the data (e.g., list of names) from remote Db and display as a list to the user. Can you please suggest how do I go about doing that! Or can you suggest a good tutorial.

  55. Pingback: How to create Simple Login form using php in android? - Connect php with android.

    1. James

      Hello Mourad:- After all date is a string, make it a string and update.

      Reply
  56. Nishant Mendiratta

    im using this following code …whenever i enter the values in fields and click the login button is shows me and error
    =>Unfortunately loginForm has stopped

    🙁

    package com.example.loginform;

    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    import android.widget.Toast;
    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 android.preference.PreferenceManager;
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.view.Menu;

    public class LoginTest extends Activity {

    Button login;
    String name=””,pass=””;
    EditText username,password;
    TextView tv;
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences ;
    List nameValuePairs;
    CheckBox check;

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

    app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    login = (Button) findViewById(R.id.login);
    check = (CheckBox) findViewById(R.id.check);

    String Str_user = app_preferences.getString(“username”,”0″ );
    String Str_pass = app_preferences.getString(“password”, “0”);
    String Str_check = app_preferences.getString(“checked”, “no”);
    if(Str_check.equals(“yes”))
    {
    username.setText(Str_user);
    password.setText(Str_pass);
    check.setChecked(true);
    }
    login.setOnClickListener(new View.OnClickListener()
    {
    public void onClick(View v)
    {
    name = username.getText().toString();
    pass = password.getText().toString();
    String Str_check2 = app_preferences.getString(“checked”, “no”);
    if(Str_check2.equals(“yes”))
    {
    SharedPreferences.Editor editor = app_preferences.edit();
    editor.putString(“username”, name);
    editor.putString(“password”, pass);
    editor.commit();
    }
    if(name.equals(“”) || pass.equals(“”))
    {
    Toast.makeText(LoginTest.this, “Blank Field..Please Enter”, Toast.LENGTH_LONG).show();
    }
    else
    {
    try {
    httpclient = new DefaultHttpClient();
    httppost = new HttpPost(“http://127.0.0.1/android/Test/login.php”);
    // Add your data
    nameValuePairs = new ArrayList(2);
    nameValuePairs.add(new BasicNameValuePair(“UserEmail”, name.trim()));
    nameValuePairs.add(new BasicNameValuePair(“Password”, pass.trim()));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    response = httpclient.execute(httppost);
    inputStream = response.getEntity().getContent();

    data = new byte[256];

    buffer = new StringBuffer();
    int len = 0;
    while (-1 != (len = inputStream.read(data)) )
    {
    buffer.append(new String(data, 0, len));
    }

    inputStream.close();
    }

    catch (Exception e)
    {
    Toast.makeText(LoginTest.this, “error”+e.toString(), Toast.LENGTH_LONG).show();
    }
    if(buffer.charAt(0)==’Y’)
    {
    Toast.makeText(LoginTest.this, “login successfull”, Toast.LENGTH_LONG).show();
    }
    else
    {
    Toast.makeText(LoginTest.this, “Invalid Username or password”, Toast.LENGTH_LONG).show();
    }
    }
    }
    });
    check.setOnClickListener(new View.OnClickListener()
    {
    public void onClick(View v)
    {
    // Perform action on clicks, depending on whether it’s now checked
    SharedPreferences.Editor editor = app_preferences.edit();
    if (((CheckBox) v).isChecked())
    {

    editor.putString(“checked”, “yes”);
    editor.commit();
    }
    else
    {
    editor.putString(“checked”, “no”);
    editor.commit();
    }
    }
    });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_login_test, menu);
    return true;
    }
    }

    Reply
  57. Nishant Mendiratta

    yes i thinks so ..!!

    i created an database and stored php script in local host “http://127.0.0.1/android/Test/login.php”

    Still not working 🙁

    Reply
    1. James

      Check the reason for force close in the LogCat and paste the reason here. Then only I can say anything about that.

      Reply
    2. James

      Check the reason for force close in the LogCat and paste the reason here. Then only I can say anything about that and reply.

      Reply
      1. Nishant Mendiratta

        08-14 17:26:20.342: E/Trace(666): error opening trace file: No such file or directory (2)
        08-14 17:26:42.713: E/AndroidRuntime(666): FATAL EXCEPTION: main
        08-14 17:26:42.713: E/AndroidRuntime(666): java.lang.NullPointerException
        08-14 17:26:42.713: E/AndroidRuntime(666): at com.example.loginform.LoginTest$1.onClick(LoginTest.java:113)
        08-14 17:26:42.713: E/AndroidRuntime(666): at android.view.View.performClick(View.java:4084)
        08-14 17:26:42.713: E/AndroidRuntime(666): at android.view.View$PerformClick.run(View.java:16966)
        08-14 17:26:42.713: E/AndroidRuntime(666): at android.os.Handler.handleCallback(Handler.java:615)
        08-14 17:26:42.713: E/AndroidRuntime(666): at android.os.Handler.dispatchMessage(Handler.java:92)
        08-14 17:26:42.713: E/AndroidRuntime(666): at android.os.Looper.loop(Looper.java:137)
        08-14 17:26:42.713: E/AndroidRuntime(666): at android.app.ActivityThread.main(ActivityThread.java:4745)
        08-14 17:26:42.713: E/AndroidRuntime(666): at java.lang.reflect.Method.invokeNative(Native Method)
        08-14 17:26:42.713: E/AndroidRuntime(666): at java.lang.reflect.Method.invoke(Method.java:511)
        08-14 17:26:42.713: E/AndroidRuntime(666): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        08-14 17:26:42.713: E/AndroidRuntime(666): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        08-14 17:26:42.713: E/AndroidRuntime(666): at dalvik.system.NativeStart.main(Native Method)

        Reply
  58. Adi

    Hello, Thanks for this great tutorial. I am facing a error in the line if(buffer.charAt(0)==’Y’). I commented this part and went on to run the code, then on clicking login, the toast message gives an error:
    org.apache.http.conn.HttpHostConnectException : Connection to http://localhost refused. Can you help me out. Thanks!

    Reply
      1. Adi

        thankyou sir, changing the host worked and now I am not getting even the buffer.charAt(0) error. But each time I login, it gives invalid username or password. I have entered the username and password combo correctly as in the database. Still getting this error. I tried an alternate entry but the same error. Any solution to this? Thanks again 🙂

        Reply
  59. Chandan

    please help me, The code run fine on emulator but whenever I run the app in android phone and click on login button, app is getting crashed and stops unexpectedly.

    //MainActivity.java

    package gps.attendance.android;

    //import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    import android.widget.Toast;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    //import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    //import org.apache.http.client.methods.HttpRequestBase;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    //import android.preference.PreferenceActivity;
    import android.preference.PreferenceManager;
    import android.app.Activity;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    //import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.TextView;
    //import android.widget.Toast;

    public class MainActivity extends Activity
    {
    /** Called when the activity is first created. */

    int ch=0;
    Button login;
    String name=””,pass=””;
    EditText username,password;
    TextView tv;
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences ;
    List nameValuePairs;
    CheckBox check;
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    login = (Button) findViewById(R.id.login);
    check = (CheckBox) findViewById(R.id.check);

    String Str_user = app_preferences.getString(“username”,”0″ );
    String Str_pass = app_preferences.getString(“password”, “0”);
    String Str_check = app_preferences.getString(“checked”, “no”);
    if(Str_check.equals(“yes”))
    {
    username.setText(Str_user);
    password.setText(Str_pass);
    check.setChecked(true);
    }
    login.setOnClickListener(new View.OnClickListener()
    {
    public void onClick(View v)
    {
    name = username.getText().toString();
    pass = password.getText().toString();
    String Str_check2 = app_preferences.getString(“checked”, “no”);
    if(Str_check2.equals(“yes”))
    {
    SharedPreferences.Editor editor = app_preferences.edit();
    editor.putString(“username”, name);
    editor.putString(“password”, pass);
    editor.commit();
    }
    if(name.equals(“”) || pass.equals(“”))
    {
    Toast.makeText(MainActivity.this, “Blank Field..Please Enter”, Toast.LENGTH_LONG).show();
    }
    else
    {

    try {
    httpclient = new DefaultHttpClient();
    httppost = new HttpPost(“http://118.139.185.68/login.php”);
    // Add your data
    nameValuePairs = new ArrayList(2);
    nameValuePairs.add(new BasicNameValuePair(“UserEmail”, name.trim()));
    nameValuePairs.add(new BasicNameValuePair(“Password”, pass.trim()));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    response = httpclient.execute(httppost);
    inputStream = response.getEntity().getContent();

    data = new byte[256];

    buffer = new StringBuffer();
    int len = 0;
    while (-1 != (len = inputStream.read(data)) )
    {
    buffer.append(new String(data, 0, len));
    }

    inputStream.close();
    }

    catch (Exception e)
    {
    Toast.makeText(MainActivity.this, “error”+e.toString(), Toast.LENGTH_LONG).show();
    }
    if(buffer.charAt(0)==’Y’)
    {
    Toast.makeText(MainActivity.this, “login successfull”, Toast.LENGTH_LONG).show();

    startActivity(new Intent(MainActivity.this, GpsMain.class));

    }
    else
    {
    Toast.makeText(MainActivity.this, “Invalid Username or password”, Toast.LENGTH_LONG).show();
    ch++;
    if(ch==2)
    {
    ch=0;
    startActivity(new Intent(MainActivity.this, second_step.class));

    /* Intent intent = new Intent(this, second_step.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    startActivity(intent);
    */
    }
    }
    }
    }
    });
    check.setOnClickListener(new View.OnClickListener()
    {
    public void onClick(View v)
    {
    // Perform action on clicks, depending on whether it’s now checked
    SharedPreferences.Editor editor = app_preferences.edit();
    if (((CheckBox) v).isChecked())
    {

    editor.putString(“checked”, “yes”);
    editor.commit();
    }
    else
    {
    editor.putString(“checked”, “no”);
    editor.commit();
    }
    }
    });
    }
    public void Move_to_next()
    {

    // startActivity(new Intent(this, zzz.class));
    }
    }

    _________________________________________________________________

    //activity_main.xml

    ___________________________________________________________________

    Reply
    1. James

      PLease paste the LogCat error here, then only I can give you the solution.

      Reply
  60. C

    hi James great tutes…I followed all 3 but still have the same problem in line

    httppost = new HttpPost(“http://10.0.0.2/my/login.php”);

    It doesn’t connect with the server..

    When I run login.php i have the URL on address-bar like this “http://localhost/my/login.php” when i used it instead, android app crashes… What should I do?
    Please Help it’s been several days still I can’t figure it out…

    Reply
  61. logu pushpa

    thanks for ur tutorial.i need a coding for storing the info in database(Mysql)using PHP.pls post any tutorial or send me coding..my mail id is logupushpa5@gmail.com as soon as possible.
    thank u :):)

    Reply
  62. Swapnil Gaikwad

    I have been searching for such kind of tutorials from last one month. Your posts are simple and very easy to understand. Keep posting new posts.
    Thank you.

    Reply
  63. Ayan

    Hey james…Thanks for this tutorials. But there some problem I face that whenever I try to connect its show wrong username and password and on the below of app show “response from our domain_name”.and full code which show if u check from browser. Help me pls..

    Reply
    1. James

      Did you checked your php code perfectly in a brower by hard coding the values before using it in android?

      Reply
  64. Pingback: Fix Vertrigo Http Error Windows XP, Vista, 7, 8 [Solved]

  65. kalai

    Can you please post how to insert user details into mysql database and retrieve the same content in simpleformat

    Reply
  66. Pingback: 连接到外部数据库-Android应用程序 – FIXBBS

  67. Pingback: Connecting to external database - Android application

Leave a Reply

Your email address will not be published. Required fields are marked *