How to add online server login and SignUP inside android app using HttpURLconnection source code download .
This tutorial is one of the most demanded tutorial on internet because every android developer who wish to create a fully dynamic android application is mostly used login and registration feature on their android app with server side code included . So here is the complete step by step tutorial for Android Login Registration With PHP MySQL Example Tutorial
Before getting started things you need to prepare :
- Android Studio .
- Emulator or Your android phone ( To test the app ) .
- Online free hosting server that supports PHP .
- Working internet connection in your mobile phone .
- Just read all the below instructions .
List of all activities in this project :
- MainActivity.java .
- LoginActivity.java .
- Profile .
List of all layout files in this project :
- activity_login.xml .
- activity_main.xml .
- activity_profile.xml .
List of all PHP files in this project used for server connectivity :
- dbconfig.php .
- insert-registration-data.php .
- android-login.php .
Please follow the steps to import org.apache.http.legacy library in your project :
1. Open your project’s build.gradle(Module : App) file .
2. Now type useLibrary ‘org.apache.http.legacy’ inside android scope like i did in below screenshot .
Here you Go now this library will be successfully imported in your project . Next step is to start coding .
Android Login Registration With PHP MySQL Example Tutorial .
Code for MainActivity.java file.
package com.android_examples.androidloginregistration_android_examplescom; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; 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.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button register , login ; EditText name, email , password ; String RegisterURL = "http://androidblog.esy.es/login/insert-registration-data.php" ; Boolean CheckEditText ; String Response; HttpResponse response ; String NameHolder, EmailHolder, PasswordHolder ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); register = (Button)findViewById(R.id.button); login = (Button)findViewById(R.id.button2); name = (EditText)findViewById(R.id.name); email = (EditText)findViewById(R.id.email); password = (EditText)findViewById(R.id.password); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GetCheckEditTextIsEmptyOrNot(); if(CheckEditText){ SendDataToServer(NameHolder, EmailHolder, PasswordHolder); } else { Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show(); } } }); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Login_Activity.class); startActivity(intent); } }); } public void GetCheckEditTextIsEmptyOrNot(){ NameHolder = name.getText().toString(); EmailHolder = email.getText().toString(); PasswordHolder = password.getText().toString(); if(TextUtils.isEmpty(NameHolder) || TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)) { CheckEditText = false; } else { CheckEditText = true ; } } public void SendDataToServer(final String name, final String email, final String password){ class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String QuickName = name ; String QuickEmail = email ; String QuickPassword = password; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("name", QuickName)); nameValuePairs.add(new BasicNameValuePair("email", QuickEmail)); nameValuePairs.add(new BasicNameValuePair("password", QuickPassword)); try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(RegisterURL); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); } catch (ClientProtocolException e) { } catch (IOException e) { } return "Data Submit Successfully"; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show(); } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(name, email, password); } }
Code for activity_main.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#03A9F4" android:padding="20dp" tools:context="com.android_examples.androidloginregistration_android_examplescom.MainActivity"> <TextView android:text="Register Here" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" android:textColor="#ffffff" android:textSize="30dp" android:gravity="center" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="30dp" /> <EditText android:layout_width="fill_parent" android:layout_height="50dp" android:inputType="textPersonName" android:ems="10" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:layout_marginTop="30dp" android:id="@+id/name" android:gravity="center" android:background="#fbfefd" android:hint="Enter Name Here" /> <EditText android:layout_width="fill_parent" android:layout_height="50dp" android:inputType="textEmailAddress" android:ems="10" android:layout_marginTop="30dp" android:id="@+id/email" android:gravity="center" android:background="#fbfefd" android:hint="Enter Email Here" android:layout_below="@+id/name" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <EditText android:layout_width="fill_parent" android:inputType="textPassword" android:layout_marginTop="30dp" android:ems="10" android:id="@+id/password" android:gravity="center" android:background="#fbfefd" android:hint="Enter Password Here" android:layout_height="50dp" android:layout_centerVertical="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:text="REGISTER" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/password" android:layout_centerHorizontal="true" android:layout_marginTop="30dp" android:id="@+id/button" /> <Button android:text="Already Register! Login From Here" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/button" android:layout_centerHorizontal="true" android:id="@+id/button2" android:layout_marginTop="10dp"/> </RelativeLayout>
Code for LoginActivity.java file.
package com.android_examples.androidloginregistration_android_examplescom; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; public class Login_Activity extends AppCompatActivity { Button login ; ProgressDialog progressDialog; EditText email, password ; String EmailHolder, PasswordHolder ; boolean CheckEditText ; String ServerLoginURL = "http://androidblog.esy.es/login/android-login.php"; public static final String UserEmail = ""; String finalResult ; HashMap<String,String> hashMap = new HashMap<>(); URL url; String FinalHttpData = ""; BufferedWriter bufferedWriter ; LoginParseClass loginParseClass = new LoginParseClass(); BufferedReader bufferedReader ; OutputStream outputStream ; StringBuilder stringBuilder = new StringBuilder(); String Result ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_); login = (Button)findViewById(R.id.button); email = (EditText) findViewById(R.id.email); password = (EditText)findViewById(R.id.password); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GetCheckEditTextIsEmptyOrNot(); if(CheckEditText){ LoginFunction(EmailHolder,PasswordHolder); } else { Toast.makeText(Login_Activity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show(); } } }); } public void GetCheckEditTextIsEmptyOrNot(){ EmailHolder = email.getText().toString(); PasswordHolder = password.getText().toString(); if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)) { CheckEditText = false; } else { CheckEditText = true ; } } public void LoginFunction(final String email, final String password){ class LoginFunctionClass extends AsyncTask<String,Void,String> { @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(Login_Activity.this,"Loading Data",null,true,true); } @Override protected void onPostExecute(String httpResponseMsg) { super.onPostExecute(httpResponseMsg); progressDialog.dismiss(); if(httpResponseMsg.equalsIgnoreCase("Data Matched")){ finish(); Intent intent = new Intent(Login_Activity.this, profile.class); intent.putExtra(UserEmail,email); startActivity(intent); }else{ Toast.makeText(Login_Activity.this,httpResponseMsg,Toast.LENGTH_LONG).show(); } } @Override protected String doInBackground(String... params) { hashMap.put("email",params[0]); hashMap.put("password",params[1]); finalResult = loginParseClass.postRequest(hashMap); return finalResult; } } LoginFunctionClass loginFunctionClass = new LoginFunctionClass(); loginFunctionClass.execute(email,password); } public class LoginParseClass { public String postRequest(HashMap<String, String> Data) { try { url = new URL(ServerLoginURL); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setReadTimeout(12000); httpURLConnection.setConnectTimeout(12000); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); outputStream = httpURLConnection.getOutputStream(); bufferedWriter = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(FinalDataParse(Data)); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) { bufferedReader = new BufferedReader( new InputStreamReader( httpURLConnection.getInputStream() ) ); FinalHttpData = bufferedReader.readLine(); } else { FinalHttpData = "Something Went Wrong"; } } catch (Exception e) { e.printStackTrace(); } return FinalHttpData; } public String FinalDataParse(HashMap<String, String> hashMap2) throws UnsupportedEncodingException { for(Map.Entry<String, String> map_entry : hashMap2.entrySet()){ stringBuilder.append("&"); stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8")); stringBuilder.append("="); stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8")); } Result = stringBuilder.toString(); return Result ; } } }
Code for activity_login.xml layout file.