Here you will learn to make android login and register system using restful web services in java and mysql.
In this tutorial I will teach you to develop a very simple android app for login and register system. This system sends the login or register request to the restful web service that is running on local server.
If you don’t know how to make restful web services in java and use it in android then I would highly recommend you to first read below tutorials.
Also Read:Â Create Simple Java RESTful Web Services Using Jersey
Also Read:Â Android Restful Web Service Client Example
Android Login and Register Using Restful Web Services (Java + MySQL)
Create Restful Web Service
I have used MySQL database in this web service. Make a login table in database with following schema.
Below is the code for restful web service developed in Java.
DemoService.java
package example; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/DemoService") public class DemoService { final static String url = "jdbc:mysql://localhost:3306/test"; final static String user = "root"; final static String pass = "root"; @POST @Path("/login") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML) public String login(@FormParam("email") String email, @FormParam("password") String password){ String result="false"; try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, pass); PreparedStatement ps = con.prepareStatement("select * from login where email=? and password=?"); ps.setString(1, email); ps.setString(2, password); ResultSet rs = ps.executeQuery(); if(rs.next()){ result = "true"; } con.close(); } catch(Exception e){ e.printStackTrace(); } return result; } @POST @Path("/register") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML) public String register(@FormParam("email") String email, @FormParam("password") String password){ String result="false"; int x = 0; try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, pass); PreparedStatement ps = con.prepareStatement("insert into login(email, password) values(?,?)"); ps.setString(1, email); ps.setString(2, password); x = ps.executeUpdate(); if(x==1){ result = "true"; } con.close(); } catch(Exception e){ e.printStackTrace(); } return result; } }
Create Android Project
Make a new android project with package name com.loginandregister
For sending and fetching data from server I am using Volley library. So add its dependency in build.gradle file.
compile 'com.android.volley:volley:1.0.0'
Read below tutorial if you don’t know how to use volley library.
Also Read:Â Android Volley Tutorial With Example
As we are doing network related operation so add internet access permission in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET"/>
Now create three activities in the project Login, Register and Home. Add following code in the respective files.
Login.java
package com.loginandregister; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class Login extends AppCompatActivity { EditText emailBox, passwordBox; Button loginButton; TextView registerLink; String URL = "http://192.168.1.8/JavaRESTfullWS/DemoService/login"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); emailBox = (EditText)findViewById(R.id.emailBox); passwordBox = (EditText)findViewById(R.id.passwordBox); loginButton = (Button)findViewById(R.id.loginButton); registerLink = (TextView)findViewById(R.id.registerLink); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){ @Override public void onResponse(String s) { if(s.equals("true")){ Toast.makeText(Login.this, "Login Successful", Toast.LENGTH_LONG).show(); startActivity(new Intent(Login.this,Home.class)); } else{ Toast.makeText(Login.this, "Incorrect Details", Toast.LENGTH_LONG).show(); } } },new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(Login.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();; } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("email", emailBox.getText().toString()); parameters.put("password", passwordBox.getText().toString()); return parameters; } }; RequestQueue rQueue = Volley.newRequestQueue(Login.this); rQueue.add(request); } }); registerLink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Login.this, Register.class)); } }); } }
activity_login.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="20dp" android:paddingLeft="20dp" android:paddingRight="20dp" android:paddingTop="20dp" tools:context="com.loginandregister.Login" android:orientation="vertical" android:gravity="center"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email" android:id="@+id/emailBox"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:id="@+id/passwordBox" android:layout_marginTop="10dp"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login" android:id="@+id/loginButton" android:layout_marginTop="10dp"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click here to register" android:textSize="20dp" android:layout_marginTop="15dp" android:gravity="center" android:id="@+id/registerLink" android:textColor="#0D47A1"/> </LinearLayout>
Register.java
package com.loginandregister; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class Register extends AppCompatActivity { EditText emailBox, passwordBox; Button registerButton; TextView loginLink; String URL = "http://192.168.1.8/JavaRESTfullWS/DemoService/register"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); emailBox = (EditText)findViewById(R.id.emailBox); passwordBox = (EditText)findViewById(R.id.passwordBox); registerButton = (Button)findViewById(R.id.registerButton); loginLink = (TextView)findViewById(R.id.loginLink); registerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){ @Override public void onResponse(String s) { if(s.equals("true")){ Toast.makeText(Register.this, "Registration Successful", Toast.LENGTH_LONG).show(); } else{ Toast.makeText(Register.this, "Can't Register", Toast.LENGTH_LONG).show(); } } },new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(Register.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();; } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("email", emailBox.getText().toString()); parameters.put("password", passwordBox.getText().toString()); return parameters; } }; RequestQueue rQueue = Volley.newRequestQueue(Register.this); rQueue.add(request); } }); loginLink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Register.this, Login.class)); } }); } }
activity_register.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.loginandregister.Register" android:orientation="vertical" android:gravity="center"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email" android:id="@+id/emailBox"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:id="@+id/passwordBox" android:layout_marginTop="10dp"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register" android:id="@+id/registerButton" android:layout_marginTop="10dp"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click here to login" android:textSize="20dp" android:layout_marginTop="15dp" android:gravity="center" android:id="@+id/loginLink" android:textColor="#0D47A1"/> </LinearLayout>
Home.java
package com.loginandregister; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class Home extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); } }
activity_home.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="20dp" android:paddingLeft="20dp" android:paddingRight="20dp" android:paddingTop="20dp" tools:context="com.loginandregister.Home" android:gravity="center"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="- Welcome -" android:textSize="30dp" android:gravity="center"/> </LinearLayout>
Make sure the web service is already running on the server. Also change the IP 192.168.1.8 in the URL with the IPv4 of your local system. You can find the IPv4 in windows by typing ipconfig command in command prompt.
Finally run and test the project.
Screenshots
The whole code is very simple and self-explanatory. If still you are facing any problem then feel free to ask in comment section.
Hay,
The Above code are not able to connect to database. It Show com.android.volly.NoConnectionError java.net.connectException failed to connect to 127.0.0.1. It Show exception in emulator with Toast.
Replace 127.0.0.1 with the ipv4 of your computer. Also add the port number after the ip where the web service is running. The url will look like this http://192.168.1.8:8080/JavaRESTfullWS/DemoService/register. This is just an example, in your case the ip and port number can be different.
Estou com erro conexao ver se esta certo?
*Login.java
String URL = “http:///10.105.75.149:8080/JavaRESTfullWS/DemoService/login”;
*DemoService.java
final static String url = “jdbc:mysql://localhost:8080/webservice”;
webservice é o nome do meu banco
Can you write an example for CRUD operation please,..It will be helpful…
I am getting error: BasicNetwork.performRequest: Unexpected response code 404
Checked with all solution
my URL: 10.0.0.155/webservice/Service/login
In your class demo.java i seen user and password with plain text. It’s so riskcan buddy. You can encryption them. Willy this unrecommended .just comment to get good result maybe in the future.
it will helpfull if you share all the source code
can you please send me full code for the above example ..I getting error in webservice page.
I am getting error stating “com.android.volly.ServerError”
can you please explain me on how to set the string URL
i’m getting error as com.android.volley.NoConnectioError.
i dint understand how to give the url please help me in these two cases
can you please help me out in creating a web service for a android project.
I will be so graceful.
thanks in advance
this command is not working in android studio 3.0.1 Toast.makeText(”Register.this”, “Registration Successful”, Toast.LENGTH_LONG).show();
is this can be replaced by
toast.makeText(getapplicationcontext, “Registration Successful”, Toast.LENGTH_LONG).show();
reply fast
first thanks for this project
please put web.xml file for this project in site
What do i need to change if I want to consume and produce Json instead.
I have used my IP address of my PC in the Url = http://[my ip address]:8081/MyFoodies/LoginRegisterWebService/login
But still its throwing ‘Volley – time out error ‘
> Switched off my Firewall settings
> Tried this IP too 10.0.2.2
> Tried Port no 8080, 8082, 8500
I am using the ‘Remix OS Player’ emulator in my android studio.
Set a break point in following step, but its not going inside ‘onResponse(String s)’ method …any idea what could be the problem ?
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener()
Hello Neeraj,
I have seen your above example and i am 99% sure that i have done all perfectly but i am getting problem in one place may be you have faced it so plz help me in solving this.
(I am using POST method).
The problem is when i am testing Rest api using Postman Rest Client in browser the data is inserting properly and getting proper json response and also when i execute the same url from my Android Phone’s Chrome Browser it is working perfectly. But when i am setting value from Android app i am getting “null” (in Eclipse Log cat) and not inserting that value in MySql database.
Neeraj i solved my problem.
no need to answer know. 🙂
Hey, where do you created the DemoService.java file
Please help…It showing Timeout error
Hi,
Could anyone tell me , from where is the URL present in Demoservice.java taken ?
Hello,
Program is running but I want the program to pull data in JSON format. How can I do this in ANDROID STUDIO program?
Hey can you pls tell me where we have to create the DemoService class file. I have created in spring suite tool
i try this exemple and i get timeout error. can anyone help me please?
This example does not work. Can you throw away the project codes
If you desire to improve your knowledge only keep visiting this web site and
be updated with the most recent gossip posed here.
StringRequest request = new StringRequest(DownloadManager.Request.Method.POST, URL, new Response.Listener()
Method line cannot be resolved plz help I am using this code on my project
Hi, Thank you so much for your generosity. I have however failed to get it working so far. I get a server timeout error. Two days on this and I haven’t moved a foot.
Thank you a lot for your helpful tutorial
thank you very much….
sir when i try to login with my own API it seems incorrect details every time.please reply
can you please using instead of android application an html pages ?
sir when i try to login with my own API it seems incorrect details every time.please reply
Hey, can you pls explain where we have to make DemoService.java file and which dependencies we have to use for that?
Pls reply.