DEVELOPMENT

A simple authenticating System in android....

For the purpose, three activities are essential -

1. Activity from where user can get login(MainActivity).
2. User's Registration on the server will be performed by register activity(Register).
3. Welcome activity for login users(home).

login android register android home screen android

The Table

I've used only three columns....insake to make it less complex...

login android

build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.tut.tut_7_3"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.tut.tut_7_3" >

 <uses-permission android:name="android.permission.INTERNET" />

 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name=".MainActivity"
 android:label="@string/app_name"
 android:noHistory="true">
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <activity
 android:name=".home"
 android:label="@string/title_activity_home"
 android:noHistory="true">
 <intent-filter>
 <action android:name="com.example.tut.tut_7_3.home" />

 <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>
 </activity>
 <activity
 android:name=".Register"
 android:label="@string/title_activity_register" >
 <intent-filter>
 <action android:name="com.example.tut.tut_7_3.Register" />

 <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>
 </activity>
 </application>

</manifest>
MainActivity.java
package com.example.tut.tut_7_3;


import java.io.IOException;
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.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.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

	private EditText pnumber;
	private EditText password;
	private Button btn;
	private ProgressBar pb;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		SharedPreferences sp = getSharedPreferences("com.example.tut.tut_7_3.USER_ID", Context.MODE_PRIVATE);
		 if (sp.contains("userid"))
	      {
			 startActivity(new Intent("com.example.tut.tut_7_3.home"));

	      }

		pnumber=(EditText)findViewById(R.id.Pnumber);
		password=(EditText)findViewById(R.id.Password);
		pb=(ProgressBar)findViewById(R.id.progressBar1);
		pb.setVisibility(View.GONE);

	}

	public void onClickReg(View v) {
		startActivity(new Intent("com.example.tut.tut_7_3.Register"));
	}

	public void onClick(View v) {

		if(pnumber.getText().toString().length()<1 || password.getText().toString().length()<1){
			Toast.makeText(this, "Please, Fill the Fields", Toast.LENGTH_LONG).show();
		}else{
			pb.setVisibility(View.VISIBLE);
			new NewAsyncTask().execute(pnumber.getText().toString(), password.getText().toString());
		}
	}

	private class NewAsyncTask extends AsyncTask<String, Integer, String>{

		String restext="Connection error!!!";
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			restext=postData(params[0],params[1]);
			return restext;
		}
		public void onPostExecute(String result){
			pb.setVisibility(View.GONE);
			Toast.makeText(getApplicationContext(), restext, Toast.LENGTH_LONG).show();
		}
		protected void onProgressUpdate(Integer... progress){
			pb.setProgress(progress[0]);
		}

		public String postData(String no,String pass) {


			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("/checklog.php"); //your url

			try {

				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("pnumber", no));
				nameValuePairs.add(new BasicNameValuePair("password", pass));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				restext = EntityUtils.toString(entity);
				String mod=restext.substring(0,1);

				if (mod.equals("1"))
				{	SharedPreferences sp = getSharedPreferences("com.example.tut.tut_7_3.USER_ID", Context.MODE_PRIVATE);
					SharedPreferences.Editor editor = sp .edit();
					editor.putString("uid",no);
					editor.commit();
					restext="redirecting...";
					startActivity(new Intent("com.example.tut.tut_7_3.home"));
				}
				else if(mod.equals("0"))
				{
					restext="Username or Password was wrong.";
				}
			}
			catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}

			return restext;
		}
	}
}
Register.java
    package com.example.tut.tut_7_3;


        import java.io.IOException;
        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.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.app.Activity;
        import android.content.Intent;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.EditText;
        import android.widget.ProgressBar;
        import android.widget.Toast;

public class Register extends Activity implements OnClickListener{

    private EditText pnumber;
    private EditText password;
    private ProgressBar pb;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);

        pnumber=(EditText)findViewById(R.id.Pnumber);
        password=(EditText)findViewById(R.id.Password);
        pb=(ProgressBar)findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);
    }
    public void onClickLogin(View v) {
        startActivity(new Intent(this, MainActivity.class));

    }
    @Override
        public void onClick(View v) {

        if(pnumber.getText().toString().length()<1 || password.getText().toString().length()<1){
                     Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
        }else{
            pb.setVisibility(View.VISIBLE);
            new MyAsyncTask().execute(pnumber.getText().toString(),password.getText().toString());
        }
    }

    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

        String responseText="Connection error!!!";
        @Override
        protected Double doInBackground(String... params) {
            postData(params[0],params[1]);
            return null;
        }

        protected void onPostExecute(Double result){
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), responseText, Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }

        public void postData(String no,String pass) {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("/register.php");

            try {

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("pnumber", no));
                nameValuePairs.add(new BasicNameValuePair("password", pass));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                responseText = EntityUtils.toString(entity);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
        }

    }
} 
home.java
package com.example.tut.tut_7_3;


import android.app.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;


public class home extends Activity {

    private TextView disp;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        disp=(TextView)findViewById(R.id.disp_home);
        disp.setText("Home");

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_home, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.logout:
                SharedPreferences sharedPref = this.getSharedPreferences(
                        "com.example.tut.tut_7_3.USER_ID", Context.MODE_PRIVATE);
                sharedPref.edit().remove("uid").commit();
                startActivity(new Intent(this, MainActivity.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >
 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Phone no." />
 <EditText
 android:id="@+id/Pnumber"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"/>
 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Password" />
 <EditText
 android:id="@+id/Password"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"/>
 <Button android:id="@+id/clogin"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="login"
 android:onClick="onClick"/>
 <Button android:id="@+id/creg"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Get register"
 android:onClick="onClickReg"/>
 <ProgressBar
 android:id="@+id/progressBar1"
 style="?android:attr/progressBarStyleLarge"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true" />
 </LinearLayout>

res/layout/activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >
 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Phone ni." />
 <EditText
 android:id="@+id/Pnumber"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"/>
 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Password" />
 <EditText
 android:id="@+id/Password"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"/>
 <Button android:id="@+id/greg"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Register me"
 android:onClick="onClick"/>
 <Button
 android:id="@+id/glog"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Already registred. Login Me!"
 android:onClick="onClickLogin"
 />
 <ProgressBar
 android:id="@+id/progressBar1"
 style="?android:attr/progressBarStyleLarge"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true" />
</LinearLayout>
res/layout/activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >
 <TextView
 android:id="@+id/disp_home"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Home" />

</LinearLayout>

Place both the below php file checklog.php and register.php on your server...

register.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") 
{

$pnumber=$_POST["pnumber"];
$password=$_POST["password"];
$id=rand(1000,99999);

$conn=mysql_connect("","","") or die("ERROR");
$db=mysql_select_db("",$conn) or die("ERROR");
$d=0;
$result = mysql_query("SELECT * FROM user",$conn);
while($row = mysql_fetch_array($result)) 
{
 
 if($row['pnumber']==$pnumber) 
 {
 echo "Sorry,You are already registered"; 
 $d=1;
 }
} 

if($d==0)
{
$sql="insert into user(pid,pnumber,password) values (\"$id\",\"$pnumber\",\"$password\")";
$res=mysql_query($sql,$conn) or die("ERROR");
if($res)
{
 echo "You are now registered";
 
} 
else
{
 echo "ERROR";
}

}
}
?>
checklog.php
<?php 
$email=$_POST['pnumber'];
$pass=$_POST['password'];
$c=0;

$conn=mysql_connect("","","") or die("ERROR");
$db=mysql_select_db("",$conn) or die("ERROR");

$result = mysql_query("SELECT * FROM user",$conn);

 while($row = mysql_fetch_array($result)) {
 if($row['pnumber']==$email && $row['password']==$pass)
 { 
 $c=1;
 
 }
 }
if($c==1)
{
 
 echo 1;
}
else
{
 echo 0;
}
?>


Leave a Comment  
Download Code(34)





All rights reserved, the content is copyrighted to the author.

RELATED POST