
Most of android developers already developed how to conform user login / register data to local Sqlite database, but may few of you try how to authenticate login details with remote (like mysql with php) sever ! am i right, no lets do it…. I think handling remote database with local mobile is tricky task, you need [...]
Most of android developers already developed how to conform user login / register data to local Sqlite database, but may few of you try how to authenticate login details with remote (like mysql with php) sever ! am i right, no lets do it….

Android Login App
I think handling remote database with local mobile is tricky task, you need to use some thing as middle interface to send mobile request to server and vice-verse.
Lest discuss step i have use to authenticate remote db
- Post login data using XmlHttpRequest
- Call remote server php file
- Your posted data will data which is sent by mobile (GET/POST)
- php file will authenticate that user information with mysql db (PHP MYSQL)
- php file will respond to mobile (echo 1 /0 | 1: login 0: wrong user)
So here is the code
First create login2.java
package com.example.login2;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class login2 extends Activity {
EditText un,pw;
TextView error;
Button ok;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
ok=(Button)findViewById(R.id.btn_login);
error=(TextView)findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://engiguide.com/check.php", postParameters); //Enetr Your remote PHP,ASP, Servlet file link
String res=response.toString();
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}}
});
}}
CustomHttpClient.java This is ready file so need to understand it just use because we are using Http request client side.
CustomHttpClient.java
package com.example.login2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* @return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}}}}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}}}}}
And now the remote server PHP file (If you want to use C#.NET,ASP,JSP you can !! )
check.php
0) // ( $un == “ajay” && $pw == “ajay”) echo 1; // for correct login response else echo 0; // for incorrect login response ?>
And if you want to use JSP instead of php this is jsp code.
Thanks to prashant for this code!!
package web.com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Prashant
*/
@WebServlet(name="AndroidResponse", urlPatterns={"/androidres.do"})
public class AndroidResponse extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
String un,pw;
un=request.getParameter("username");
pw=request.getParameter("password");
if(un.equalsIgnoreCase("prashant") && pw.equals("sharma"))
out.print(1);
else
out.print(0);
}
}
Your layout file main.xml, iamges and AndroidManifest.xml file attached in this download packge. And don’t forget to change AndroidManifest file otherwise your code will not work
Will discuss your problem just comment it

Login Success Image

Login Fail
No related posts.







225 Responses
What are the requirements of my webserver for this to work? I have lighhtp with PHP running this script and when view the page in a browser I only get a ; on the screen which looks like its working. My application has the URL changed to my local server and I am on the same wi-fi address as I can view my pages on the other parts of my server like my check.php file. Do I need to add a mysql server to my webserver for this example or should it all be handled via the php? I have left everything as you wrote it and I am using ajay as the username and password for both. I have deployed this to the htc hero running AOSP running 2.2 strictly using wifi.
thanks
Anthony
put your wamp server online
try port forwarding or bmz for local host
and still it is not working try to use ip address instead of localhost
Hi there, just wanted to drop by to let you know about an amazing plugin that would help your blog tremendously. Check it out for yourself at seopressorplugin.biz. It’s a real timesaver and any internet marketer’s dream plugin. Hope you like it!
Greetings, I am using your code here but faling at one point. I have it altered to my database on my server, so it finds the .php file but keeps saying wrong user and pasword. the “result” variable doesnt get anything from the .php file also I have a toast display with the result and instead of giving me a 1 or 0 it displays the content of the .php file. This tells me the program isn’t even accessing the .php file.
Any help would be great.
Thanks!
Steve
HI
Steve
I don’t know why this script is not working for you, see first of all clear that your php file is calling by android phone?
If yes then try to get the value which are you posting by android device.
So your first task is to clear the cycle mobile to server & server to mobile.
By the way can you please send me your php file code with error you getting?
I’m pretty sure its being called my my android…how can I tell for sure? what do you mean my clear the cycle? Also what changes to the manifest am I suppose to make?
Here is the php code without my username and password:
also sometimes when I open the file it brings up this:
   Login Page
<? if ($_SESSION['loginerror'] == "true")
{
$_SESSION['loginerror'] = "false";
echo "”;
echo “The username/password is incorrect”;
echo “”;
}
?>
username *
password *
Thanks!
It seems that my last comment didnt post all the code… let me know if you got it all.
Thanks!
Got it and i am i sorry about my syntax highlighter plugin give wrong php code with comment remove it
Try this
< ?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = ‘bduser’;
$pswd = ‘dbpwd’;
$db = ‘dbname’;
$conn = mysql_connect(‘localhost’, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = “SELECT * FROM people WHERE username = ‘$un’ AND password = ‘$pw’”;
$result = mysql_query($query) or die(“Unable to verify user because : ” . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
// ( $un == “ajay” && $pw == “ajay”)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Awesome thanks it works smoothly! How much more would be needed to return info from the database instead of a 1 or 0?
Thanks again!
Steve
or to even add a username and password?
Your welcome
Why not ? Instead of 0 & 1 you can replay your db value !!
Try it its now your task
Nice work.
I have this up and running but i have a question for you.
It works as it should but i have two warnings in my CustomHttpClient.java:
This raw:
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception {
have this warning:
ArrayList is a raw type. References to generic type ArrayList should be parameterized
And this raw:
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
have this warning:
Type safety: The expression of type ArrayList needs unchecked conversion to conform to List
Is this something that i could fix or do you have the same in your code? and if so, is it ok to have it like that?
Thanks.
Thanks,
Kristoffer
I think i should take a look again about this warning and inform you as soon as possible.
Gud luk
Thanks for the help Ajay.
Keep up the good work.
in php code
if(mysql_num_rows($result) == 1)
should be
if(mysql_num_rows($result) > 0)
because mysql_num_rows() returns
The number of rows in a result set on success or FALSE on failure
I am appreciating this one is really fault , The syntax highlighter sucks my php code always now i will not use it for php.
check out the syntax highlighter http://code.google.com/p/syntaxhighlighter/wiki/Usage bugs for php :]
By d way thanks
the solution is very simple. u just have to identify the arraylist
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception {
and thats it
hoooo is not showing here
so just write ” NameValuePair ” in front of ArrayList with ”
Hi Ajay,
How to start new activity if login is success.
tried using StartActivityResult but not getting success..
Thanks in advance.
yeah! got it..
forgot to declare activities in manifest.xml
got it using StartActivity only .
simple and common mistake done by Android Dev !! now tak ker
Thanks for the tutorial.
Do we have to send username and password each time we need remote data?
yes, you have you can create login session for some time if don’t want.
hi!
I am also unable to get it to work. It just always says that it’s the wrong password:(
Hi Ajay, es here…..I copy and paste the coding exactly that you given above but stil failed in login. It appear “java.lang.IllegalArgumentException: Illegal character in scheme at index 0:” and also ” android.os.NetworkOnMainThreadException” on the Username textbox, could you pls help me out….or can u email me the login that u already done? Thx in advance.
and izzit cause the php got wrong??? the $user = ‘bduser’; should be “db” or “bd”?? I used xampp, localhost and editplus to write the php. pls gv some advice….
My mistake, i’m using md5 for my password. It still doesn’t work, i’m getting 1 for correct login, but if statementi isn’t working….
check the new php file is in comment is corrected
the syntexthigliter sucks my php code
check the login php file comment in thread of jigar , will try gain u ll solve it surely
String t =”1″;
if(res.equals(t)){
error.setText(“deluje”);
// Zapiši id v spremeljivko
// Intent i = new Intent(login2.this, base.class);
// startActivity(i);
}
else{
error.setText(“napaka”+res);
Even if echo is 1, it still doesn’t work, it always displays “napaka”+1…damn it
got it to work. Had to use .contains(“1″): if(res.contains(“1″)){
I still can’t slove the error =(
Ajay, may I know which version of android when u create this login page?? it’s Android 2.2 or Android 3.2?? and also its SDK version. Thx ~
this was tested in 2.1,2.2 not sue about 3.x. But i think it should work in 3.x.
Can you please explain me what is the actually error. Have u seen the new php file in comment ?
yea…i gt saw it….do u knw hw to do with the Async Task??
Nice Tutorial help me lot
Really Thanks Ajay
Hi Ajay
I have one doubt .I want to store the values from android UI to my remote DB any idea about this
please help me with sample code
hey, i m getting following EXCEPTION when i m trying to connect it with localhost ‘phpmyadmin’…..
‘java.net.SocketException: Permission denied’
pls can anyone help me….???
davor is right, the solution is change if(res.equals… for if(res.contains(“1″)… thanks for the code man!! Greetings from Colombia!! Saludos desde Colombia
Thanks davor & alvaro
try to look out the comment thread may u will get the solution.
or post your full problem
“response = CustomHttpClient.executeHttpPost(“http://localhost/stupidsid/CB.php”, postParameters);”
i m writing this code to connect to a localhost’s PHP file…..
so i m getting following EXCEPTION…
“java.net.SocketException: Permission denied”
pls help me…!!!
np, glad I could help and a BIG thank you for this code! I made some adjustments, so I get ID instead of just 1 and 0 and in the android code so that it starts a new intent…so you saved me a ton of work!
thanks davor post the bug u find and solve so ppl can also use it.
i have invested a week for this
i don’t think android allows you to connect to a localhost. I’m using eclipse and I get an error: connecting to localhost is not allowed.
Hi all
I am new to Android development and I dont understand something. This application can be added to one I have build for example, or I must heave a server in order to apply this to my project?
Thanks
sure u need a linux web server or u can use any free hosting for testing
Good day
Yes, thank you, I have figure it out.
woo huuu N joy
Hi again
Is is possible to post your SQL code also?
Thanks
Thank you
It`s very useful code.
Hi,
i have a URL in that data is like as follows
-
-
1
support@xyz.com
admin
b44220b1213e5083c97220eaeffc6ee7
M
Y
this is URL is for Login for this when i’m using the above code i’m getting incorrect username or password.
for this how can i write code to check email and password and one more thing here the password in encrypted.
kindly provide solution for my question.
Thanks in advance.
Hey thanks for this very useful bit of code it really saved me hours and the CustomHttpClient class is so very useful thanks again
wel come
Thank u Ajay…how can add androis for php.apk file to my eclipse cofiguration….
You cant add php file in android apk, you can use it on remote server
Hi…Ajay,,,,,I want to ask you that the sample code that u have provided.what is the username and password for that.Also while doing R&d of connecting database remotely in android I found kumulos for android .I did tried the sample code provided in the docs of kumulos,But it did not worked.If u have anyother sample code of how to conect database remotely in android,,can u kindly guide me…..
Regards
Tushar
Hey Ajay,
I’ve had a major problem with receiving any response with this. For some reason, respone is always:
Index of /
Index of /
cgi-bin/
Even if the URL is incorrect, or my file contains random code, this always shows up…
On which link ??
If you are getting this it means that you are in root directory, give your php file name like ” index.php ”
or try full path like http://www.domainname.com/xyz.php
The url is http://www.projectmma.net/android/user.php with the posts being request, username and password. The request being ‘login’. I tried the same method using HttpAssistant which works fine, but using this script always return that blank index page, even if the filename was wrong (e.g. use.php instead of user.php)
surely,it will give u a blank page because your page has no output text and we also do not want, this php file just replay android mobile 1/0 just for login conformation …
The php code is identical to yours which echoes 1 or 0. Even if I provide default text it still responds with that blank page :S
OMG Can you please mail me the php code
on ajay@webdesignergeeks.com
Sent, thanks for your time!
On a side note, I’m developing in Android 2.3.3?
why does the timed out respond like “java.netSocketException: The operation Timed Out” or “Your Application Does not responding. Force close?” always shown up either on your project that i’ve import and my app.. is it about internet connection?
I had this. Its because I didnt add the permission to use internet in the androidmanifest.
should work after that
Im also getting the error Steve talked about earlier where when I toast the ‘res’ variable in the code it just displays the whole php file. I have even corrected the syntax in the php file but im still seeing this. Is there anything else I need to do to fix this?
hi i got any error java.lang.illegalArgument exception illegal exception in path index 24 of my check.php file any help?
erm why did it show correct username and password even though i enter the wrong username ans password?
i think may your php file is wrong ! do not use that php url was i used in my post.
use your own
i did change to my own url i put the php file in my xampp htdocs androidapps folder and this is my url response = CustomHttpClient.executeHttpPost(“http://192.168.220.1/AndroidApps/check.php”, postParameters);
Sure it will not work, because its HTTP request so your web-page(php) must be live. or your xampp must be on online mode and close your firewall then try to open this http://192.168.220.1/AndroidApps/check.php from other pc OR simple host this php file in online free server
i have tried closing my firewall and my xampp is also in online mode however i still get correct username and password even when i type the wrong username and password
Ok, now first forget the login authentication and try to check whether you are receiving data from php or not? just echo one php variable and try to get in android if this is possible then it should work.
If you are not receiving any replay from php file then may it show you correct login each time.
check this http://wowjava.wordpress.com/2011/01/16/login-application-for-android/ for more info
ok i finally manage to get it to work i found out that there was a space at my php script < $php
thanks for your help
Hi is there any idea on how to authenticate login with salted passwords instead of plaintext passwords
sure, try md5($var); here $var is the password which you will get in php file from android device and in your db there also stored password in md5 hash
Hi!
This is very good source. Thank you.
I use asp for android.
How do receive about “member” and “password” in asp ?
Please………….
I’m sorry. I solve it.
Thank you
HI,
how can we get sessionId as response from server when the form is authenticated.
pls reply me.
Thanks.
Thank you
check.asp
.asp and Ms SQL
un = request(“username”)
pw = request(“password”)
‘connect to the db
Set db = Server.CreateObject(“ADODB.Connection”)
db.open strconnect
sql = “SELECT * FROM member where username = ‘” & un & “‘ and password = ‘” & pw & “‘ ”
Set Result = db.Execute(sql)
if result.eof then
Response.write 0
‘ for correct login response
else
Response.write 1
‘ for incorrect login response
end if
wel come
im entering
username:-ajay
and
password:-ajay
it will showing “Sorry!! Incorrect Username or Password”
when im using
HttpPost(“http://testmysite.biz/andriod/login.php”, postParameters);
following error occuring–
unknown host exception unable to resolve host “http://testmysite.biz:” no adress associted with hist name…
plz reply ….
Hey its Cool code. Thank you very much. Its work great but i have one question. Can you help with one think. I want do this – if user use good login and password to connect i want to show him a massege “Correct” and redirect to next Activity where he can will next information from data base ?? Can u help me with that code ??
Thank you!
Hi there I am so new to android THANKS SO MUCH for including the project file…but what should I change in the Android Manifest?????
Please I am doing a finaly year uni project and I am trying to developer an app the can login to a mysql database and display data from it.
PLEASE I AM A TOTAL NEWBIE your help wil be much appreciated
Hi, thanks for the post. I am pretty new on these things and I am trying to do the check.php file in C#.net (Connect to MSSql) , put it into my local server, can you post the source code that would work?
sorry, i can’t write code for you. and you need to host check.php file on live server not at localhost
Try it dude and let me know what is problem. i have explained this tut in detail
do not use my chek.php path its not working
Hi Ajay,
Nice post.. keep it up…
I got error while connecting to my localhost.
“response = CustomHttpClient.executeHttpPost(“http://localhost/android/check.php”, postParameters);”
The error:
“java.net.SocketException: Permission denied”
Is there any way solve this issue. Thanks in advance.
Please use live server to host check.php
how do u add braces in a variable for php?
example
$un=$_POST['username'];
i want to add curly braces to the variable $un such that it becomes ‘{value}’ in plaintext
Thanks for the tutorial.
It’s working fine.
I’m trying to improve this code adding a ProgressDialog while authentication. But with no success.
Adding:
pd = ProgressDialog.show(this, “”, “Authenticating”);
just before
response = CustomHttpClient.executeHttpPost(” …
and disabling it at the end, the ProgressDialog doesn’t load in time. It has some delay, never showing properly.
Did someone tried this or can give me some help.
Thanks.
oh,that is good !!
Hi there, how do i save the session after login so that i can grab the username to use it
http://www.w3schools.com/php/php_sessions.asp
check this , set session like 1 min
Sir, Thanks for the awesome tutorials. Can u help me with this error sir? org.apache.http.conn.HttpHostConnectException:Connection to http:127.0.0.1 refused
Is it possible sir to use the localhost? like for example. http://127.0.0.1/user.php
But it is connected to the internet. I have also put this line in the androidmanifest,xml
please do not use localhost
So I need to purchase a domain and also web hosting… Im sorry, I just thought it is possible to use the localhost. Thanks sir
Hi Ajay,
Thanks for the tutorial, it´s exactly what i was looking for. Keep up the good work.
Regards!
My pleasure ,Rafael Martins
Keep visiting.
Hi, very Good Job !
I have an Error, the Java code works fine, but the PHP code does not work!
Can you Help Me Please?
PHP Code:
0)
// ( $un == “ajay” && $pw == “ajay”)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Thanks!
about the code.. should i use contains or equal?
if my php file has more than one functions to insert, delete or select on different tables,
then how do i call a specific function thru the android code, and pass data to server, and collect the data back to android
Hi, thanks for the tutorial.
I am having an incorrect password message, even when the password is correct.
I checked the DDMS messages and I was having the following message;
12-03 13:01:52.137: D/SntpClient(73): request time failed: java.net.SocketException: Address family not supported by protocol
please i need help with this. I also need help on how to get and display database content in listview.
Thanks
forgot to add. The .php file i’m using to communicate with mysql is on the same server.
here is the php code:
Untitled Document
0)
echo 1;
else
echo 0;
//mysql_close();
?>
hi, thank you for your sharing. it’s very helpful. I have another question. How can we manage the accout of the user after logging in? How can we keep track of which account is logged in and who the user is? Thank you.,
I think all this if you wand to do on server side , you can create php code for keeping track for it…
like getting username in $post=”username” and track it for how many times that use login from his/her device
hi, sorry, I think i didn’t make my question clear. I mean on the client side, after logging in, it may directs to another activity, but we always need to know that who is the user, how can we keep track of the user account? (Sorry , I don’t know whether it’s something really basic, I’m pretty new in Android development. Hope you can help me.) Thanks.
[...] Android login authenticatie met externe database: http://webdesignergeeks.com/mobile/android/android-login-authentication-with-remote-db/ [...]
I just put this code in my project, and it errors even though the password is correct. I see the connection on my httpd logs, so it is getting to my server. I am using SQL by the way.
Hello,
Thank you Ajay for this code.
Please, I have this exception (org.apache.http.conn.HttpHostConnectException:Connection to : http://127.0.0.1 refused) when I try to login !!!! where is the problem ???
Hi Ajay, Gud eve…I copy and paste the coding exactly that you given above but stil failed in login. It appear “java.lang.IllegalArgumentException: Illegal character in scheme at index 0:” and also ” android.os.NetworkOnMainThreadException” on the Username textbox, could you pls help me out….or can u email me the login that u already done? Thx in advance.
plz rly me..itz my urgently project work..
Thanks! I tried your code but the php returned the entire html page to me instead of just 1 or 2. Could you tell me why?
[...] http://webdesignergeeks.com/mobile/android/android-login-authentication-with-remote-db/#comment-1236 [...]
it returns a blank html page before 1 or 0
0
Could some please tell how can I solve it?
use this php code
my syntax high-liter sucks my php code…
< ?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = ‘bduser’;
$pswd = ‘dbpwd’;
$db = ‘dbname’;
$conn = mysql_connect(‘localhost’, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = “SELECT * FROM people WHERE username = ‘$un’ AND password = ‘$pw’”;
$result = mysql_query($query) or die(“Unable to verify user because : ” . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
// ( $un == “ajay” && $pw == “ajay”)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
and keep in mind ur php file must be on server(which have ip or domain ).
What is the issue ? what are you getting ?
i have downloaded your code but can you tell me how to set up the database with the php file?? what is your database structure??
awaiting your respones, thanks!!
Hi….my error is ” android.os.NetworkOnMainThreadException” on the Username textbox, could you pls help me out…y dis error is displaying …what is solutions…plz tell me..
hi am getting dis error in my username textbox ” android.os.NetworkOnMainThreadException” …how it is cleared…
Hi friends…am beginer in android..am using android4.0..when am fill in the username and password then just clicking login button that time displaying android.os.NetworkOnMainThreadException” on the Username textbox…so what error is found here…help me…
dis error will occured in my logcat ajay..
12-23 11:37:46.677: E/AndroidRuntime(694): FATAL EXCEPTION: main
12-23 11:37:46.677: E/AndroidRuntime(694): java.lang.NullPointerException
12-23 11:37:46.677: E/AndroidRuntime(694): at com.ar.mydatabaseProject.pack.MydatabaseProjectActivity$1.onClick(MydatabaseProjectActivity.java:117)
12-23 11:37:46.677: E/AndroidRuntime(694): at android.view.View.performClick(View.java:3480)
12-23 11:37:46.677: E/AndroidRuntime(694): at android.view.View$PerformClick.run(View.java:13983)
12-23 11:37:46.677: E/AndroidRuntime(694): at android.os.Handler.handleCallback(Handler.java:605)
12-23 11:37:46.677: E/AndroidRuntime(694): at android.os.Handler.dispatchMessage(Handler.java:92)
12-23 11:37:46.677: E/AndroidRuntime(694): at android.os.Looper.loop(Looper.java:137)
12-23 11:37:46.677: E/AndroidRuntime(694): at android.app.ActivityThread.main(ActivityThread.java:4340)
12-23 11:37:46.677: E/AndroidRuntime(694): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 11:37:46.677: E/AndroidRuntime(694): at java.lang.reflect.Method.invoke(Method.java:511)
12-23 11:37:46.677: E/AndroidRuntime(694): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-23 11:37:46.677: E/AndroidRuntime(694): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-23 11:37:46.677: E/AndroidRuntime(694): at dalvik.system.NativeStart.main(Native Method)
when am fill in the username and password then just clicking login button that time displaying android.os.NetworkOnMainThreadException” on the Username textbox……so what error here..how it is cleared..help me urgenty i need…dis is my final year project…
plz rly soon ajay…
[...] How is connecting mysql database connection in android.am new to android. Worked in dis site :Android login authentication with remote db – WebDesignerGeeks – Web Designer, Web Developer blog having error only….when am entered in the username and password then just clicking login button [...]
Hi, I’ve just tried to include a ProgressDialog in your great class CustomHttpClient.
I added a parameter in executeHttpPost and executeHttpGet methods to pass the context, but it doesn’t work!
Can you help me?
Thanks in advance
Now I’m trying to use onPreExecute() and onPostExecute() methods into CustomHttpClient class, but this way I don’t know how to pass the context to use into ProgressDialog. Any ideas?
I’ve solve the context problem. I set executeHttpPost and executeHttpGet as not static methods and in MyActivity now I have:
…
CustomHttpClient my_request= new CustomHttpClient(MyActivity.this);
String response = my_request.executeHttpPost(“http://my_address/page.php”, postParameters);
…
and in CustomHttpClient:
public class CustomHttpClient {
Context my_context;
public CustomHttpClient(Context my_context){
this.my_context = my_context;
}
but now the problem is that onPreExecute and onPostExecute methods are not called.
Can i use SQLite instead of SQL for remote DB .
Yes you can …
Hi …am beginer in android..am using android4.0..when am fill in the username and password then just clicking login button that time displaying android.os.NetworkOnMainThreadException” on the Username textbox…so what error is found here…y dis error is displayed on the text box…help me…
hai…dis is my coding part…
krish.php
0)
// ( $un == “ajay” && $pw == “ajay”)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
login2.java:
package com.example.login2;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login2
extends Activity {
EditText un,pw;
TextView error;
Button ok;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
ok=(Button)findViewById(R.id.btn_login);
error=(TextView)findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList postParameters = new ArrayList();
postParameters.add(new BasicNameValuePair(“username”, un.getText().toString()));
postParameters.add(new BasicNameValuePair(“password”, pw.getText().toString()));
//String valid = “1″;
String response = null;
try {
response = CustomHttpClient.executeHttpPost(“http://localhost/krishnaveni/krish.php”, postParameters); //Enetr Your remote PHP,ASP, Servlet file link
String res=response.toString();
// res = res.trim();
res= res.replaceAll(“\\s+”,”");
//error.setText(res);
if(res.equals(“1″))
error.setText(“Correct Username or Password”);
else
error.setText(“Sorry!! Incorrect Username or Password”);
} catch (Exception e) {
un.setText(e.toString());
}}
});
}}
CustomHttpClient.java:
package com.example.login2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* @return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer(“”);
String line = “”;
String NL = System.getProperty(“line.separator”);
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}}}}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer(“”);
String line = “”;
String NL = System.getProperty(“line.separator”);
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}}}}}
main.xml:
AndroidManifest.xml:
now am running my project here login2 has stopped unexceptedly…but nothing error is displaying in logcat…what problem in my project…plz explain me ajay….
dis is my php file:
krish.php:
0)
// ( $un == “ajay” && $pw == “ajay”)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Hi Ajay,
Thanks gor your helpful tutorial, it’s really good. I used your this project in Android 4.0 an got a problems with running, i.e. the following lines in login2.java code was marked as errors in eclipse:
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
ok=(Button)findViewById(R.id.btn_login);
error=(TextView)findViewById(R.id.tv_error);
“id cannot be resolved or is not a field”, how could be solved this? any help from you would be helpful.
orif- i had the same errors..but i re-imported and it was working all fine, do you knw how to set up the database(back end) with this source code?? need help!!
hi, you can localhost to test this… proivide ip as 10.0.2.2 and test…..
Your local host should be online and unlock your firewall
hey ajay, i m done with connecting localhost wit mysql database..so its workin fine on the emulator but its nt connecting when i deploy into an android device…i tried supplying the ip address of my laptop whic has the wampserver.
plz help me!!!
Turn Off your firewall
and cross check that your root dir can be open by another ISP provider.
If it will then it should work
Do you know how to create session with your php code?? i hv taken up a huge project in my university, need to develop multiplayer game for android!!
hey ajay great script!! just wondering how would you implement updating the textview to show a connection error?
hey ajay plz give me another help on map
im developing map application on multiple pin on map to display depending on that lat and lon values and that can pass dynamically on database.there is 4 values coming from database that 4 location can diplay with 4 pin with different colors………..plz help me im new on android plz.
Hi AJAY
please I have this error
org.apache.http.conn.HttpHostConnectException connect to localhost:3308;
That appear in the same field when I write username and password ?
can you help me plzz
my file PHP:
0)
// ( $un == “ajay” && $pw == “ajay”)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
im developing Googlemap application of version 2.2 but that code not working on galaxy tab plz help me
Do you know how to create session with your php code?? i hv taken up a huge project in my university, need to develop multiplayer game for android!!
please can you help me….
hi ajay good evening…
how is set the session concepts here…
http://www.w3schools.com/php/php_sessions.asp
pho session Google it
Hi ajay good morning,
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…
hi ajay..how is save the logged in username in a global variable in the activity.Then get it in the next activity and query again the database with this username.am checked
these link http://coderzheaven.com/2011/05/global-variables-in-android/ for setting the global variable and dis http://coderzheaven.com/2011/03/passing-data-between-intents-in-android/ for passing the extras in the intent.but i don’t know how is to do???plz how is inserting our code…plz send me dis modified code is send to krishnaveniv@live.com….plz help me ajay…more number of days am worked dis concepts..but am not clear dis concept..plz help me ….thanks in advance..
[...] after login success Hi….am worked dis site for login page using json web services: Android login authentication with remote db – WebDesignerGeeks – Web Designer, Web Developer blog i need next activity having logged person username…But i don't know how it is do?..sp plz give me [...]
[...] Android login authentication with remote (MySql)database [...]
Hai ajay
I am developing a android application in that i want to connect and access ms sql database from a external server.Can u give the code for me.
The details are
Database : CRLocator
Port : 49162
Username : crlocator
pwd : crlocator
Hi ajay
response = CustomHttpClient.executeHttpPost(“http://127.237.72.20/check.php”, postParameters);
will this work.
I want to use C#.NET…
than please send me code for C#.NET.
Yes you can.
).
May you know, how to use GET method in c# ?
If yes then its easy.
And never comment like that send me code, you need to solve it your self(I have my own life too
@Ajay,,,,
i want your help,,, i take your source files, the emulator opens normally but when i hit login i got this exception
org.apache.http.conn.HttpHostConnectException: Connection to Http://localhost refused
please help meeee
Thanks Ajay..Your script works perfectly with no hassles.. It will be nice if you can post a code on how to continue on success, with a new activity by passing variables..
@Ajay @Tunji Olu- Tawio
i want your help pleasse where did you save the .php file and what you do to make it work,,, what the url of the php and what is the ip you use help please
@Yasmeen. You need to host the php file on a live web server. I use a Zend’s free cloud service which is still beta. checkout it out at http://www.phpcloud.com/
The url will be something like http://yemekpakette.my.phpcloud.com/YemekPakette/check.php
@ Tunji Olu- Taiwo: Thanks
hi ajay…u r connecting php file and using web services ok file…how is connecting mysql database using jdbc…how is write jdbc connection…
Hi friend this is a good contribution to the programming on android but I have a question if you could not make a method that says “ConectarBD” and “DesconectarBD” to open and close connections. Well and also I have another question your application that you run in this photo but as long as the PHP this posted on the internet but I want to test on localhost and then publish it as online, idk if you could tell me where in the code I have to modified to run in local mode executions in PHP.
i want to make registration form..
and for that form we need insert query..
than what is the insert query for java..
please help me..???
what is the insert query for java..for use in registration form
please help me..???
I got java.net.SocketException when trying implement this, any one know how to fix it?
Hello Ajay Patel sir,This is Mahesh from bangalore.
sir recently i joined in an IT company.They are asking me connect your android emulator to local mysql database.i don’t know how connect it.but i downloaded your code and trying to run it is showing error.when i am click on login button after entering user name:ajay,pwd:ajay,the follwing error i got. java.net.UnknowException http://vrundalaygardens.com/check.php etc.
one thing i didnt do any modification on your code.just i downloaded your app and just imported into my eclipse ide.then i just runned it.
But i dont know how to create php file and where to create and where i have to store that file…but my TL also doesn;t know this.can u plz help me sir..plz plz plz plz plz can u send step step process from from new android project to php and every thing…if possible plz send every thing to this mail:mahesh.bangalore123@gmail.com
hi, im getting an error saying ” id cannot be resolved or is not a field ”
where i should define this “id.et_un” ? and how ?
Good article. I have a similar one to connect to a mysql database that your readers might find useful. It explains the whole process of getting the php files into a live server and also creating the mysql database:
http://adblogcat.com/connect-mysql-remote-server-php/
Where did you put your php file?
In your own domain?
lot of thanks
Hello,
Thanks for the tutorial. when I enter the username and the password, I have this error : “android.osNetworkOnMainThreadException”
Could u plz help me?
regards
Hello,
When I access to my php file from the localhost, I got this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\mesRequetes\log.php on line 11
This is my code:
0)
// ( $un == “ajay” && $pw == “ajay”)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Plz plz help me!!
Regards
sir,
i am new to such connections of database with android and i have to do a project which requires such a database.i will be having a database on a free hosting server for eg:” xxx.com ” ie my host….i wanted to know that the php file i will be writing …where should i locate it ie whether the php file should be on my host ie “xxx.com” or it will be along with the android project i create or somewhere else.
please help sir,looking forward for your response.
regards,
RISHABH
Thanks bro its awesome !!!!! Works fine
How do I get data from remort database to view in spinner in android ?
Hello! I am using your code as local host.
But the problem is that proper response is not available to my emulator.
I got response string as
I need the solution as quick as possible.
So plz tell me what to do.
Thanks.
hello guys, please help me with this one.. i’ve just made an application that displays database from mysql (localhost) on emulator, then i wanna add this login before i can access that application.. help please
how can this login connect with my application after it succeded in login?
Thank you this is a very good tutorial, but I encounter a problem during the execution of this project with the use of android version 4.0 and some 3.0 Please help me to solved this problem
Sincerely,
package com.best.college.hunt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient
{
public static final int HTTP_TIMEOUT = 30 * 1000;
private static HttpClient mHttpClient;
private static HttpClient getHttpClient()
{
if (mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer(“”);
String line = “”;
String NL = System.getProperty(“line.separator”);
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer(“”);
String line = “”;
String NL = System.getProperty(“line.separator”);
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
}
}
package com.best.college.hunt;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class page2 extends Activity
{
EditText un,pw;
TextView error;
Button ok;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabSpec spec1=tabHost.newTabSpec(“Login”);
spec1.setContent(R.id.tab1);
spec1.setIndicator(“Login”);
TabSpec spec2=tabHost.newTabSpec(“Register”);
spec2.setIndicator(“Register”);
spec2.setContent(R.id.tab2);
TabSpec spec3=tabHost.newTabSpec(“About”);
spec3.setIndicator(“About”);
spec3.setContent(R.id.tab3);
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
un=(EditText)findViewById(R.id.editText1);
pw=(EditText)findViewById(R.id.editText2);
ok=(Button)findViewById(R.id.button1);
error=(TextView)findViewById(R.id.textView1);
ok.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
ArrayList postParameters = new ArrayList();
postParameters.add(new BasicNameValuePair(“username”, un.getText().toString()));
postParameters.add(new BasicNameValuePair(“password”, pw.getText().toString()));
String response = null;
try
{
response = CustomHttpClient.executeHttpPost(“http://10.0.2.2/check.php”, postParameters);
String res=response.toString();
// res = res.trim();
res= res.replaceAll(“\\s+”,”");
//error.setText(res);
if(res.equals(“1″))
error.setText(“Correct Username or Password”);
else
error.setText(“Sorry!! Incorrect Username or Password”);
} catch (Exception e) { un.setText(e.toString()); }
}
});
}
}
not connecting to database mysql…. can any one help me
I have questions about the “people” table from
$query = “SELECT * FROM people WHERE username = ‘$un’ AND password = ‘$pw’”;
Where is it located?Do I have to create this first?what should be its contents??
Please reply as soon as possible..Thanks!
HI Ajay Patel ,
Good tutorial,I good everything properly, but I got 1 issue over here, while giving username and password it shows Invalid each time, I created one same db in host and sample table and added 1 value to that table, but while trying to fetch tat same data , its shows error….. help me for this.. thank u in advance
[...] have a problem connecting database with Android app. I am trying to implement this tutorial. Everything seems to be fine but I neither get any success not an [...]
I have this android code i need to add user name and passwd whatever users login can show it on server side database…plz help m new in android..what changes i have to make in this code
/**
*
*/
package com.ssc.olec.candidate;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.ssc.olec.AndroidContext;
import com.ssc.olec.IndexActivity;
import com.ssc.olec.OLECDatabase;
import com.ssc.olec.R;
public class TestStartActivity extends Activity {
/** Called when the activity is first created. */
Bundle getTestTechnology;
String viewTestTechnology;
SQLiteDatabase dh;
private String rowId = null;
private String sQuestion, sOption1, sOption2, sOption3, sOption4;
private TextView tvQuestion;
RadioGroup rgAns;
private RadioButton rbOption1, rbOption2, rbOption3, rbOption4;
private boolean ischeck = false;
public int count = 0;
int check = 0;
ImageView nextQuestion, previousQuestion;
Drawable previousDisable, previousEnable, nextDisable, nextEnable;
Resources res;
Cursor cursor;
int total_mark=20,mpq=3,passmark=15,markobtained;
String userid=”r1″;
int candidateAns = 0;
String selectedanswer;
public String storedanswer;
public String grade;
int t = 9;
int limit = 1;
TextView timer;
InputStream in = null;
String result = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_question);
timer = (TextView) findViewById(R.id.timerview);
AndroidContext.setContext(this);
MyCount counter = new MyCount(60000, 1000);
counter.start();
dh = OLECDatabase.getInstance().getDb();
res = getResources();
previousDisable = res.getDrawable(R.drawable.leftarrow_disable);
previousEnable = res.getDrawable(R.drawable.left_arrow);
nextDisable = res.getDrawable(R.drawable.rightarrow_disable);
nextEnable = res.getDrawable(R.drawable.right_arrow);
// Get Selected Technology from previce page
getTestTechnology = getIntent().getExtras();
viewTestTechnology = getTestTechnology.getString(“TestTechnology”);
// viewTestTechnology=”Android”;
rgAns = (RadioGroup) findViewById(R.id.test_question_ans);
tvQuestion = (TextView) findViewById(R.id.test_question_content);
rbOption1 = (RadioButton) findViewById(R.id.test_option1);
rbOption2 = (RadioButton) findViewById(R.id.test_option2);
rbOption3 = (RadioButton) findViewById(R.id.test_option3);
rbOption4 = (RadioButton) findViewById(R.id.test_option4);
// Getting Questions on Selected technology from database
cursor = dh.query(OLECDatabase.QUESTIONS_TABLE, new String[] { “_id”,
“technology”, “question”, “option1″, “option2″, “option3″,
“option4″, “answer”, “isChecked” }, “technology =?”,
new String[] { viewTestTechnology }, null, null, null);
startManagingCursor(cursor);
if ((cursor != null) && cursor.moveToFirst()) {
rowId = cursor.getString(0);
System.out.println(“KOushik RowId :”+cursor.getString(0));
sQuestion = cursor.getString(cursor.getColumnIndex(“question”));
sOption1 = cursor.getString(cursor.getColumnIndex(“option1″));
sOption2 = cursor.getString(cursor.getColumnIndex(“option2″));
sOption3 = cursor.getString(cursor.getColumnIndex(“option3″));
sOption4 = cursor.getString(cursor.getColumnIndex(“option4″));
check = cursor.getInt(cursor.getColumnIndex(“isChecked”));
}
if ((sQuestion != null) && !sQuestion.trim().equals(“”)) {
tvQuestion.setText(“Question : ” + sQuestion.trim());
}
if ((sOption1 != null) && !sOption1.trim().equals(“”)) {
if (check == 1) {
rbOption1.setChecked(true);
} else {
rbOption1.setChecked(false);
}
rbOption1.setText(“Option 1 : ” + sOption1.trim());
}
if ((sOption2 != null) && !sOption2.trim().equals(“”)) {
if (check == 2) {
rbOption2.setChecked(true);
} else {
rbOption2.setChecked(false);
}
rbOption2.setText(“Option 2 : ” + sOption2.trim());
}
if ((sOption3 != null) && !sOption3.trim().equals(“”)) {
if (check == 3) {
rbOption3.setChecked(true);
} else {
rbOption3.setChecked(false);
}
rbOption3.setText(“Option 3 : ” + sOption3.trim());
}
if ((sOption4 != null) && !sOption4.trim().equals(“”)) {
if (check == 4) {
rbOption4.setChecked(true);
} else {
rbOption4.setChecked(false);
}
rbOption4.setText(“Option 4 : ” + sOption4.trim());
}
previousQuestion = (ImageView) findViewById(R.id.previousQuestionButton);
nextQuestion = (ImageView) findViewById(R.id.nextQuestionButton);
Cursor c = null;
if (rowId != null) {
c = dh.query(OLECDatabase.QUESTIONS_TABLE, new String[] { “_id” },
“_id ” + c.getColumnCount());
startManagingCursor(c);
if (c.getCount() == 0) {
previousQuestion.setImageDrawable(previousEnable);
previousQuestion.setEnabled(false);
previousQuestion.setClickable(false);
} else {
// previousQuestion.setImageDrawable(previousEnable);
previousQuestion.setVisibility(View.GONE);
}
c = dh.query(OLECDatabase.QUESTIONS_TABLE, new String[] { “_id” },
“_id > ?”, new String[] { rowId }, null, null, null);
System.out.println(“corsor count for next ->” + c.getColumnCount());
startManagingCursor(c);
if (c.getCount() == 0) {
nextQuestion.setImageDrawable(nextDisable);
nextQuestion.setEnabled(false);
nextQuestion.setClickable(false);
} else {
nextQuestion.setImageDrawable(nextEnable);
nextQuestion.setVisibility(View.VISIBLE);
}
} else {
previousQuestion.setImageDrawable(previousDisable);
previousQuestion.setEnabled(false);
previousQuestion.setClickable(false);
nextQuestion.setImageDrawable(nextDisable);
nextQuestion.setEnabled(false);
nextQuestion.setClickable(false);
}
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
t–;
if (t != -1) {
MyCount counter = new MyCount(60000, 1000);
counter.start();
} else {
timer.append(“Times Up”);
compute();
}
}
@Override
public void onTick(long millisUntilFinished) {
timer.setText(“Timer Left” + t + “:” + millisUntilFinished / 1000);
}
}
public void clickHandler(View v) {
ContentValues args = null;
args = new ContentValues();
/* if (v.getId() == R.id.previousQuestionButton) {
switch (rgAns.getCheckedRadioButtonId()) {
case R.id.test_option1:
candidateAns = 1;
break;
case R.id.test_option2:
candidateAns = 2;
break;
case R.id.test_option3:
candidateAns = 3;
break;
case R.id.test_option4:
candidateAns = 4;
break;
}
args.put(“isChecked”, candidateAns);
dh.update(OLECDatabase.QUESTIONS_TABLE, args, “_id=?”,
new String[] { String.valueOf(rowId) });
if (limit >= 1) {
limit–;
}
if (limit < 1) {
limit = 0;
}
moveToPreviousQuestion();
}*/
if (v.getId() == R.id.nextQuestionButton) {
switch (rgAns.getCheckedRadioButtonId()) {
case R.id.test_option1:
candidateAns = 1;
break;
case R.id.test_option2:
candidateAns = 2;
break;
case R.id.test_option3:
candidateAns = 3;
break;
case R.id.test_option4:
candidateAns = 4;
break;
}
args.put("isChecked", candidateAns);
dh.update(OLECDatabase.QUESTIONS_TABLE, args, "_id=?",
new String[] { String.valueOf(rowId) });
if (limit 10) {
limit = 10;
} else {
// Toast.makeText(getApplicationContext(), “Exam_over”,
// Toast.LENGTH_LONG).show();
// compute();
AlertDialog.Builder builder = new AlertDialog.Builder(
TestStartActivity.this);
builder.setTitle(“Last Question”);
builder.setMessage(“Show Results ?”)
.setPositiveButton(“Yes”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
compute();
}
})
.setNegativeButton(“No”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
}
}).create().show();
}
}
}
private void moveToPreviousQuestion() {
String previousRowId = “”;
ContentValues args = null;
if ((cursor != null) && cursor.moveToPrevious()) {
rowId = cursor.getString(0);
sQuestion = cursor.getString(cursor.getColumnIndex(“question”));
sOption1 = cursor.getString(cursor.getColumnIndex(“option1″));
sOption2 = cursor.getString(cursor.getColumnIndex(“option2″));
sOption3 = cursor.getString(cursor.getColumnIndex(“option3″));
sOption4 = cursor.getString(cursor.getColumnIndex(“option4″));
int check = cursor.getInt(cursor.getColumnIndex(“isChecked”));
/*
* if (check == 0) { ischeck = false; } else { ischeck = true; }
*/
args = new ContentValues();
args.put(“isChecked”, candidateAns);
System.out.println(“Viewing Technology 1->” + viewTestTechnology);
System.out.println(“Viewing sQuestion ->” + sQuestion);
System.out.println(“Viewing sOption1 ->” + sOption1);
System.out.println(“Viewing sOption2 ->” + sOption2);
System.out.println(“Viewing sOption3 ->” + sOption3);
System.out.println(“Viewing sOption4 ->” + sOption4);
System.out.println(“is checked ->” + check);
if ((sQuestion != null) && !sQuestion.trim().equals(“”)) {
tvQuestion.setText(“Question : ” + sQuestion.trim());
}
if ((sOption1 != null) && !sOption1.trim().equals(“”)) {
rbOption1.setText(“Option 1 : ” + sOption1.trim());
if (check == 1) {
rbOption1.setChecked(true);
} else {
rbOption1.setChecked(false);
}
}
if ((sOption2 != null) && !sOption2.trim().equals(“”)) {
rbOption2.setText(“Option 2 : ” + sOption2.trim());
if (check == 2) {
rbOption2.setChecked(true);
} else {
rbOption2.setChecked(false);
}
}
if ((sOption3 != null) && !sOption3.trim().equals(“”)) {
rbOption3.setText(“Option 3 : ” + sOption3.trim());
if (check == 3) {
rbOption3.setChecked(true);
} else {
rbOption3.setChecked(false);
}
}
if ((sOption4 != null) && !sOption4.trim().equals(“”)) {
rbOption4.setText(“Option 4 : ” + sOption4.trim());
if (check == 4) {
rbOption4.setChecked(true);
} else {
rbOption4.setChecked(false);
}
}
/*
* tvOption1.setChecked(false); tvOption2.setChecked(false);
* tvOption3.setChecked(false); tvOption4.setChecked(false);
*/
} else {
Toast.makeText(getApplicationContext(), “This is First Question”,
Toast.LENGTH_LONG).show();
}
/*
* dh.update(OLECDatabase.QUESTIONS_TABLE, args, “_id=?”, new String[] {
* String.valueOf(previousRowId) });
*/
}
private void moveToNextQuestion() {
ContentValues args = null;
if (limit ”
+ viewTestTechnology);
System.out.println(“Viewing sQuestion ->” + sQuestion);
System.out.println(“Viewing sOption1 ->” + sOption1);
System.out.println(“Viewing sOption2 ->” + sOption2);
System.out.println(“Viewing sOption3 ->” + sOption3);
System.out.println(“Viewing sOption4 ->” + sOption4);
System.out.println(“is checked ->” + ischeck);
if ((sQuestion != null) && !sQuestion.trim().equals(“”)) {
tvQuestion.setText(“Question : ” + sQuestion.trim());
}
if ((sOption1 != null) && !sOption1.trim().equals(“”)) {
rbOption1.setText(“Option 1 : ” + sOption1.trim());
if (check == 1) {
rbOption1.setChecked(true);
} else {
rbOption1.setChecked(false);
}
}
if ((sOption2 != null) && !sOption2.trim().equals(“”)) {
rbOption2.setText(“Option 2 : ” + sOption2.trim());
if (check == 2) {
rbOption2.setChecked(true);
} else {
rbOption2.setChecked(false);
}
}
if ((sOption3 != null) && !sOption3.trim().equals(“”)) {
rbOption3.setText(“Option 3 : ” + sOption3.trim());
if (check == 3) {
rbOption3.setChecked(true);
} else {
rbOption3.setChecked(false);
}
}
if ((sOption4 != null) && !sOption4.trim().equals(“”)) {
rbOption4.setText(“Option 4 : ” + sOption4.trim());
if (check == 4) {
rbOption4.setChecked(true);
} else {
rbOption4.setChecked(false);
}
}
}
else {
// Toast.makeText(getApplicationContext(), “Exam_over”,
// Toast.LENGTH_LONG).show();
// compute();
AlertDialog.Builder builder = new AlertDialog.Builder(
TestStartActivity.this);
builder.setTitle(“Last Question”);
builder.setMessage(“Show Results ?”)
.setPositiveButton(“Yes”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
compute();
}
})
.setNegativeButton(“No”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
}
}).create().show();
}
}
}
public void compute() {
cursor = dh.query(OLECDatabase.QUESTIONS_TABLE, new String[] { “_id”,
“technology”, “question”, “option1″, “option2″, “option3″,
“option4″, “answer”, “isChecked” }, “technology =?”,
new String[] { viewTestTechnology }, null, null, null);
startManagingCursor(cursor);
cursor.moveToFirst();
//passmark = cursor.getCount() / 2;
while (cursor.isAfterLast() == false) {
selectedanswer = cursor.getString(8);
storedanswer = cursor.getString(7);
// Toast.makeText(getApplicationContext(),”AnswerStored:”+cursor.getString(7)+”SelectedAnswer:”+cursor.getString(8),Toast.LENGTH_LONG).show();
if (selectedanswer.equals(storedanswer)) {
Toast.makeText(
getApplicationContext(),
“AnswerStored:” + cursor.getString(2)
+ “SelectedAnswer:” + cursor.getString(8),
Toast.LENGTH_LONG).show();
count = count + 1;
}
cursor.moveToNext();
}
markobtained=mpq*count;
try {
URL url = new URL(“http://192.168.2.7:8181/OnlineExaminationCenter/services/ServiceProvider/store_result?total_mark=”+total_mark+”&mark_obtained=”+markobtained+”&result=”+grade+”&subject=”+viewTestTechnology+”&uname=”+userid); // ##############
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
HttpURLConnection httpConn = urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while (true) {
read = bis.read(buffer);
if (read == -1) {
break;
}
baf.append(buffer, 0, read);
}
result = new String(baf.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (count >= passmark) {
grade = “Pass”;
AlertDialog.Builder alert = new AlertDialog.Builder(
TestStartActivity.this);
alert.setTitle(“Online_Exam”);
alert.setMessage(“Your Result:” + grade);
alert.setPositiveButton(“OK”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Intent indexIntent = new Intent(
TestStartActivity.this, IndexActivity.class);
startActivity(indexIntent);
}
});
alert.show();
} else {
grade = “Fail”;
AlertDialog.Builder alert = new AlertDialog.Builder(
TestStartActivity.this);
alert.setTitle(“Online_Exam”);
alert.setMessage(“Your Result:” + grade);
alert.setPositiveButton(“OK”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Intent indexIntent = new Intent(
TestStartActivity.this, IndexActivity.class);
startActivity(indexIntent);
}
});
alert.show();
}
}
}
Hello All…………This is sandeep i am new to mobile development in android…I am in training so could any one suggest me the future of android in the perspective view of career
Hi Ajay Patel,
I downloaded ur code and I cahanged to ma php page, but it works only the Front end, it is not fetching the data from my remote data base.. help me plz reg this Issue
Hi to alll,
I downloaded ur code and I cahanged to ma php page, but it works only the Front end, it is not fetching the data from my remote data base.. help me plz reg this Issue
Hi Ajay….,
The above tutorial is connecting mysql using remote database..it is successfully worked for me..thanks for giving such a nice tutorial…But now i wish to need how is connecting mysql database using soap webservices…please help me ajay.
Hi
I used the same code but when i ran it there was an error
process has stopped unexpectedly.
I used package com.android.rss.
Please help.
thank Ajay …
your tutorial work in my android application
I am new to Android, I want to create sample application in which when user open my application first user has to login into my application in mysql which on server. After successful login I want to display menu or other pages. But I want to know how user can see other pages of my application only and only after login successfully? So Any one can help me for this?
Hi Ajay,
I have one issue when I run your project.
I have set up my SQL table and entered one user, when I run the project in the Android emulator I enter the correct username and password, click login. I then get the error message “Sorry!! incorrect Username or Password.
I have double check that the username and password are correct, and they are. Do you have any idea why I am getting the error message.
Regards,
Dereck
Thank you sir i got a output through your code
yaa its working?
please give me your next project
Hello sir i cann’t execute your project in android4.0.3 version and sdkversion=15.
It’s showing android.Os.NetworkMain thread Exeception
Hi Ajay,
I just downloaded the code and i executed it in eclipse. I am getting login2 has stopped unexpectedly. Pls help me and i am new to android.
Thanks,
Udhayakumar G K.
Hi Ajay
I have asked this question to lot of people and blog and I never got any reply so far. just though of asking your help here.
I am developing following application
Spring Web Application(App Client)
Spring Restful Services and this restful service contains all user login information and other business data
Android Client
I have question that how should my App Client and Android client send user and password to Restful Service Application and get authenticated
Suppose even after authenticated , how do they maintain user information in further calls in both App Client and Android Client since Restful is stateless
Could you please give me clear picture and your help would be appreciated
Thanks
May i know where to put the remote server PHP file, check.php at? The .php file is it put under the xampp/htdocs folder?
When i create a new database, do i have to put any tables of users or..?
When i type in the username and password i get,
java.lang.illegal state exception in the field itself.
Please help me sir.
Thanks,
Udhayakumar G K.
http://saijava.blogspot.in/
Dear,
I have just read you post and I am gonna make mine. However, I am facing with some minor errors that I don’t where it comes from. I check the .php file, it’s ok due to return the correct result by testing parameter. But the main thing is that nothing happens when I click the ‘Login’ button because it seems that the java code has not been connected to the .php file even I make a setup as same as yours. Can you point out what the way the java code connects to the php file?
Hi Ajay,
Thanks for the tutorial.
I’m getting warning in CustomHttpClient.java for
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception {
and
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
When I tried to add NameValuePair before ArrayList as mentioned in one of the comment I got error. Though code is working fine but want to remove the warning as well.
Please let me know the fix to this warning.
I need to find an integer on database how can i send an integer by this function :
postParameters.add(new BasicNameValuePair(“password”, pw.getText().toString()));
Thanks man. I edited it a little and got it to work with json. Next step is sqlite.
The best part of this tutorial is the customHttpClient. It highlights what is most important. Most people just put it with the parsers etc
thank u man…but i have one doubt…u store the username and password in sqlite right….any one can change or add new username and password in sqlite easily and get enter into app??????
Thanks a ton.
[...] Android login authentication with remote (MySql)database [...]
Hi, I’m new for web based project, i have used your code and executed and the result is org.apache….eEception:The target server failed to respond… how to solve this…
everything seems to be fine, connection to the db from .php is okay, android to website is okay but the problem is instead of returning values 1 or 0 to the phone it’s returning values like this “nullnullnullreplacenull<scriptlanguage="JavaScript"….." The thing is i'm using php. any help will be greatly appreciated.
correction to my post, i received a 403 forbidden access from my site, how do i solve it.
Hi і аm kavin, its my firѕt occasion tο cοmmenting anyplace, ωhen i rеad this ρarаgraph
i thοught i coulԁ аlso сreаte сomment due to thіѕ gοod paragгaph.
I just could not leave your website before suggesting that I
really loved the usual info a person provide to your visitors?
Is gonna be again regularly in order to inspect new posts
Asking questions are actually fastidious thing if you are not
understanding anything fully, but this paragraph offers good
understanding yet.
Hello, your tutorial is very useful for my android project. Could you please let me know how to modify the Android Mainifest.xml to make my code work?
Thanks in advice.
Ajay, please help. Every time I press login button, it says correct username or password. what can I do?
thanks for your work
what use of customhttpclient.java please reply soon
good tutorial, where to add this check.php file do i need to create a separate file and upload it to server or can i place that in wordpress editor ?
Hello,
I’ve encountered the same problem as Andoo.
When I access to my php file from the localhost, I got this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\mesRequetes\log.php on line 11
This is my code:
0)
// ( $un == “ajay” && $pw == “ajay”)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Plz plz help!!
Regards
Where do i have to add the php or jsp file in eclipse?? i mean which folder?? Please reply asap! its urgent! Please help!
It will be hosted on server not in your android project, you are communication with remote server and remote server can understand php / jsp.
android can fetch data in MS ACCESS?
You truly created a number of remarkable items in your post, “Android login authentication with remote
db – WebDesignerGeeks – Web Designer, Web Developer blog WebDesignerGeeks – Web Designer, Web Developer
blog”. I will become coming back to ur page soon enough.
Thx ,Matthias
Thanks … I have been searching for weeks for a working example and finally I found one. With much tweaking(corrected the PHP and my IP addresses) it eventually works. And to all out there that says says emulator should have referal IP of 10.0.2.2 for 127.0.0.1 that does not work , my machine’s LAN IP address of 10.14.x.x worked. Emulator on server machine and even from my Galaxy S3 wirelessly. Thanks alot to author.
I like the valuable info you provide on your articles. I’ll bookmark your weblog and take a look at once more right here regularly. I am somewhat certain I will learn many new stuff proper here! Good luck for the next!