First create a database  named “mydatabase” in MySql. Then create a table “tbl_user” with three fields (id, username and password).

The next step is to create a php page which will communicate between the  MySql database and the android application.

For this create a “Connections.php” page as shown below. It will set up a  connection to the database with the username and password

$hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";

$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

Then the main PHP file is to be created. Actually the android application will call this php file along with the data(username and password ) and this code will check the database. If the details is valid then it will return “Y” and otherwise return “N”.

Here the data is passed as POST method. We can also use GET method where the data is passed along with the url . Android support both these two features.


<?php 

  require_once('yourfolder/Connections.php'); 
  mysql_select_db($database_localhost,$localhost);

  $useremail = $_POST['UserEmail'];
  $password = $_POST['Password'];

  $query_search = "select * from tbl_user where username = '".$useremail."' AND password = '".$password.      
  "'";
   $query_exec = mysql_query($query_search) or die(mysql_error());
 $rows = mysql_num_rows($query_exec);

  if($rows --> 0) { 
       echo "Y"; 
  }
  else  {
       echo "N"; 
  }

?>

So by now we created php and the database part. Then we have to focus on android section. For this first create a xml file which will be our login screen.The screen look like this.

The layout of the xml is displayed below.

<RelativeLayout
	  xmlns:android="http://schemas.android.com/apk/res/android"
	  android:layout_width="fill_parent"
	  android:layout_height="fill_parent"
	  android:background="#ff2a1703"
	  android:fadingEdge="horizontal">
	 <TextView
	 		android:id="@+id/text"
	 		android:text="manage your projects..."
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:typeface="serif"
            android:textStyle="italic"
            android:layout_centerHorizontal="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="50dip"
            android:textSize="20sp" >
     </TextView>
	 <EditText
			android:id="@+id/username"
			android:layout_width="213dip"
			android:layout_marginTop="60dp"
			android:layout_below ="@+id/text"
			android:layout_centerHorizontal="true"
			android:layout_height="wrap_content"
			android:hint="username"
			android:gravity="center"
			android:textSize="18sp"
			android:typeface="sans"
			android:textStyle="italic">
	 </EditText>
	 <EditText
			android:id="@+id/password"
			android:layout_width="211px"
			android:layout_height="wrap_content"
			android:hint="password"
			android:textSize="18sp"
			android:typeface="sans"
			android:textStyle="italic"
			android:gravity="center"
			android:password="true"
			android:layout_marginTop="20dp"
			android:layout_below ="@+id/username"
			android:layout_centerHorizontal="true">
	 </EditText>
 	 <CheckBox
			android:id="@+id/check"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Remember me"
			android:layout_marginTop="10dp"
			android:layout_below ="@+id/password"
			android:layout_centerHorizontal="true">
	 </CheckBox>
	 <Button
			android:id="@+id/login"
			android:layout_width="141px"
			android:layout_height="wrap_content"
			android:text="Login"
			android:textSize="22sp"
			android:typeface="serif"
			android:textStyle="bold"
			android:layout_marginTop="20dp"
			android:layout_below ="@+id/check"
			android:layout_centerHorizontal="true">
	 </Button>
</RelativeLayout>

We now create the java file . This file should contain the 3 sections

1. Store the preference when the checkbox is checked
2. Establish a connection between this file and the php file
3. Validate the user

package com.ar.mydatabaseProject.pack;

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 mydatabaseProject extends Activity
{
    /** Called when the activity is first created. */

	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<NameValuePair> nameValuePairs;
	CheckBox check;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        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(mydatabaseProject.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show();
				}
				else
				{


			    try {
			    	httpclient = new DefaultHttpClient();
				    httppost = new HttpPost("http://10.0.2.2/android/user_validate.php");
			        // Add your data
			        nameValuePairs = new ArrayList<NameValuePair>(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(mydatabaseProject.this, "error"+e.toString(), Toast.LENGTH_LONG).show();
			    }
			    if(buffer.charAt(0)=='Y')
			    {
			    	Toast.makeText(mydatabaseProject.this, "login successfull", Toast.LENGTH_LONG).show();
			    }
			    else
			    {
			    	Toast.makeText(mydatabaseProject.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, zzz.class));
        }
}

At last don’t forget to put the permission in Manifest file

<uses-permission android:name="android.permission.INTERNET"></uses-permission>


Note : if you have any problem in working with this post, please check this more simple version here.

Here is another more detailed explanation.


How to create Simple Login form using php in android? – Connect php with android.

 

148 Comments

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

    • subhash February 29, 2012 at 11:43 am

      public void Move_to_next()
      {

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

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

       
      • James February 29, 2012 at 8:39 pm

        what is happening? Is your app crashing?

         
  2. Anubhav May 1, 2011 at 10:27 pm

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

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

     
    • James May 2, 2011 at 7:50 pm

      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.

       
  3. Soorya May 2, 2011 at 6:21 am

    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.

     
  4. Pingback: Android « thomastka

  5. nik May 3, 2011 at 1:15 pm

    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.

     
    • James May 3, 2011 at 7:39 pm

      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.

       
  6. Soorya May 4, 2011 at 9:31 pm

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

     
  7. Pharmd772 May 8, 2011 at 4:11 am

    Hello! interesting site!

     
  8. Pharmc307 May 16, 2011 at 4:17 am

    Hello! interesting site!

     
  9. arya May 16, 2011 at 5:27 am

    thanks for the tutorial. I will try this

     
  10. ishan May 17, 2011 at 3:30 pm

    this is great.. its worked for me 😀

     
    • Milind September 19, 2012 at 6:36 am

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

       
  11. peter May 23, 2011 at 10:28 am

    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……

     
    • James May 23, 2011 at 11:07 pm

      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

       
  12. uly June 10, 2011 at 1:10 pm

    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.

     
    • James June 10, 2011 at 9:56 pm

      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

       
  13. webhostingpad coupon June 15, 2011 at 4:06 am

    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.

     
  14. alaa June 16, 2011 at 1:10 pm

    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));

    }

    }

     
    • Soorya June 16, 2011 at 10:15 pm

      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

       
    • Priya February 13, 2014 at 7:41 am

      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.

       
      • James February 13, 2014 at 5:44 pm

        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.

         
  15. alaa June 16, 2011 at 1:12 pm

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

     
  16. Pankaj Doshi June 21, 2011 at 9:16 pm

    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

     
    • Soorya June 21, 2011 at 9:23 pm

      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

       
    • James June 21, 2011 at 9:49 pm

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

       
    • Nick May 21, 2012 at 7:47 pm

      remove import android.R and you are ok
      late response:<

       
  17. Pankaj Doshi June 21, 2011 at 9:28 pm

    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

     
    • Soorya June 21, 2011 at 9:32 pm

      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..

       
  18. Pankaj Doshi June 21, 2011 at 9:30 pm

    and yea my target is ticked ..it’s android 2.3.3

     
  19. Pankaj Doshi June 21, 2011 at 9:36 pm

    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

     
    • James June 21, 2011 at 9:38 pm

      What are your problems? Type in here we will help u.

       
    • Soorya June 21, 2011 at 9:40 pm

      we dont have an account there…..can you sent me your code to coderzheaven@gmail.com…..i wil check

       
  20. Pankaj Doshi June 21, 2011 at 9:42 pm

    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

     
  21. Pankaj Doshi June 21, 2011 at 9:55 pm

    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

     
    • James June 21, 2011 at 10:02 pm

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

       
  22. Pankaj Doshi June 22, 2011 at 5:33 pm

    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 !!

     
  23. Anthony July 12, 2011 at 4:04 pm

    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.

     
    • James July 12, 2011 at 9:36 pm

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

       
  24. Jeba July 17, 2011 at 4:19 pm

    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.

     
    • Jeba July 17, 2011 at 4:26 pm

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

       
      • James July 17, 2011 at 6:14 pm

        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.

         
    • James July 17, 2011 at 6:06 pm

      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.

       
  25. Jeba July 17, 2011 at 9:08 pm

    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

     
    • Jeba July 18, 2011 at 12:56 pm

      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….

       
  26. Jeba July 17, 2011 at 11:26 pm

    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.

     
    • James July 17, 2011 at 11:49 pm

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

       
      • Jeba July 18, 2011 at 8:17 pm

        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

         
        • James July 18, 2011 at 10:46 pm

          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.

           
          • Jeba July 18, 2011 at 10:57 pm

            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

             
          • James July 19, 2011 at 6:58 am

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

             
          • Jeba July 19, 2011 at 8:17 pm

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

             
          • Soorya July 19, 2011 at 9:14 pm

            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 .

             
          • Jeba July 20, 2011 at 11:25 am

            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….

             
  27. Max July 27, 2011 at 9:18 am

    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)

     
    • Max July 27, 2011 at 9:37 am

      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.

       
    • James July 28, 2011 at 6:11 am

      Hello max: Check the latest post. This will help you.

       
  28. Pingback: Android phpmySQL connection redone. | Coderz Heaven

  29. datadiary August 1, 2011 at 12:43 pm

    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…..

     
  30. savin August 4, 2011 at 9:24 pm

    good sharing !!! thanks

     
  31. jaymo August 8, 2011 at 11:21 am

    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

     
    • James August 8, 2011 at 8:09 pm

      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.

       
  32. Karthy August 17, 2011 at 11:44 pm

    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
    ================================================

     
  33. RYS September 9, 2011 at 3:17 pm

    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. :<"

     
  34. Reval September 22, 2011 at 9:12 pm

    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

     
  35. sds65805 November 7, 2011 at 3:10 am

    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?

     
    • James November 7, 2011 at 10:42 pm

      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,

       
      • sds65805 November 8, 2011 at 3:40 am

        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.

         
  36. mak December 15, 2011 at 9:21 pm

    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

     
  37. krishnaveni December 23, 2011 at 10:37 am

    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.

     
  38. Pingback: MySql connection - Android Forums

  39. krishnaveni December 27, 2011 at 2:42 pm

    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 ….

     
  40. shan January 3, 2012 at 5:30 pm

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

     
    • James January 3, 2012 at 8:46 pm

      Hey Shan Please check this post http://coderzheaven.com/2011/07/android-phpmysql-connection-redone/
      or buffer.charAt(0)==’Y’ will work for string. PLease print that string in the logcat and check.
      or sent another string from php side and check it in the android side, like send “success” and compare that string in the android side.

       
  41. krishnaveni January 5, 2012 at 11:10 am

    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….

     
  42. Orif January 10, 2012 at 12:30 am

    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

     
  43. krishnaveni January 31, 2012 at 9:39 am

    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…

     
    • James January 31, 2012 at 8:20 pm

      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.

       
  44. krishnaveni February 1, 2012 at 11:06 am

    thanks for very useful solutions…but i can’t handle it…so how is handled dis coding in our login page..

     
  45. krishnaveni February 1, 2012 at 4:33 pm

    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…

     
  46. jenny February 6, 2012 at 3:40 pm

    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

     
    • James February 6, 2012 at 8:16 pm

      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.

       
  47. jenny February 8, 2012 at 4:02 pm

    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……

     
    • James February 8, 2012 at 10:16 pm

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

       
  48. jenny February 8, 2012 at 11:41 pm

    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…

     
  49. jenny February 9, 2012 at 3:16 pm

    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….

     
    • James February 9, 2012 at 8:21 pm

      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.

       
      • Jenny February 9, 2012 at 11:08 pm

        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…..

         
  50. Jenny February 9, 2012 at 11:13 pm

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

     
  51. jenny February 10, 2012 at 4:04 pm

    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 ..

     
  52. jenny February 11, 2012 at 8:32 pm

    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

     
  53. krishnaveni February 13, 2012 at 6:05 pm

    hi james,
    How is connecting mysql database using jdbc in android…

     
    • James February 13, 2012 at 9:24 pm

      Never tried it. I will check that.

       
  54. Jenny February 13, 2012 at 9:57 pm

    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

     
    • James February 14, 2012 at 8:57 pm

      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.

       
  55. jenny February 14, 2012 at 4:36 pm

    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 ..

     
  56. jenny February 15, 2012 at 5:59 pm

    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

     
  57. Jenny February 15, 2012 at 7:53 pm

    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

     
    • James February 15, 2012 at 9:00 pm

      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

       
  58. ebtehal March 1, 2012 at 2:43 am

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

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

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

  61. Anant April 14, 2012 at 12:14 pm

    Nice tutorial very helping ///great work//

     
  62. dan April 18, 2012 at 11:57 pm

    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.

     
    • admin April 19, 2012 at 4:56 pm

      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.

       
      • Dan April 20, 2012 at 2:52 am

        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?

         
      • Dan April 20, 2012 at 2:57 am

        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.

         
  63. Dan April 20, 2012 at 3:55 am

    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

     
    • admin April 20, 2012 at 4:55 pm

      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.

       
      • Dan April 21, 2012 at 4:09 pm

        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.

         
        • James April 22, 2012 at 5:59 am

          Hello Dan. PLease check your mail we have sent you the code. or else you can check this post where you can download the source from the link below the post.
          http://www.coderzheaven.com/2012/04/22/create-simple-login-form-php-android-connect-php-android/

           
          • Dan April 23, 2012 at 1:32 am

            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

             
          • James April 23, 2012 at 1:21 pm

            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).

             
          • Dan April 23, 2012 at 1:36 am

            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”?

             
          • James April 23, 2012 at 1:23 pm

            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.

             
          • Dan April 24, 2012 at 2:01 am

            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

             
          • James April 24, 2012 at 1:51 pm

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

             
          • Dan April 26, 2012 at 12:59 am

            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?

             
          • James April 26, 2012 at 3:51 pm

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

             
          • Dan April 29, 2012 at 9:34 pm

            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.

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

  65. Mourad May 11, 2012 at 11:53 am

    Hello, haw to update date from mysql database ??

     
    • James May 12, 2012 at 1:00 am

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

       
  66. Nishant Mendiratta August 13, 2012 at 8:40 pm

    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;
    }
    }

     
  67. Nishant Mendiratta August 13, 2012 at 8:46 pm

    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 🙁

     
    • James August 14, 2012 at 10:07 am

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

       
    • James August 14, 2012 at 10:16 am

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

       
      • Nishant Mendiratta August 14, 2012 at 11:58 am

        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)

         
  68. Adi February 19, 2013 at 2:04 pm

    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!

     
    • James February 19, 2013 at 2:27 pm

      Change the host to 10.0.0.2

       
      • Adi February 20, 2013 at 2:21 am

        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 🙂

         
        • James February 21, 2013 at 3:18 pm

          This is the problem with your php code. please check it.

           
  69. Chandan March 2, 2013 at 5:23 am

    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

    ___________________________________________________________________

     
    • James March 2, 2013 at 2:30 pm

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

       
  70. C March 31, 2013 at 11:05 am

    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…

     
  71. logu pushpa April 15, 2013 at 3:19 am

    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 :):)

     
  72. Swapnil Gaikwad August 14, 2014 at 6:29 am

    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.

     
  73. Ayan August 27, 2014 at 5:01 am

    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..

     
    • James September 2, 2014 at 9:56 am

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

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

  75. kalai August 5, 2015 at 6:25 pm

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

     

Leave a Reply

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

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.