First create a database named “mydatabase” in MySql. Then create a table “tbl_user” with three fields (id, username and password).
The next step is to create a php page which will communicate between the MySql database and the android application.
For this create a “Connections.php” page as shown below. It will set up a connection to the database with the username and password
$hostname_localhost ="localhost"; $database_localhost ="mydatabase"; $username_localhost ="root"; $password_localhost =""; $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
Then the main PHP file is to be created. Actually the android application will call this php file along with the data(username and password ) and this code will check the database. If the details is valid then it will return “Y” and otherwise return “N”.
Here the data is passed as POST method. We can also use GET method where the data is passed along with the url . Android support both these two features.
<?php require_once('yourfolder/Connections.php'); mysql_select_db($database_localhost,$localhost); $useremail = $_POST['UserEmail']; $password = $_POST['Password']; $query_search = "select * from tbl_user where username = '".$useremail."' AND password = '".$password. "'"; $query_exec = mysql_query($query_search) or die(mysql_error()); $rows = mysql_num_rows($query_exec); if($rows --> 0) { echo "Y"; } else { echo "N"; } ?>
So by now we created php and the database part. Then we have to focus on android section. For this first create a xml file which will be our login screen.The screen look like this.
The layout of the xml is displayed below.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff2a1703" android:fadingEdge="horizontal"> <TextView android:id="@+id/text" android:text="manage your projects..." android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif" android:textStyle="italic" android:layout_centerHorizontal="true" android:layout_alignParentTop="true" android:layout_marginTop="50dip" android:textSize="20sp" > </TextView> <EditText android:id="@+id/username" android:layout_width="213dip" android:layout_marginTop="60dp" android:layout_below ="@+id/text" android:layout_centerHorizontal="true" android:layout_height="wrap_content" android:hint="username" android:gravity="center" android:textSize="18sp" android:typeface="sans" android:textStyle="italic"> </EditText> <EditText android:id="@+id/password" android:layout_width="211px" android:layout_height="wrap_content" android:hint="password" android:textSize="18sp" android:typeface="sans" android:textStyle="italic" android:gravity="center" android:password="true" android:layout_marginTop="20dp" android:layout_below ="@+id/username" android:layout_centerHorizontal="true"> </EditText> <CheckBox android:id="@+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Remember me" android:layout_marginTop="10dp" android:layout_below ="@+id/password" android:layout_centerHorizontal="true"> </CheckBox> <Button android:id="@+id/login" android:layout_width="141px" android:layout_height="wrap_content" android:text="Login" android:textSize="22sp" android:typeface="serif" android:textStyle="bold" android:layout_marginTop="20dp" android:layout_below ="@+id/check" android:layout_centerHorizontal="true"> </Button> </RelativeLayout>
We now create the java file . This file should contain the 3 sections
1. Store the preference when the checkbox is checked
2. Establish a connection between this file and the php file
3. Validate the user
package com.ar.mydatabaseProject.pack; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class mydatabaseProject extends Activity { /** Called when the activity is first created. */ Button login; String name="",pass=""; EditText username,password; TextView tv; byte[] data; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; InputStream inputStream; SharedPreferences app_preferences ; List<NameValuePair> nameValuePairs; CheckBox check; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); app_preferences = PreferenceManager.getDefaultSharedPreferences(this); username = (EditText) findViewById(R.id.username); password = (EditText) findViewById(R.id.password); login = (Button) findViewById(R.id.login); check = (CheckBox) findViewById(R.id.check); String Str_user = app_preferences.getString("username","0" ); String Str_pass = app_preferences.getString("password", "0"); String Str_check = app_preferences.getString("checked", "no"); if(Str_check.equals("yes")) { username.setText(Str_user); password.setText(Str_pass); check.setChecked(true); } login.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { name = username.getText().toString(); pass = password.getText().toString(); String Str_check2 = app_preferences.getString("checked", "no"); if(Str_check2.equals("yes")) { SharedPreferences.Editor editor = app_preferences.edit(); editor.putString("username", name); editor.putString("password", pass); editor.commit(); } if(name.equals("") || pass.equals("")) { Toast.makeText(mydatabaseProject.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show(); } else { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://10.0.2.2/android/user_validate.php"); // Add your data nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim())); nameValuePairs.add(new BasicNameValuePair("Password", pass.trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request response = httpclient.execute(httppost); inputStream = response.getEntity().getContent(); data = new byte[256]; buffer = new StringBuffer(); int len = 0; while (-1 != (len = inputStream.read(data)) ) { buffer.append(new String(data, 0, len)); } inputStream.close(); } catch (Exception e) { Toast.makeText(mydatabaseProject.this, "error"+e.toString(), Toast.LENGTH_LONG).show(); } if(buffer.charAt(0)=='Y') { Toast.makeText(mydatabaseProject.this, "login successfull", Toast.LENGTH_LONG).show(); } else { Toast.makeText(mydatabaseProject.this, "Invalid Username or password", Toast.LENGTH_LONG).show(); } } } }); check.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on clicks, depending on whether it's now checked SharedPreferences.Editor editor = app_preferences.edit(); if (((CheckBox) v).isChecked()) { editor.putString("checked", "yes"); editor.commit(); } else { editor.putString("checked", "no"); editor.commit(); } } }); } public void Move_to_next() { // startActivity(new Intent(this, zzz.class)); } }
At last don’t forget to put the permission in Manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Note : if you have any problem in working with this post, please check this more simple version here.
Here is another more detailed explanation.
How to create Simple Login form using php in android? – Connect php with android.
Pingback: ANDROID - Upload an image to a server | Coderz Heaven
public void Move_to_next()
{
// startActivity(new Intent(this, zzz.class));
}
in my case my new activity is not started plaese help me anyone ?
what is happening? Is your app crashing?
can you pls tell me what permissions to write in manifest.xml????
and the namevaluepair is giving error……. I dont know why????
Did you import this one “import org.apache.http.NameValuePair“, Check whether your case is correct or not. This is the permission you need to set in androidmanifest.xml
Place this before or after the application tag.
It is a collection…..No need to add permission in the Manifest. Only Internet Permission is required…Can you specify the details of the error.
Pingback: Android « thomastka
I also have error in my eclipse in the following line:
nameValuePairs = new ArrayList(2);
how do i fix it?
import org.apache.http.NameValuePair is already insert.
Hi nik……
I think there is some problem in the case. change the “namevaluepair” to “nameValuePairs” in the error line.
I think this will work.
sorry friends…..use “NameValuePair” instead of “namevaluepair”………
It might have occured when i copied the code…….
Hello! interesting site!
Hello! interesting site!
thanks for the tutorial. I will try this
this is great.. its worked for me 😀
plz…..can you post your enyire code…i’m trying get conn.btween mysql database in android app.for many days but i failed….!!
hello….i try this .. i dont know implement this ……..
httpclient = new DefaultHttpClient();
httppost = new HttpPost(“http://10.0.2.2/android/user_validate.php”);
What is this ? ….is it connect to php “validate.php”
http://10.0.2.2/ /// is it local host …….
already everthing i done ….base on ur tutorial…….i use eclipe java ……it how to connect with php file……
Hello Peter 10.0.2.2 is the localhost…
If you want to try it in a remote domain then change it to http://yourdomain.com/your_folder/your_phpfile
Try creating a sample file in the localhost and a simple echo inside it. then connect using the above code.
For eg: your file name is test.php and you have a folder named test_folder then change the URL to http://10.0.2.2/test_folder/test.php
This will work. make sure you are printing out the output. The output will be a stream, make sure to convert it to a string..
There is a sample post for that also . Let us know if you have any more doubts. Also while connecting to localhost make sure your server is running
I got lost somewhere here… how do you use connection.php and user_validate.php. are you referring to a one file sir? I got invalid user response and when i check the logcat it says something like no window to dispatch pointer action 1.
Those are two files, the connection.php is used for connecting to mySQL database and other file you can use as you wish , you can have anything inside it. The error you got is not due to these files.
If you have any doubt, send your project to coderzheaven@gmail.com
Thanks for another informative website. Where else could I get that kind of info written in such an ideal way? I’ve a project that I am just now working on, and I’ve been on the look out for such information.
i tried to implement code but when i try to run it always say invalid password it not check buffer why this the code after edit
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
username = (EditText) findViewById(R.id.editText1);
password = (EditText) findViewById(R.id.editText2);
login = (Button) findViewById(R.id.button1);
check = (CheckBox) findViewById(R.id.check);
b2 = (Button) findViewById(R.id.button2);
String Str_user = app_preferences.getString(“username”,”0″ );
String Str_pass = app_preferences.getString(“password”, “0”);
String Str_check = app_preferences.getString(“checked”, “no”);
if(Str_check.equals(“yes”))
{
username.setText(Str_user);
password.setText(Str_pass);
check.setChecked(true);
}
b2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
startActivity(new Intent(“ied.Graduationproject.TUTORIALONE”));
}
});
login.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
name = username.getText().toString();
pass = password.getText().toString();
String Str_check2 = app_preferences.getString(“checked”, “no”);
if(Str_check2.equals(“yes”))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString(“username”, name);
editor.putString(“password”, pass);
editor.commit();
}
if(name.equals(“”) || pass.equals(“”))
{
Toast.makeText(Graduationproject.this, “Please Enter your Information”, Toast.LENGTH_LONG).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(“http://10.0.2.2/brca/check.php”);
// Add your data
nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair(“username”, name.trim()));
nameValuePairs.add(new BasicNameValuePair(“assword”, pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
String res=inputStream.toString();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(Graduationproject.this, “error”+e.toString(), Toast.LENGTH_LONG).show();
}
if(buffer.charAt(0)==’Y’)
{
Toast.makeText(Graduationproject.this, “login successfull”, Toast.LENGTH_LONG).show();
Move_to_next();
}
else
{
Toast.makeText(Graduationproject.this, “Invalid Username or password”, Toast.LENGTH_LONG).show();
}
}
}
});
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it’s now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString(“checked”, “yes”);
editor.commit();
}
else
{
editor.putString(“checked”, “no”);
editor.commit();
}
}
});
}
public void Move_to_next()
{
startActivity(new Intent(this, Wellcom.class));
}
}
frind…this is the same code…….i think there must be error in the php file….may be the mysql query not returning the correct value
Thanks for your tutorial .this was really helpful.
But i need a favor , can u show me how to insert values of radio button , check box and dropdown list into mysql using php.
If you could help me through this then i would be really thankfull to you.
identify each values with a key. Like if there are two radio buttons like male and female, then add to the database as 0 or 1 and then while retreiving from the database just check whether it is 0 or 1 and check the radio button. Do the same with other controls also.
i want to ask another question can i get sample code for insert to mysql
I am getting errors in these lines :
setContentView(R.layout.login);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
//error is : ‘login’ can’t be resolved or is not a field
login = (Button) findViewById(R.id.login);
//error is : ‘id’ can’t be resolved or is not a field
Its not due to the code…..May be your project do not have the “gen” folder…..thas why this error.Try clean the project.If that doesnt work then right click(project)–>properties–>android–>check any target and click ok
Login is the layout xml file. Rename your main.xml to login.xml
remove import android.R and you are ok
late response:<
dude thanks for the reply
i do have a gen folder with R.java file in it
R.java cannot be modified so despite doing the quick fix in eclipse i cant solve the errors
i must say the AndroidManifest.xml is proper with no errors..i have put the reqd permission only the error is what i have mentioned above
k frnd…..bt usually this error occur in above mentioned situations…thas why…Have you tried creating a new project and then copying the contents..
and yea my target is ticked ..it’s android 2.3.3
yes yes i created a new android project
then entered the following as per ur code:
project name:mydatabaseProject
package name: com.ar.mydatabaseProject.pack
activity name : mydatabaseProject
application name : mydatabaseProject
and then i inserted that permission in manifest.xml and also copied same code in main.xml as what is provided in this page
if ur online rite now , can u just do a teamviewer session …dat will help solve problems quickly i guess
What are your problems? Type in here we will help u.
we dont have an account there…..can you sent me your code to coderzheaven@gmail.com…..i wil check
My problem are those errors that I have mentioned above , i m running the code in eclipse … i have all the android sdk installed ( no issues with that and the ADK plugin is also der..all pre requisites reqd for android coding are present )
but however i am getting those errors mentioned above..so i cant run my code…please help
yup sent a mail to ur given address ..thnx for immediate reply and please reply back soon
and btw u dnt need to have an account for teamviewer..it’s an open source software ..google for teamviewer …it’s a cool way to remote access someone’s machine
Sorry pankaj, U can send us emails. We will reply as fast as we can.
hey thanks a lot for the quick reply guys !! I just have one problem more which i hv mailed u ..please check it and tell me asap
thanks once again !!
Great tutorial, but lets just say that I wanted to have a home page after a successful login. How do I go about that? Point me in the right direction.
Create a new class that extends activity and call this class using startActivity.
i have did every thing as per the instruction…. and its really happy for me to se such an awesome tutorial…
nw my problem is, i have insterted values fr username and password… but then what ever the valued i give in the emulator and press Login Button it says
“The Application Has Stopped UnExpectedly, Pls Try Again ”
Im facing this repeatedly…. but there is no error shown in the java as well as xml code.
is there any problem with php?
im using xampp and ive changed the host address… i got a folder inside it and saved those two php. in the java file also i have provided the link for php.
Pls reply. Thanx in Advance.
And also i need to know…. how to get redirected to another page after that validation…. thanx fr ur support….
Create another class that extends activity. here I name it secondActivity.java that extends activity. Note that It should have onCreate function like anyother activity.
After that call this function.
startActivity(new Intent(your_activity.this,secons_activity.class));
call finish() on second_activity to close the activity.
Hello Jeba :- No, that problem is probably not from the php side. When you get this Force Close open the Logcat window from the “window->show View-> Logcat. You will be seeing the error in the red color.
Paste that error( (first two lines) here then only I can help you. Did you put the “http://” in the url.
Thank u fr d prompt reply sir…. i have put http already.
here is the report from log cat… kindly resolve this issue for me.
07-17 21:06:02.406: WARN/dalvikvm(402): threadid=1: thread exiting with uncaught exception (group=0x40015560)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): FATAL EXCEPTION: main
07-17 21:06:02.436: ERROR/AndroidRuntime(402): java.lang.NullPointerException
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at encore.bankdroid.bankdroid$1.onClick(bankdroid.java:107)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.view.View.performClick(View.java:2485)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.view.View$PerformClick.run(View.java:9080)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.os.Handler.handleCallback(Handler.java:587)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.os.Handler.dispatchMessage(Handler.java:92)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.os.Looper.loop(Looper.java:123)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at java.lang.reflect.Method.invokeNative(Native Method)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at java.lang.reflect.Method.invoke(Method.java:507)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-17 21:06:02.436: ERROR/AndroidRuntime(402): at dalvik.system.NativeStart.main(Native Method)
07-17 21:06:02.476: WARN/ActivityManager(60): Force finishing activity encore.bankdroid/.bankdroid
Thats Ok Sir….. in the previous post i have just copied the error from the logcat. could you pls resolve me? Still im facing the error message
“Application has stopped un expectedly… ” then Force Close Button….
pls sir….
Dear sir James, currently i.ve started to do a Simple Mobile Banking App as assignment to collg. it will be realy helpful if u send me any sample codes of any simple mobile banking with basic functionalities…. thanx in advance.
Sorry Jeba, I can only help you if you have any doubts. Ask your doubts and I will clear that.
dear sir…. as u hav asked i hav pasted the first two lines of the error frm the Log Cat….
Pls help me….
07-18 20:18:25.795: ERROR/AndroidRuntime(326): FATAL EXCEPTION: main
07-18 20:18:25.795: ERROR/AndroidRuntime(326): java.lang.NullPointerException
Oh Jeba, this is not enough. My suggestion is try commenting each like inside onclick function and see which line has the problem.
Or Can you see the a line starting with “cause” in the Logcat when the app crashes. Paste that line.
sir…. unexpectedly i have deleted that database… and now created another one similiar to that , i hav configured the php file. and inserted username and password admin admin
and now its saying Invalid Username/password
Hi Jeba: Print out the username and a password you are sending from android from php file and see.
I cant undrstnd that…. hw to do?
u mean to echo in php? wil u pls giv me an example ? pls….
thanx…
NO frind…..In java print the result from the php script using LOG.D, the result you can see in the logcat…or use TOAST to display .
dear sir…
i’m sory … i ve tried .. im nt able to find…. will u show me hw to do that ? im a very started to android and programming….
I’m getting an error with
“setContentView(R.layout.login);”
It says layout.login isn’t in my R file, now there is a layout.main and since R is the autogenerated file, it deletes any manual alterations to it.
So my question is, what/where do I need to insert/edit my files to find what adds layout.login
(I already copied the xml file above to my main xml)
NVM my original Post, I fixed that (it was quite simple, I simply changed layout to main but you can probably alternatively rename main to layout)
When ever I try to launch this program in my emulator, it just force closes, I can’t seem to find any error messes or anything. So I’m a little lost as to why this won’t atleast open.
Hello max: Check the latest post. This will help you.
Pingback: Android phpmySQL connection redone. | Coderz Heaven
i like this most and it’s really nice site and good content it had and above script will help me lot thanks for it…..
good sharing !!! thanks
Hi james,loved the tutorial,my code has no error in it,I have even got the emulator to run the code however no matter what password and username pair i use it still displays the error login Toast,I have gone through it,and am sure it doesnt have any syntax error,what could be the problem,or cant it acess the (xampp server).But if i ping 10.0.2.2 from the emulator terminal it can see the server
Are you getting any response from the server side while running the code. Try to echo back the values you are sending from the android side(eg. Username and password).
Or try this code. we have redone this code to help it understand more easily.
Hi
Im getting following exception in Android
================================================
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.loginapp.LoginAppActivity$1.onClick(LoginAppActivity.java:121)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8817)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:4914)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
Force finishing activity com.loginapp/.LoginAppActivity
================================================
Hi Karthy:- Check this post we have redone it for ease http://coderzheaven.com/2011/07/android-phpmysql-connection-redone/
Hi James, I’m new to android, I already search and trying many example on how to retrieve data from Mysql to android but seem no one success. :<"
Hi guys
Nice Tut, there is only one problem I am stuck!
I am using IntelliJ Idea as an IDE and Android Version 2.3.3
I copyied and pasted your code but I get the following error:
error: cannot find symbol variable login
It doesnt even open in the AVD I get the error in the error console after the code suddenly stops while compiling.
Please help me. I am researching for my final year project and I really need my android app to connect to a MySQL server.
Help will be much appreciated
Thanks in Advance
the android code is great, but your explination of what to do with mySQL and PHP lost me somewhere. What php files need to be created? I see reference to “connection.php”, ‘Connections/localhost.php’, ‘the main PHP file’, and “user_validate.php”. But I only see code for two php files. Am I suppose to create a ‘localhost.php’ file?
There is no localhost.php file, there is only connection.php which contains the code for connection with the database. You can connect to ant php file if the path is correct and the server is running,
I was able to get it working.
In the first line of your “user_validate.php” you reference ‘Connections/localhost.php’, which I believe should be ‘connection.php’.
To get things working I replaced the first line of the “user_validate.php” with the code needed to connect login to the host server.
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost).
I understand that proper mysql coding suggests having a separate file with he login credentials, but I was shooting for simplicity.
Solid information on the android side. Best code I have seen with regards to this.
hello there and thanks for the post!
i have a problem in compering buffer.charAt(0) with either the ‘Y’ or ‘N’ character…it drives me crazy
i can see that the php file returned Y/N but i cannot compare it with ‘Y’/’N’ in order to make a Succesful/unsuccesfull toast
mak :- Try this one
http://coderzheaven.com/2011/07/android-phpmysql-connection-redone/
thanks for your quick response james!!
i am new in android developing and it is very beautiful to see a solidarity like this
hi…i have did every thing as per the instruction…. and its really happy for me to se such an awesome tutorial…
nw my problem is, i have insterted values fr username and password… but then what ever the valued i give in the emulator and press Login Button it says
“The Application Has Stopped UnExpectedly, Pls Try Again ”
Im facing this repeatedly…. but there is no error shown in the java as well as xml code.
is there any problem with php?
im using xampp and ive changed the host address… i got a folder inside it and saved those two php. in the java file also i have provided the link for php.
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.loginapp.LoginAppActivity$1.onClick(LoginAppActivity.java:121)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8817)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:4914)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
Force finishing activity com.loginapp/.LoginAppActivity
Pls reply. Thanx in Advance.
Hey KrishnaVeni :-
There may be some error in line 121 of LoginAppActivity.java, if you can’t find any solution then Try this post http://coderzheaven.com/2011/07/android-phpmysql-connection-redone/
Please check the id’s in the xml and java whether they match or not.
Pingback: MySql connection - Android Forums
Hi james..
nw my problem is, i have insterted values for username and password… but then what ever the valued i give in the emulator and press Login Button it says
“The Application Has Stopped UnExpectedly, Pls Try Again”
Im facing this repeatedly…. but there is no error is displayed in logcat..how it is cleared..help me ….
How to get the response from the php……
The buffer.charAt(0)==’Y’ is not working for string..
Please slove the problem ASAP……….
Hey Shan Please check this post http://coderzheaven.com/2011/07/android-phpmysql-connection-redone/
or buffer.charAt(0)==’Y’ will work for string. PLease print that string in the logcat and check.
or sent another string from php side and check it in the android side, like send “success” and compare that string in the android side.
hi james,
I am getting this error frequently when making HTTPConnection.
The error is :
Error in http connection java.net.SocketException: The operation timed out
Sometimes it connects and sometimes not connected and displayed above timeout message…
I have tried with various link.It behaves same with all.
Why dis error is displayed…help me….
Hi James,
Your job is very helpful, thank you. Just wanted to clarify it’s important to run .php file in Xampp or Wampp? Because I have Vertrigo and during running the application by clicking login button I got a dialog box “Unfortunately, application has stopped” and program terminated. I tried several times, but result is the same. Here is the LogCat:
01-09 19:57:35.046: D/gralloc_goldfish(556): Emulator without GPU emulation detected.
01-09 19:57:54.166: D/AndroidRuntime(556): Shutting down VM
01-09 19:57:54.166: W/dalvikvm(556): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
01-09 19:57:54.195: E/AndroidRuntime(556): FATAL EXCEPTION: main
01-09 19:57:54.195: E/AndroidRuntime(556): java.lang.NullPointerException
01-09 19:57:54.195: E/AndroidRuntime(556): at jku.project.kusss.KusssActivity$1.onClick(KusssActivity.java:114)
01-09 19:57:54.195: E/AndroidRuntime(556): at android.view.View.performClick(View.java:3480)
01-09 19:57:54.195: E/AndroidRuntime(556): at android.view.View$PerformClick.run(View.java:13983)
01-09 19:57:54.195: E/AndroidRuntime(556): at android.os.Handler.handleCallback(Handler.java:605)
01-09 19:57:54.195: E/AndroidRuntime(556): at android.os.Handler.dispatchMessage(Handler.java:92)
01-09 19:57:54.195: E/AndroidRuntime(556): at android.os.Looper.loop(Looper.java:137)
01-09 19:57:54.195: E/AndroidRuntime(556): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-09 19:57:54.195: E/AndroidRuntime(556): at java.lang.reflect.Method.invokeNative(Native Method)
01-09 19:57:54.195: E/AndroidRuntime(556): at java.lang.reflect.Method.invoke(Method.java:511)
01-09 19:57:54.195: E/AndroidRuntime(556): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-09 19:57:54.195: E/AndroidRuntime(556): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-09 19:57:54.195: E/AndroidRuntime(556): at dalvik.system.NativeStart.main(Native Method)
01-09 19:59:06.487: I/Process(556): Sending signal. PID: 556 SIG: 9
Hey Orif, please check this post and try again
http://coderzheaven.com/2011/07/android-phpmysql-connection-redone/
Hi….am finished ur login page successfully completed..now i like to need next activity..that next activity having logged in user firstname and lastname detail…so i wrote one query..
$q=mysql_query(“SELECT firstname,lastname FROM customers WHERE (usertype =’A’)”);
while($e=mysql_fetch_assoc($q))
{
$row[]=$e;
}
print(json_encode($row));
here more number of admin user r logged in login page…that means admin users having permission… so here all admin user firstname and lastname displayed…but i need which admin person loged in login page that particular person detail only displayed…
$q=mysql_query(“SELECT firstname,lastname FROM customers WHERE ((usertype =’A’)&&(‘krishnaveni’))”);
itz not valuable coding…
so plz give me some solutions…(i.e)krishnaveni,kannan,hariprasad r admin user means when krishnaveni loged means krishnaveni detail ly displayed…kannan logged means kannan details only displayed..i dono how it is do???? plz give me solutions….thanks in advance…
This is really easy save the logged in username in a global variable or preferences or extras in the activity.Then get it in the next activity and query again the database with this username. that’s all.
check these links for setting the global variable and for passing the extras in the intent.
thanks for very useful solutions…but i can’t handle it…so how is handled dis coding in our login page..
hi james…stillnow i tried it…but i can’t do it…plz u r write the sample code for my requrirement and send me…plz help me james…
Hi….v tried ur code…in the login page what username and pwd shld v giv….whatever we give its showing as “invalid username and password”….pls help us…we are new to android
Hey jenny:- you decide your username and password. This question is irrelevant. Ur username and password should match the fields in the database, that’s all.
Thank u james…we tried ur code tat u posted later(AndroidPHPConnectionDemo)…v gt the excat response in emulator…but in php side it s showing as undefined index:EditText_value….vat else shld v add in php side other than these 2 lines…..pls help us……
‘EditText_value’ should match the same variable that u use to send the parameters in the namevalue pairs. It is also case sensitive.
Thank u so much 4 ur code…we gt the o/p…in our project v shld insert the data from android to server….in tat v hav several forms…in each form there are 3 pages…only if v click the save button in the 3rd page all the data in the 3 pages shld b saved together….4 tis v hav cookies concept in java…in android vat can v use….if u hav any sample code regarding tis can u pls mail me….pls help me…
hi james,how to insert spinner(combobox) and checkbox values from android to mysql..please send d syntax also sample code if u have…v used scrollview 4 joining all those forms.. ur info s really helpful…please help us….
Hay jenny:- First make a string with comma seperated with all the values in the spinner( like this “value1,value2,….”). Now send this to the mysql database ans store it there.
Now when you want this , send this string from the mysql database and split it in the android side and repopulate the spinner. that’s all. Please leave comments if you have any doubt.
You can send me messages on facebook, twitter and G+ also.
Hey james Thank u,….we tried as u said using the following code…
static final String[] Places=new String[]{“india”,”australia”,”america”,”southafrica”};
ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,Places);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
etPlaceofvisit.setAdapter(adapter);
in the onclick() try block,i hav tis line
nameValuePairs.add(new BasicNameValuePair(“Placeofvisit”,Places.toString().trim()));
In the php side,
$sql=mysql_query(“insert into countries(Placeofvisit) values(‘”.$_REQUEST[‘Placeofvisit’].'”)”);
we are getting the error as [Ljava.lang.String;@412a9750
vat changes i shld make in this code……..and if the chechbox is clicked how can i store the changes in mysql….
could u pls make the changes in tis code & clarify our doubt regarding checkbox….Thanks 4 ur help…..
we are getting the error as [Ljava.lang.String;@412a9750 in the column of the table..
hi James,
v got d o/p for spinner…thank u… if the chechbox is clicked how can i store the changes in mysql…. if u have sample code for retrieving data from mysql in JSON format,can u pls send us…thank u soo much ..
Hi james,
can u pls help us on how to store the changes in mysql if checkbox is clicked….can u pls tell us the syntax….waiting 4 ur reply
hi james,
How is connecting mysql database using jdbc in android…
Never tried it. I will check that.
Hi james,
can u pls help us on how to store the changes in mysql if checkbox is clicked….can u pls tell us the syntax….waiting 4 ur reply
Jenny : to Listen to checkbox add a listener to the checkbox and on isChecked() option run the code to update the SQL. I will put a simple post on this soon.
hello James,
pls send some sample code using javascripts in android…..
like if weight is greater than 120,the textbox colour has to be changed….pls help…..send for checkbox also..pls reply james sir ..
Hello James,
Thank u so much ….for validation purposes in android what can we use….for ex if weight is less than 20 and greater than 120,the textbox colour has to be changed while we type that value…..how can we do this….Thank u so much for ur help
Hi James,
We hav some doubts in the following program….this s for higligting the values if the value is 120….bt the color s nt getting changed…can u pls tell us vat modifications i shld make in tis code…pls help…v already posted u tis bt it was nt copied properly…..
package org.example.act;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.EditText;
import android.text.Editable;
import android.text.TextWatcher;
public class ActActivity extends Activity implements TextWatcher {
private EditText et;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.etx);
et.addTextChangedListener(this);
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
if(et.getId() 120)
et.setHighlightColor(getResources().getColor(R.color.mycolor));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
in string.xml,
i added the line,
#F5DC49
hey jeni : –
Change “et.getId() ” to Integer.parseInt(ed.getText().toString()).
ie.
if( Integer.parseInt(ed.getText().toString()) > 120){
// do the highlighting.
}
Jeni Dont paste the full code here. instead send the code as attachment to coderzheaven@gmail.com
Hi James
very nice tutorial 🙂
but i have this problem
after clicking sign in button it displays a message unfortunatly database has stopped
Pingback: Using SQLite in ANDROID, A really simple example. | Coderz Heaven
Pingback: ANDROID - Upload an image to a server | Coderz Heaven
Nice tutorial very helping ///great work//
I am new to android apps, php, and sql. The main PHP code, is that a part of the connection.php file? If not, where do you create one? Can it be created in Eclipse? If yes, what folder should it reside under (e.g., res, assets). Any help is appreciated. Thank you.
yes create two php files connections.php and the other file. Then include the connections.php in the second file.
OR you can put the two codes in the same file also.
I created one php file named connection.php, which includes the code below and I saved it under C:….xampp/htdocs/test/connection.php
0) { echo “Y”; }
else {echo “N”; }
Do I have to move this file to my Android app as well? If yes, in which folder do I save it?
The php code in my previous post didn’t paste in its entirety. Anyway, I have one php file named connection.php, which contains both codes. The one below your comments: “For this create a “Connections.php” page as shown below” and the other one below “Then the main PHP file is to be created”. I really appreciate your help. It’s been a frustrating two week for me as I can’t seem to get passed the Login page point let alone do something else.
I am getting syntax errors on token “>” in span class line in my .java file – expression expected after this token and reference type expected instead
Hello Dan, by including I meant including the ‘incude’ statement in php. Create two files inside your xampp/htdocs/test/ folder and that’s all. then call this php file from the android side using my example.
If you want another simple explanation then see this post Android phpmySQL connection redone.
Would you mind sending the entire code including php files to my email? I am showing a whole bunch of syntax errors that I can’t figure out how to to fix.
Hello Dan. PLease check your mail we have sent you the code. or else you can check this post where you can download the source from the link below the post.
http://www.coderzheaven.com/2012/04/22/create-simple-login-form-php-android-connect-php-android/
One of the messages I am getting in my Eclipse Console after pressing the Login button….ActivityManager: Warning: Activity not started, its current task has been brought to the front
Hello Dan, These are not errors. Activity not started…. means you have run the code once and you are trying to run the code without editing anything(means no build change).
after entering user name and password and hitting Login, I get “Validating user…” message and then nothing. The screen doesn’t change to userpage.xml. Even when enter incorrect user name and password I get the same. Is it possible that my app is not talking to “mydatabase”?
Are you getting anything in the LogCat. First check whether you have internet connection in the emulator and check the important points I have written in the post. If you follow the steps exactly it will work for sure.
My LogCat says (after pressing the Login button)
Connection to http:/…. refused.
Error reading data file
request time failed: java.net.SocketException: Address family not supported by protocol
check whether your emulator has internet connection and also check whether the server is running.
OK, so I finally got it to work!!! The only unknown is in the userpage.xml, which is supposed to replace the main screen if the login is successful, but it doesn’t. I see the Login Success after the validation process is complete, but the screen doesn’t change. Here is my code in
MydatabaseActivity.java
//there is some code here after which I have this code
if(response.equalsIgnoreCase(“User Found”)){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MydatabaseActivity.this,”Login Success”, Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(MydatabaseActivity.this, UserPage.class));
}else{
showAlert();
}
any ideas as to why userpage.xml doesn’t kick in?
Check the logcat. You may not have decalred the UserPage activity in the AndroidManifest.xml.
I got it to work. Finally!!! I had my UserPage activity in the Mainfest file in the wrong spot! What I am trying to do next (now that the user is logged in) is to have the android client pull the data (e.g., list of names) from remote Db and display as a list to the user. Can you please suggest how do I go about doing that! Or can you suggest a good tutorial.
Pingback: How to create Simple Login form using php in android? - Connect php with android.
Hello, haw to update date from mysql database ??
Hello Mourad:- After all date is a string, make it a string and update.
im using this following code …whenever i enter the values in fields and click the login button is shows me and error
=>Unfortunately loginForm has stopped
🙁
package com.example.loginform;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.view.Menu;
public class LoginTest extends Activity {
Button login;
String name=””,pass=””;
EditText username,password;
TextView tv;
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences ;
List nameValuePairs;
CheckBox check;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_test);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString(“username”,”0″ );
String Str_pass = app_preferences.getString(“password”, “0”);
String Str_check = app_preferences.getString(“checked”, “no”);
if(Str_check.equals(“yes”))
{
username.setText(Str_user);
password.setText(Str_pass);
check.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
name = username.getText().toString();
pass = password.getText().toString();
String Str_check2 = app_preferences.getString(“checked”, “no”);
if(Str_check2.equals(“yes”))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString(“username”, name);
editor.putString(“password”, pass);
editor.commit();
}
if(name.equals(“”) || pass.equals(“”))
{
Toast.makeText(LoginTest.this, “Blank Field..Please Enter”, Toast.LENGTH_LONG).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(“http://127.0.0.1/android/Test/login.php”);
// Add your data
nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair(“UserEmail”, name.trim()));
nameValuePairs.add(new BasicNameValuePair(“Password”, pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoginTest.this, “error”+e.toString(), Toast.LENGTH_LONG).show();
}
if(buffer.charAt(0)==’Y’)
{
Toast.makeText(LoginTest.this, “login successfull”, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(LoginTest.this, “Invalid Username or password”, Toast.LENGTH_LONG).show();
}
}
}
});
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it’s now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString(“checked”, “yes”);
editor.commit();
}
else
{
editor.putString(“checked”, “no”);
editor.commit();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login_test, menu);
return true;
}
}
yes i thinks so ..!!
i created an database and stored php script in local host “http://127.0.0.1/android/Test/login.php”
Still not working 🙁
Check the reason for force close in the LogCat and paste the reason here. Then only I can say anything about that.
Check the reason for force close in the LogCat and paste the reason here. Then only I can say anything about that and reply.
08-14 17:26:20.342: E/Trace(666): error opening trace file: No such file or directory (2)
08-14 17:26:42.713: E/AndroidRuntime(666): FATAL EXCEPTION: main
08-14 17:26:42.713: E/AndroidRuntime(666): java.lang.NullPointerException
08-14 17:26:42.713: E/AndroidRuntime(666): at com.example.loginform.LoginTest$1.onClick(LoginTest.java:113)
08-14 17:26:42.713: E/AndroidRuntime(666): at android.view.View.performClick(View.java:4084)
08-14 17:26:42.713: E/AndroidRuntime(666): at android.view.View$PerformClick.run(View.java:16966)
08-14 17:26:42.713: E/AndroidRuntime(666): at android.os.Handler.handleCallback(Handler.java:615)
08-14 17:26:42.713: E/AndroidRuntime(666): at android.os.Handler.dispatchMessage(Handler.java:92)
08-14 17:26:42.713: E/AndroidRuntime(666): at android.os.Looper.loop(Looper.java:137)
08-14 17:26:42.713: E/AndroidRuntime(666): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-14 17:26:42.713: E/AndroidRuntime(666): at java.lang.reflect.Method.invokeNative(Native Method)
08-14 17:26:42.713: E/AndroidRuntime(666): at java.lang.reflect.Method.invoke(Method.java:511)
08-14 17:26:42.713: E/AndroidRuntime(666): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-14 17:26:42.713: E/AndroidRuntime(666): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-14 17:26:42.713: E/AndroidRuntime(666): at dalvik.system.NativeStart.main(Native Method)
Hello, Thanks for this great tutorial. I am facing a error in the line if(buffer.charAt(0)==’Y’). I commented this part and went on to run the code, then on clicking login, the toast message gives an error:
org.apache.http.conn.HttpHostConnectException : Connection to http://localhost refused. Can you help me out. Thanks!
Change the host to 10.0.0.2
thankyou sir, changing the host worked and now I am not getting even the buffer.charAt(0) error. But each time I login, it gives invalid username or password. I have entered the username and password combo correctly as in the database. Still getting this error. I tried an alternate entry but the same error. Any solution to this? Thanks again 🙂
This is the problem with your php code. please check it.
please help me, The code run fine on emulator but whenever I run the app in android phone and click on login button, app is getting crashed and stops unexpectedly.
//MainActivity.java
package gps.attendance.android;
//import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
//import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
//import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
//import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
//import android.widget.Toast;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
int ch=0;
Button login;
String name=””,pass=””;
EditText username,password;
TextView tv;
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences ;
List nameValuePairs;
CheckBox check;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString(“username”,”0″ );
String Str_pass = app_preferences.getString(“password”, “0”);
String Str_check = app_preferences.getString(“checked”, “no”);
if(Str_check.equals(“yes”))
{
username.setText(Str_user);
password.setText(Str_pass);
check.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
name = username.getText().toString();
pass = password.getText().toString();
String Str_check2 = app_preferences.getString(“checked”, “no”);
if(Str_check2.equals(“yes”))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString(“username”, name);
editor.putString(“password”, pass);
editor.commit();
}
if(name.equals(“”) || pass.equals(“”))
{
Toast.makeText(MainActivity.this, “Blank Field..Please Enter”, Toast.LENGTH_LONG).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(“http://118.139.185.68/login.php”);
// Add your data
nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair(“UserEmail”, name.trim()));
nameValuePairs.add(new BasicNameValuePair(“Password”, pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, “error”+e.toString(), Toast.LENGTH_LONG).show();
}
if(buffer.charAt(0)==’Y’)
{
Toast.makeText(MainActivity.this, “login successfull”, Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, GpsMain.class));
}
else
{
Toast.makeText(MainActivity.this, “Invalid Username or password”, Toast.LENGTH_LONG).show();
ch++;
if(ch==2)
{
ch=0;
startActivity(new Intent(MainActivity.this, second_step.class));
/* Intent intent = new Intent(this, second_step.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
*/
}
}
}
}
});
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it’s now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString(“checked”, “yes”);
editor.commit();
}
else
{
editor.putString(“checked”, “no”);
editor.commit();
}
}
});
}
public void Move_to_next()
{
// startActivity(new Intent(this, zzz.class));
}
}
_________________________________________________________________
//activity_main.xml
___________________________________________________________________
PLease paste the LogCat error here, then only I can give you the solution.
hi James great tutes…I followed all 3 but still have the same problem in line
httppost = new HttpPost(“http://10.0.0.2/my/login.php”);
It doesn’t connect with the server..
When I run login.php i have the URL on address-bar like this “http://localhost/my/login.php” when i used it instead, android app crashes… What should I do?
Please Help it’s been several days still I can’t figure it out…
thanks for ur tutorial.i need a coding for storing the info in database(Mysql)using PHP.pls post any tutorial or send me coding..my mail id is logupushpa5@gmail.com as soon as possible.
thank u :):)
I have been searching for such kind of tutorials from last one month. Your posts are simple and very easy to understand. Keep posting new posts.
Thank you.
Hey james…Thanks for this tutorials. But there some problem I face that whenever I try to connect its show wrong username and password and on the below of app show “response from our domain_name”.and full code which show if u check from browser. Help me pls..
Did you checked your php code perfectly in a brower by hard coding the values before using it in android?
Pingback: Fix Vertrigo Http Error Windows XP, Vista, 7, 8 [Solved]
Can you please post how to insert user details into mysql database and retrieve the same content in simpleformat
Pingback: 连接到外部数据库-Android应用程序 – FIXBBS
Pingback: Connecting to external database - Android application