Hello all..
I have shown two other examples for creating a connection between android and php. But still users are finding difficulty in grasping it.
-
These are other posts.
- Android phpMysql connection.
- Android phpmySQL connection redone.
Here is one more post on this which is even more detailed.
OK we will start now.
First create a fresh project named “AndroidPHP”.
First we will create a layout for the login form. This xml will do this.
copy this code to main.xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.coderzheaven.logindemo.LoginActivity"> <!-- Login progress --> <ProgressBar android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:visibility="gone" /> <ScrollView android:id="@+id/login_form" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <AutoCompleteTextView android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/prompt_email" android:inputType="textEmailAddress" android:maxLines="1" android:singleLine="true" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/prompt_password" android:imeActionId="@+id/login" android:imeActionLabel="@string/action_sign_in_short" android:imeOptions="actionUnspecified" android:inputType="textPassword" android:maxLines="1" android:singleLine="true" /> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/email_sign_in_button" style="?android:textAppearanceSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="@string/action_sign_in" android:textStyle="bold" /> </LinearLayout> </ScrollView> </LinearLayout>
Now create another xml named userpage.xml by right clicking the layout folder -> Android XML File. Copy this code into that. This is the layout to show in the activity when the user successfully logins.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:text="Login Success." android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </LinearLayout>
Now in the main java file im my case AndroidPHPConnectionDemo.java, copy this code.
package pack.coderzheaven; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class AndroidPHPConnectionDemo extends Activity { Button b; EditText et,pass; TextView tv; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; List<NameValuePair> nameValuePairs; ProgressDialog dialog = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b = (Button)findViewById(R.id.Button01); et = (EditText)findViewById(R.id.username); pass= (EditText)findViewById(R.id.password); tv = (TextView)findViewById(R.id.tv); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, "", "Validating user...", true); new Thread(new Runnable() { public void run() { login(); } }).start(); } }); } void login(){ try{ httpclient=new DefaultHttpClient(); httppost= new HttpPost("http://10.0.2.2/my_folder_inside_htdocs/check.php"); // make sure the url is correct. //add your data nameValuePairs = new ArrayList<NameValuePair>(2); // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value']; nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //Execute HTTP Post Request response=httpclient.execute(httppost); ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); runOnUiThread(new Runnable() { public void run() { tv.setText("Response from PHP : " + response); dialog.dismiss(); } }); if(response.equalsIgnoreCase("User Found")){ runOnUiThread(new Runnable() { public void run() { Toast.makeText(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show(); } }); startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class)); }else{ showAlert(); } }catch(Exception e){ dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } public void showAlert(){ AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this); builder.setTitle("Login Error."); builder.setMessage("User not Found.") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } }); } }
Now create another java class “UserPage.java”
This is simply a navigation page when the user log in.
package pack.coderzheaven; import android.app.Activity; import android.os.Bundle; public class UserPage extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.userpage); } }
OK Android side is done.
Now the server side (PHP).
These things you need top remember.
1. Make sure the url you are providing to the android java code is correct.
2. Make sure your server is running.
3. Make sure your php page has no errors.
4. Also if connecting to a remote URL, you should have internet connection in your emulator or device.
5. Make sure you have a database named mydatabase(in this case) and a table named “tbl_user” and some users inserted in it.
This is the creation query of the table tbl_user in the MYSQL database.
CREATE TABLE `mydatabase`.`tbl_user` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `username` VARCHAR( 20 ) NOT NULL , `password` VARCHAR( 20 ) NOT NULL ) ENGINE = MYISAM
Check the screenshot.
I an using xampp server.
So inside xampp/htdocs folder, i have a folder named “my_folder_inside_htdocs”. Inside this folder I have a php file “check.php” which has the code for checking the user in the database.
Copy this code to check.php
<?php $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); mysql_select_db($database_localhost, $localhost); $username = $_POST['username']; $password = $_POST['password']; $query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'"; $query_exec = mysql_query($query_search) or die(mysql_error()); $rows = mysql_num_rows($query_exec); if($rows == 0) { echo "No Such User Found"; } else { echo "User Found"; } ?>
Done.Now run your project and sign in with a valid user. that’s all.
NOTE: All NETWORK OPERATIONS SHOULD BE DONE INSIDE A THREAD.
Happy Coding.
Feel free to ask if you have any doubts.
Send your comments to coderzheaven@gmail.com.
Download the complete source code of this example from here.
I’m new in android.This post is very usefull for me.I’ve run this,but it is showing a error like…….
Response from PHP:
::PETROBANGLA
Company:-
…..
…..
…..
thus with login form of android in emulator….
what is the problem,I can’t understand….
Looking forward your reply,thank’s…
So your php call is returning something, then what is your problem?
Thank’s for your reply.But I’m not clear about is it working or not?I’m sending my demo site where i wanna login.If you can,you will check this please…Again thank’s for your reply….
Dont forget to add permission internet to your manifest ! 😀
Hi ,good example !
But I can not login on other websites where I know the username and password ..
How to do that ? Is it a problem on url ? php side I don’t know
hello i am having little problem here , i have download your code run it on an emmulator but as i login it does nothin i think my url to php file is wrong or what i am using wamp.
Please help!
Hi Ayesha, are you getting any error or something. I dont know about how to place url in wamp. First try your url in the browser after putting an echo in the page and if it is working then place the url in android, that is what I am suggesting.
Dont forget to add permission internet to your manifest ! 😀
Hi sir
I write the code without error and i get internet permission also. i enter userid and password also right but the program not display the result. what is my problem?
I am new in android world. I have implemented your code successfully but problem is that even if I login successfully still it gives me an error like “User Not Found” and on text it shows “User Found”.
This will not happen, because “user found” and “user not found” are inside if and else respectively. Please recheck your logic.
Hi, I’m having a problem with the php file it self. When I run it on its own in firefox I get errors:
Notice: Undefined index: username in C:\xampp\htdocs\my_folder_inside_htdocs\check.php on line 12
Notice: Undefined index: password in C:\xampp\htdocs\my_folder_inside_htdocs\check.php on line 13
No Such User Found
And when i run the app, validating user pops up for a second then closes. Is this because my php is not working. If so how do i fix my php..
Ellie
Dont browse the url directly it will not work, because I am using post to send the data. you could have browsed directly if I was using GET.
Hi,
This is a good example! Can you give me a hint with simple example of how to connect with SQL Server and fetch the data in android.
Thanks
In this example also you are fetching the data from a SQL Server. The data here is – whether the user is present or not. If you want some other data then edit the php file to return the data you want. Any data from the server will be a string which we can get it in the android side.
This article is very helpful and easy to understand for beginners. I am
trying to implement this code, but facing one error on “span” tag.
error is:
Multiple markers at this line
– Syntax error on token “<", delete this token
– The left-hand side of an assignment must be a
variable
– Syntax error on token "/", delete this token
how do I solve it??? Kindly guide me…
Thanks in advance
Sorry, that’s the problem with my syntax highlighter. please remove those HTML span tags and proceed.
hi, i’m facing a little problem here. everything works fine for me except when the user found, it will not direct me to UserPage. It just close the alertdialog and show back the login form.
how to solve this?
thanks
Please paste here the code how you are checking when the user is found.
Apparently there needs to be an entry in the manifest file for the second page, i.e.
and permission for the app to use internet
Warning: Activity not started, its current task has been brought to the front
Simply edit some code and run the project. This is not an error. This comes before you have already ran the same code and recompiling is not needed.
everything works fine for me except when the user found, it will not direct me to UserPage. It just close the alertdialog and show back the login form.
I am getting the following error when trying to run this code from eclipse on my phone via usb.
Exception : Connection to http://10.0.2.2 refused
I also tried using my pc’s ip and adding port 8080.
first please check whether your local server is running.
Yes the server is running – I can access it via localhost on my browser.
Apparently there needs to be an entry in the manifest file for the second page, but I don’t see what that should be in the tutorial
Hello,
First I want to say great tutorial. Such resources are hard to find. However, I came across a problem on my end. When I run the code and click log-in it doesn’t do anything. The dialog for “Validating user…” doesn’t even show up. There’s absolutely no effect after I click / select log in. Am I missing something? Please help. Thank you very much 🙂
I forgot to mention I am running API 10. Would this cause any error? Thank you.
Did you add the internet permission in the Manifest file. Also check the Logcat.
OK! A third post 🙂
I thought i’d share my solution in case some others made the same mistake as myself. I created a new activity in Eclipse. However, the XML code I copied from the beginning of the tutorial was placed in the MAIN xml (activity). Thus the two were not working together. The layout and class code weren’t communicating. So if the button doesn’t respond for you please advise.
However I still have a problem. I’ve tested this on my s3 and Kindle Fire. When I try to login I get this error: “The application MySQL (process com.example.mysql) has stopped unexpectedly. please try again.”
Why would it crash? I’ve tested a script on my server and everything checks out ok, but the app just crashes.
Please check the LogCat for the error and Paste that error here.
Hello B : Please check the LogCat for the error and Paste that error here.
Hello B : Please check the Eclipse LogCat for the error and Paste that error here.
Hello B : I have edited the code for All versions. Now it will not crash. PLease check it again.
Hello B : I have edited the code for All versions. Now it will not crash. PLease check it again. ok
Hello B : I have edited the code for All versions.Now it will not crash. PLease check it again. ok
Hello B : I have edited the code for All versions.Now it will not crash.PLease check it again. ok
After validating user message its showing message as Unfortunately phpconnection stopped. Plz give me solution
hi..i want to ask, when i create the database in xampp, i didnt find the folder inside the htdocs..what happen? is iam create manualy the folder or its generated automaticalyy when i create the database?
and when i click the login button, the device didnt show anything..is it because not connected to database?where my problem?thanks..
best regards..
You have to manullay create the folder inside htdocs and put your php files in it. There you have to write the php code to connect with the database.
I tried your tutorial but when i click on login button then it shows validating input and then does not thing and it again shows normal login screen..Plz help
Did you add the internet permission in the AndroidManifest file.
hi james
me too have the same problem and i add the user permission in my android manifest file…but there is no any change…..
The post was posted in Android 2.1 so Please do the network operation inside a thread if you are working in Android > 2.1.
Please paste the error that is coming in the LogCat.
This is great for app with a single activity
but how about if I want to use php session.
I know that should be something to work with cookies
it said permission denied from logcat
Add the internet permission in the AndroidManifest file.
i am not getting error and i gave exact username and password. A dialog
opens and says validating user and it disappear in few seconds….then it stands in login.java………
waiting for reply sir……………thank you
First check whether your username and password are reaching the server, then check the response from the server.
how to check it is reaching to sever sir…………Thank you
Try echo “yoursentusername” and echo “yoursentpassword” from the php server side after getting these values as POST. if you are getting the values together with response in the android side, then your values are reaching the server else check the android side.
I did as u said php code is correct..and still remains same………
Send me the code to coderzheaven@gmail.com
My problem is when i click login, it keeps validating then it goes back to the login page, nothing happens. I have already add internet permission
Check the result from your server. Check whether there is any exception is not.
Sorry that I am new to the android development..how to check those exception in server? Thanks
I am telling to check exceptions in android itself. print out the error message inside the try-catch and then you can know whether there is any problem with the server.
hi , i trying to debug this application through USB to my phone . My computer IP is 192.168.1.4 …so , i charged to httppost= new HttpPost(“http://192.168.1.4/my_folder_inside_htdocs/check.php”); // make sure the url is correct. In the same time , i using in same network …Anyone know how to solve it and connect it ?
For testing in your phone you need to install it in a public domain, the Localhost is for the system you are using not for the phone.
HI JAMES,
Great tutorial…
I am trying to run this code from 2 hours and after validating dialog app show no response and these are logcat errors as under.
Exception : Connection to http://localhost refusing
these are erros and done uses-permission and also using Emulator having api level 10.
Please help I have need of this example.
Hi James,
I have pasted all the codes as directed by you. But still my app is not giving result. When i give the username and password and click login after it, it only shows a pop up “validating user” and then nothing happens.The same login screen is shown.I have given the URL as follows:
http://192.168.0.168/android/check.php. First is one my pc’s IP and the android is my folder name inside htdocs of xampp in which i have kept the check.php file. The logcat is showing following
“unexpected value from nativeGetEnabledTags”.
Please help me out of this situation.
After few try now it is always saying Login Error. When i am entering correct user name and password also it saying Login Error.
The php response is showing User Found but android side showing login error. it is not redirecting to login success page.
What can be the error? suggest.
I have pasted all the codes as directed by you. But still my app is not giving result. When I give the username and password and click login after it, it only shows a pop up “validating user” and then nothing happens.
URL as follows: http://127.0.0.1/my/check.php (I keep my check.php file under my folder, I have got wamp server)
hello.. first thing thx for this examples very useful but i have little problem i think there is something is missing to connect login button to php interface give mee “no such user” so i think maybee if wee add onclick in button login i think will work … what u think??
try printing out the count from the php file and check the result in the php side.
Hye.
First of all thanks for the great tutorial!!
It works well but there is only a single problem.
In Android activity – it shows the php respone that i have a valid user (n thats right) but the progress dailogbox shows me that i have a invalid user inspeat of having a valid user in database!
I am stuck and i dont know why it is causing this probs!!
It would great if i get respone as soon as possible!!
Thankyou n Best Regards!!
Please check your php side script and check the response from php side in the Android side according to the parameters sent.
Hello,
I have the same problem as few users:
“My problem is when i click login, it keeps validating then it goes back to the login page, nothing happens. I have already add internet permission”
Error from the LogCat:
Exception : Connection to http://127.0.0.1 refused
I’m using a XAMPP 1.8.1. When I checking check.php file in the browser, everyting works fine I can get a name and password from the database, but in android app, nothing is going fine.
Apache Ports: 80, 443
What I need to change?
Could You help me? Thank You.
Sorry for my English.
Sorry for the confusion. In the below link is the solution to my problem.
http://stackoverflow.com/questions/5495534/java-net-connectexception-localhost-127-0-0-18080-connection-refused
Use 10.0.2.2 instead of 127.0.0.1 if you are testing in the emulator and server is your system itself.
Thanku you for your reply.
One more thing
If I would like to launch an application on an external device (not emulator), then how address looks like?
i have interested in learning for creating the mobile apps in android so please guide me so that i can became a android developer i can understand the program but some terms i cant understand.
So mail some of the PDF files basics of learning the android application development so that i can learn thank u
You can first visit the developer site to study the basics of Android. (http://d.android.com)
Hi james.I really appreciate that from your busy schedule activities, you are giving us time to solve our issue.I am new to android development and as suggested by your article, if you will send me code to fill spinner with mysql table records using php and mysql.I have a project in which i have to implement this.Your current reply will help me a lot.Thanks in advance.
Check this link
http://www.coderzheaven.com/2012/11/18/load-spinner-values-sqlite-database-android/
Respected sir
Thanks for your quick reply,but I have already tried to fill spinner with sqlite database and i have succeeded in that.Actually I want fill spinner from mysql database.I will really be very greatful to you if you send me code realted to ‘Fill spinner with mysql’.
Hello Sir…my code runs just fine when the correct username password combo are entered in the android app…but on entering incorrect values, the application force closes..i have tried in vain to solve this error..even replaced the alert dialog with a simple toast message..but still fails to work.can you help me out? Thanks in advance.
Try to run it inside a thread because from 2.3 onwards network operations need to be run inside a thread.
Hi great tute….
But what can I do if the values are NOT reaching the server… The URL when i run .php on browser is what i used in httpPost but still not reaching the server please help…
Check the important things to note that I have posted in this article. Make sure you have done those correct.
Where to put the database files? I have sql query browser on my computer. Can i use this for creating the database?
What are u looking for? a online database or Local database.? if it is a Local database then you should try SQLite database. Check out other posts about SQLite in Coderzheaven.com
My code is not running properly. As i click on signin, validating user comes for few secs and then nothing happens.
print you username and password in the LogCat and also print the reponse from server in the Logcat and check it.
solved it! Adjusted some permissions in the apache files, and it worked fine.
Potboiler what did you adjust to allow permissions in the apache files. I’m getting the same problem you had as well?
hii..
code is working properly but it is not validating my userid and pass..
Had no problem in running just one that in one of your screenshot you showed a page with only text [login success] i hope that after login that page should not open.
And also tell me that after logging in how can i redirect to another page?
check the response and start another activity.
Connection error is my problem?
what is the cause and possible solution
Check your file exists in the server and you have internet connection. Also you should have INTERNET PERMISSION in the Manifest.
Hi,,nice tutorial..i can run this tutorial..but after i click log in, the toast said user found..but it dont go to the userpage..i already add internet permission in the manifest..hope someone can help me..thank u..
i have given permission in android manifest file
exception: connection to http://127.0.0.1 refused
use 10.0.0.1
Hi james… I am getting many errors in eclipse with this code.. please help..
hello James,
I copied the entire code and compiled it without errors but when i ran it there are several null pointer exceptions and also fatal errors and zygote errors. could you tell me how to solve them?
Sara
May be it is due to my syntax highlighter problem. Check for spelling mistakes and case mistakes.
Hi James, i encountered some problem with the login page. when i type either the correct or incorrect username and password it does not bring me to the respective pages. when i clicked login, it just stays at validating user, thats all.
can you help me. thanks.
Hi!
First I want to thank you for your tutorial. It is very informative although as a novice Android programmer I’m not able to take full advantage of it. I tried implementing your codes to the best of my abilities however I’m having problems making it work. I am currently trying to work it with my Android phone and changed the 10.0.2.2 with my own IP address. I made sure I also included the internet permission on the Android manifest. However, when I run it on my device, the following error message shows up:
Response from PHP :
Notice: Undefined index: username in /Applications/XAMPP/xamppfiles/htdocs/my_folder_inside_htdocs/check.php on line 13
Notice: Undefined index: password in /Applications/XAMPP/xamppfiles/htdocs/my_folder_inside_htdocs/check.php on line 14
No Such User Found
Can you please tell me how I could fix this? Thanks in advance!
Make sure you put the ‘$’ sign before variables in the PHP.
i copied the javacode to my eclipse i got two error they are..
main cannot be resolved or is not a field
UserPage cannot be resolved to a type
can u help me to solve this??
bast sir much much thnk
Hello there, You have done an excellent job. I’ll definitely digg it and personally recommend to my friends.
I’m confident they’ll be benefited from this site.
Greate job sir, it helps me a lot,,,
Exception : android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
For those complaining about two problems: 1). cannot connect to your database and 2). cannot show the new activity page after login successful. Please read on for the solutions.
1). if you cannot connect to the database (assuming you have setup the database correctly). the url in android should be httppost= new HttpPost(“http://xxx.xxx.x.xxx/check.php”); // where all the x’s are ure IP address of your computer or server. remember to put the check.php file in the htdocs folder in xampp
2). for the second problem, u must add the activity in androidManifest.xml like this (bold):
and finally James thx for the tutorial !!!! excellent !
Faisal, perfectly told.
Thanks for much James and faisal..
🙂
…………………
// > is important
……………..
Hello James,
Really it’s helpful to me.I wasted my 2 days time to connect Mysql DB from android using JSON+ php. This is very simple way to achieve this.Your post is simply Super.
thanks for your good work.keep it Up.
Hi James,
My login is working, PHP is return true to me.
But after, when I call another method, I do a session verification for know if the user is logged. How can I get and set this session through the android app?
Thanks!
Save it in a global variable or preferences.
Pingback: How to create Simple Login form using php in android? – Connect php with android. | Techno Fusions
Though i know it’s not possible but thought i am getting the problem of one same person that is at the same time text view of id tv shows me ‘user found’ and dialogue box shows me ‘user not found’.
If you wish i can mail u my code.
hello james thnx for ur nice Article..its help me a lot.. this login tutorial helps me a lot ..but i face some problem…
My project run properly in localhost i mean in xamp but not works with my webserver url.. i check several times of my url but didnt get any sol8n. itz not take input from username and password i mean submitt button didnt work.. can u give me some proper idea..
httppost= new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/index.php”);
here i use
httppost= new HttpPost(“http://mywebsite.co/my_folder_inside_htdocs/index.php”);
and my subfolder also named my_folder_inside_htdocs.
thank you
Did you give the internet permission in the android manifest file.
i am trying to execute a simple demo android app which shows the db connect using php from past 10days i am trying i dont know why people are giving wrong code and do not know who are commenting all this fake id’s in this code first time i found this some span and all thing which is clearly showing error in xml file i am trying to remove but errors are not going….. totally i hate all this wrong ………….things
yeah i have resolved the problem its working can you show a demo to storing the things in list view and after clicking on particular item it should fetch some data from database and display in another screen if you then please its very urgent for me have to do project.. please if u can… between thanks a looot for perfect code…
when i click on login . progress dialog appears thats it.. no toast meassage…i have give 127.0.0.1
use 10.0.2.2 instead of 127.0.0.1
when i open check.php it shows error Undefined index: username and password line 12 and 13
hai master..
nice tutorial..
but i get an error
i have insert data to the table
when i open check.php file it shows “No Such User Found”
sorry for bad english 🙂
thanks for ur reply
please check your logic in the server side.
im having some difficulties, when i log in nothing happens. please help.
package com.fits;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class FinalITSActivity extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List nameValuePairs;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(FinalITSActivity.this, “”,
“Validating user…”, true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost(“http://10.0.2.2/Aconnect/check.php”); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair(“username”,et.getText().toString().trim())); // $Edittext_value = $_POST[‘Edittext_value’];
nameValuePairs.add(new BasicNameValuePair(“password”,pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here….
ResponseHandler responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println(“Response : ” + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText(“Response from PHP : ” + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase(“User Found”)){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(FinalITSActivity.this,”Login Success”, Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(FinalITSActivity.this, verfiycourse.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println(“Exception : ” + e.getMessage());
}
}
public void showAlert(){
FinalITSActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(FinalITSActivity.this);
builder.setTitle(“Login Error.”);
builder.setMessage(“User not Found.”)
.setCancelable(false)
.setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
this is my code. its looks exactly the same but there are some modifications.
and this is my php codes.
Where is your php code? And also please dont paste these big code in there. You can mail me at coderzheaven@gmail.com
i have added internet permission to my manifest file but still i get errors in my log cat.
1) once i press the login button in the emulator there is no navigation to login success page and there is no change as the login form remains the same. I only get validating user and no change happens.
2) the error reported in the logcat is ” skipped 66 frames, the application is doing too much work on its main thread”
3) what should be the android manifest file?
4) i have done certain modifications in the code and i shall mail you the code.
Please suggest some solution as soon as possible, as i am doing my project on android and having a bad deadline to submit it.
Please do the network operations in a new thread instead of main thread from android 2.3 onwards, otherwise it will not work.
Very Good Thanks….
Thanks for the tutorial, I had not found a good tutorial like yours. I had no problems, everything works. Greetings.
Can I ask you why didn’t you use Jsonparser .I didn’t even know that it’s possible to connect without it.
you can use json parser also, this is just another example.
Hi james great tuto,but i’ve got some problems :s
when i press the login button it says :
“user not found” although i entered the right values.
response from php : no database selected.
any
Please check your database name and logic you have changed.
Hi, I’m new to android. I’m attempting to understand this code; however I can’t to seem to fully apprehend how you came up with this piece of code
httppost= new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/check.php”);
Can you please explain what exactly was placed in the brackets?
Its the server address where your server side code is located. 10.0.2.2 means it is localhost or your system is your server.
i m trying to runn this appplication at my local hpst..with this refferece in this index.php is name of table
is is right,? because i m not getting output of this application
httppost= new HttpPost(“http//localhost/index.php”);
Pingback: How to create Simple Login form using php in android? – Connect php with android. | nileshtpatil
Hi,
where i paste these codes
“package pack.coderzheaven;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidPHPConnectionDemo extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List nameValuePairs;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, “”,
“Validating user…”, true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/check.php”); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair(“username”,et.getText().toString().trim())); // $Edittext_value = $_POST[‘Edittext_value’];
nameValuePairs.add(new BasicNameValuePair(“password”,pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here….
ResponseHandler responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println(“Response : ” + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText(“Response from PHP : ” + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase(“User Found”)){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AndroidPHPConnectionDemo.this,”Login Success”, Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println(“Exception : ” + e.getMessage());
}
}
public void showAlert(){
AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
builder.setTitle(“Login Error.”);
builder.setMessage(“User not Found.”)
.setCancelable(false)
.setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}”
on mainactivity.java ?? comming 20 errors
The error might have came when you copied the code from my site. please check each line.
thank you , for this useful tutorial but i got problemin “org.apache.http.meesage.BasichttpResponse@242a8890”
please Help??
Hi,
I downloaded the code. there is no errors in the code but if i click on login button its not getting or starting the UserPage.java. Can anyone pls do help me out in this what i have to do.
Regards,
Prathima
You may have to change the code according to the instruction in the tutorial.
Whenever I try to login its showed ‘login error’ and show the line of php which written on php file.
Thank for your tutorial
i did same what you did from mysql to php and android
and i insert from phpmysql username and passowrd
but when i run the app on emulator
i got this error message
” Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use musql or PDO instead in ”
what i should do ?
note : im using wamp so i set my_folder_inside_htdocs under this root
C:\wamp\www\my_folder_inside_htdocs
looking forward to hear from you
Please use the latest version of the function
mysql_connect() may be deprecated…so there will be another method similar to it. Use that.
This should not cause any problem.
Dear Author
Thanks for your good examples and tutorials!
By the way,
I did all the processes you wrote down in article,
I corrected URL in AndroidPHPConnectionDemo.java and PHP file.
but when I execute this program on my android device,
Login button does not work.
It do not retrieve any validating messages and fail messages,
remaining only login front page.
What should I do?
Could you please check the Logcat and see what is happening when you click Login Button.
I downloaded the code. there is no errors in the code but if i click on login button it gives error user not found and at login page it displays message Response from PHP: NO databasse selected … waiting for your reply thanks …
i just solved my problem thanks for this informative tutorial 🙂
Hello this is useful it works with me but i need to add one more thing and i tried many times but i couldn’t make it
the access is happening from one table form mysql and it navigate me to one page
i added one field to that database which is “role”
if the “role” is a “student” it will navigate me to page1
and if the “role” is a ” faculty” it will navigate me to page2
how i can apply this ?
looking forward to hear from you
sorry didn’t complete my previous post well
here is extended post
what i would to achieve as i said i added one more field to that table i call it “role”
the purpose for this is that i would like to have a navigation according to “role”
for example
if the user enters his username and password and clicks on login button it will check that username and password if it is available and his role is “student” it will navigate him to page1
and if the “role” is “faculty”it will navigate him to page2
how i can achieve this ?
looking forward to hear from you
Did you managed to connect to PHP and authenticate?
If yes, then pass the “role” as parameter along with the intent for navigation to the next page and get it there and do accordingly.
Check this post
yes i could connect with php
i guess my problem comes in if statement
i will mail you the code there
ok mail at coderzheaven@gmail.com.
thank you
i sent you the email
I import the project into eclipse. and trying to run on emulator but after entering the data into text field . when i click on login button . only validating user is come .. and then after some time nothing will happen on screen.
I also added internet permission in manifest file. and also but i am not connected to internet. i just want it add check the user exist or not without internet on localhost xampp server. i have added the url
http://localhost/my_folder_inside_htdocs/check.php but still not working. ..
Send your code to coderzheaven@gmail.com. I will try to fix it.
where to create the check.php file?
do i need to create php project using eclipse (file->new->PHP project) or
directly create a notepad file with .php extension.
By doing what u have told , after entering username, password while i click login its says validating user and stays in the login page itself. there is no response.
Note: i have created database with sample values and connected through java http connection
since we are calling a script in the server, check.php should be in the server.
httppost = new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/check.php”);
is this statement right. i am using xampp server and AVD for launching in eclipse. what would supposedly be the IP address i need to refer is it 10.0.0.2 or 127.0.0.1
Response from php: parse error:
syntax error:unexpected mysql_select_db
i think i am almost there , but i cant understand this error in android emulator
note: log cat and console are free of errors
Thanks in advance!!!!
hi james..i am copy ur code and some place i currect the my relavent code..but that time i am insert currect username or wrong username password that time same error is shown user not found…so why waht is the problem..
Hi, I want to make session control with php and android .Could you help me about this subject?
Pingback: Php Program For Login Form
Sir, the code opens debug perspective on button click and the logcat error shows—> skipped 103 frames..the application may be doing too much work on the main thread….pls help me sir as my complete BE project depends on it.
what is the error you are getting?
sir James what is the 10.0.2.2 is this a server or an ip address thanks for your reply
httppost= new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/check.php”);
10.0.2.2 is the localhost for Android. If you are using your developments system;s localhost as Host, then you should use this.
This tutorial is very helpful but there is a problem in my php file.
It is giving my error that variable in which i am taking input from the user is undefined index.
I m taking phoneNumber as a input.
The id of the TextField in xml file is textView1 and the MainActivity I defined a String of “PhoneNumber”.
This “PhoneNumber” is giving error in the lines below
$PhoneNum=$_POST[‘PhoneNumber’];
$query=”INSERT INTO phonebook(PhoneNumber) values(‘{$PhoneNum}’)”;
$query=”INSERT INTO phonebook(PhoneNumber) values(‘$PhoneNum’)”;
Check the “Case” also.
You need to register the activity in AndroidManifest.xml to make it go to UserPage after login.
this code is giving me this error when i run it
AndroidPHP does not specify a android.test.InstrumentationTestRunner instrumentation.
On Click login button , it is just showing validating user, rest all is not coming up.
Please check your logcat…
Hi James, i have this error.
Notice: Undefined index: user_login in C:\xampp\htdocs\check\check.php on line 12
Notice: Undefined index: user_pass in C:\xampp\htdocs\check\check.php on line 13
No Such User Found
this my check.php
when i login in my android. android studio log error :
Exception : Connection to http://127.0.0.1 refused
how can i fix it, sorry my english so bad. thx u so much for tutorial, ^^