Saturday, 16 December 2017

Calculus112: Android App Development Day 1


What you will learn in this tutorial include
1. Splash Screen
2. Android NotificationManager
3. Android Thread
4. ConnectivityManager
5. Vibrator
6. Alarm Manager
7. Android SQL Database


Hello android developers. Today I’m going to be sharing the source code of a project named calculus112. Calculus112 is a college base mathematics app which includes content such as function, limits, differentiation and integration. In this application, we shall take advantage of the android studio material design as well as advance technology (android classes and layout) of the android system. This application is base on the book The Android Manager, the wisdom to advance android development. You can get the book from http://laprice.com.ng or simply navigate to the left top corner of the screen and click on the download button. In this tutorial, I’m going to combine several android managers from the book, include latest android studio material design and teach you how to add admob to your application. By the way, admob is a way to monetize your application. What that means is that, it enables you to show up advert know as ads. When user clicks on those ads, you get paid. You can monitor your money from your Google console dash board. Base on the facts that this is a huge project and a lot will be taught and learn, I decided to divide it into several days of learning. Day one will focus on user registration and login. Below are the screen shot of the application.




                             





                       




As explain earlier, day one will be focusing on user registration and login. We are going to build a user registration and login system using SQL database which android provide for us. An advance way of using android SQL database is explain in the book on chapter 15 of the android manager know as SQLManager. Android uses the SQLite database system to collect large amount of information and query it efficiently. In this tutorial, you will be able to learn how to create, delete, execute SQL commands and perform other relational database management tasks. If you recalled correctly, we make mention of google admob. The truth is that, admob uses internet connectivity to display ads. Therefore we are going to use a manager know as ConnectivityManager to detect if internet connection is available or not. ConnectivityManager has been explain in the book get yours at http://laprice.com.ng The ConnectivityManager class is responsible for detecting if internet connection is available or unavailable. Therefore, users will not only be prompt to check if user name and password are correct but also check if connections are available.

Below is the screen shot






To kick start this project, open your android studio. Navigate to File---->new-----> new project. Give the application name as Calculus112 and include your company name. My advice for you is to choose API 19, the kitkat version.

Choose Navigation Drawer Activity.



 Open up your AndroidManifest.xml and populate it with the following

AndroidManifest.xml  
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="calculus112.gworld.unycorp.calculus112">

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

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

    <uses-permission android:name="android.net.conn.CONNECTIVITY_CHANGE"/>

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

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

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

    <application

        android:allowBackup="true"

        android:icon="@drawable/mymth"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity

            android:screenOrientation="portrait"

            android:name=".MainActivity"

            android:label="@string/app_name"

            android:theme="@style/AppTheme.NoActionBar">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />



                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

<activity android:name=".Contents"

    android:screenOrientation="portrait">

</activity>

        <activity android:name=".Function"

            android:screenOrientation="portrait"

            android:label="Function">



        </activity>

        <activity android:name=".Limit"

            android:screenOrientation="portrait"

            android:label="Limit">



        </activity>

        <activity android:name=".Differentiation"

            android:screenOrientation="portrait"

            android:label="Differentiation">



        </activity>

        <activity android:name=".Integration"

            android:screenOrientation="portrait"

            android:label="Integration">



        </activity>

        <activity android:name=".RegistrationPage"

            android:screenOrientation="portrait"

            android:label="Registration">



        </activity>

        <activity android:name=".Login"

            android:screenOrientation="portrait">

        </activity>

<activity android:name=".AppDescription"

    android:screenOrientation="portrait"

    android:label="App Description">

</activity>

        <activity android:name=".BlogView"

            android:screenOrientation="portrait"

            android:label="unycorp.blogspot.com">

        </activity>

        <activity android:name=".GalleryActivity"

            android:theme="@style/AppTheme.NoActionBar"

            android:label="@string/app_name"

            android:screenOrientation="portrait">

        </activity>



        <receiver android:name=".AlarmReceiver"> </receiver>



        <activity

            android:name="com.google.android.gms.ads.AdActivity"

            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"

            android:theme="@android:style/Theme.Translucent" />

    </application>



</manifest>
 
I know there is a lot to take in right now. Here is the basics of a blue print of what we are trying to achieve.






When the application runs for the first time, we are presented with a splash screen, after some few seconds, the LoginActivity is presented. A TextView is use to navigate to the RegistrationActivity. When the user finishes the registration process, it navigates him to the LoginActivity where he will be asking to input his email and password. If the email and password correspond to what was stored in the database but no internet connectivity is available the user will be ask to switch on the device internet connection. If the email and password correspond with what was stored in the database and internet connections are available then the user should be allow to login to GalleryActivity. The GalleryActivity contains the navigation drawer. More about the Gallery Activity will be explain in another tutorial. When your application is run for the first time, the MainActivity.java and activity_main is what is presented on the screen. We shall turn our MainActivity to the splash screen activity. Therefore change the setContentView(R.layout.activity_main) to setContentView(R.layout.activity_splash). Populate your MainActivity with the following statement.
The main purpose of the MainActivity.java is to show a Splash Screen for 4 seconds 
before navigating to the LoginActivity. Also, this class is responsible for showing up notification 
everyday at 18:00. Therefore, populate it with the following statement
MainActivity.java
package mth112.gworld.unycorp.mth112;





import android.app.AlarmManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.widget.TextView;



import java.util.Calendar;



public class MainActivity extends AppCompatActivity {

    AlarmManager alarm;

    Intent i;

    PendingIntent pi;

    TextView fb,tw,bl,gm;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash);

fb = (TextView)findViewById(R.id.splashtxt1);



        tw = (TextView)findViewById(R.id.splashtxt2);

        bl = (TextView)findViewById(R.id.splashtxt3);

        gm = (TextView)findViewById(R.id.splashtxt4);



        fb.setText("Be my friend on facebook at"+ "\n"+

        "facebook.cm/udoh unyime");

        tw.setText("following me on twitter at"+ "\n"+

                "twitter.com/udoh unyime");

        bl.setText("View my blog page at"+ "\n"+

                "unycorp.blogspot.com");

        gm.setText("Have any questions? Send me email"+ "\n"+

                "udohunyime0@gmail.com");



        alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

        i = new Intent(getApplicationContext(), AlarmReceiver.class);

        pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar cal = Calendar.getInstance();

        cal.setTimeInMillis(System.currentTimeMillis());

        cal.set(Calendar.HOUR_OF_DAY, 18);

        cal.set(Calendar.MINUTE, 00);

        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);





        Thread background = new Thread() {

            public void run() {

                try {

                    // Thread will sleep for 5 seconds

                    sleep(4000);



                    // After 5 seconds redirect to another intent

                    Intent i=new Intent(getApplicationContext(),Login.class);

                    startActivity(i);



                    //Remove activity

                    finish();

                } catch (Exception e) {

                }

            }

        };

        // start thread

        background.start();

    }

}
 
Create a layout and named it activity_splash. Under activity_splash, populate it with the following statement.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="@drawable/bulblight">



    <ImageView

        android:id="@+id/facebooksplashimage"      

        android:layout_width="70dp"

        android:layout_height="70dp"

        app:srcCompat="@mipmap/fb"

        android:layout_marginTop="64dp"

        android:layout_marginLeft="23dp"

        android:layout_marginStart="23dp"

        android:layout_alignParentTop="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true" />



    <TextView

        android:id="@+id/splashtxt1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignLeft="@+id/splashtxt2"

        android:layout_alignStart="@+id/splashtxt2"

        android:layout_alignTop="@+id/facebooksplashimage"

        android:text="TextView"

        android:textColor="@android:color/background_dark"

        android:textSize="16dp" />



    <ImageView

        android:id="@+id/twitterplashimage"

        android:layout_width="80dp"

        android:layout_height="80dp"

        app:srcCompat="@mipmap/tw"

        android:layout_below="@+id/facebooksplashimage"

        android:layout_alignLeft="@+id/facebooksplashimage"

        android:layout_alignStart="@+id/facebooksplashimage"

        android:layout_marginTop="13dp" />



    <TextView

        android:id="@+id/splashtxt2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignTop="@+id/twitterplashimage"

        android:layout_marginLeft="10dp"

        android:layout_marginStart="10dp"

        android:layout_toEndOf="@+id/twitterplashimage"

        android:layout_toRightOf="@+id/twitterplashimage"

        android:text="TextView"

        android:textColor="@android:color/black"

        android:textSize="16dp" />



    <ImageView

        android:id="@+id/blogsplash"

        android:layout_width="70dp"

        android:layout_height="70dp"

        app:srcCompat="@mipmap/bg"

        android:layout_below="@+id/twitterplashimage"

        android:layout_alignLeft="@+id/twitterplashimage"

        android:layout_alignStart="@+id/twitterplashimage" />



    <TextView

        android:id="@+id/splashtxt3"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignLeft="@+id/splashtxt2"

        android:layout_alignStart="@+id/splashtxt2"

        android:layout_alignTop="@+id/blogsplash"

        android:text="TextView"

        android:textColor="@android:color/black"

        android:textSize="16dp" />



    <ImageView

        android:id="@+id/gmailsplashimage"

        android:layout_width="70dp"

        android:layout_height="70dp"

        app:srcCompat="@drawable/gmailicon"

        android:layout_below="@+id/splashtxt3"

        android:layout_alignLeft="@+id/blogsplash"

        android:layout_alignStart="@+id/blogsplash"

        android:layout_marginTop="59dp" />



    <TextView

        android:id="@+id/splashtxt4"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignLeft="@+id/splashtxt3"

        android:layout_alignStart="@+id/splashtxt3"

        android:layout_alignTop="@+id/gmailsplashimage"

        android:text="TextView"

        android:textColor="@android:color/black"

        android:textSize="16dp" />



    <TextView

        android:id="@+id/splashtxtfirst"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Built for android 4.4 or higher"

        android:textColor="@android:color/holo_red_dark"

        android:textSize="16dp"

        tools:text="Built for android 4.4 or higher"

        android:layout_alignParentBottom="true"

        android:layout_alignLeft="@+id/gmailsplashimage"

        android:layout_alignStart="@+id/gmailsplashimage"

        android:layout_marginLeft="58dp"

        android:layout_marginStart="58dp" />

</RelativeLayout>

Create a new class, name the class AlarmReceiver.java. The purpose of the AlarmReceiver.java is to display the notification message and vibrate the device everyday at 18:00. Take note that it extends a BroadcastReceiver class. Therefore, populate it with the following statements.

AlarmReceiver.java
import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Vibrator;

import android.widget.Toast;



import static android.content.Context.NOTIFICATION_SERVICE;



public class AlarmReceiver extends BroadcastReceiver{

    NotificationManager nm;

    Notification notification;

    int notificationID = 1;

    @Override

    public void onReceive(Context context, Intent intent) {

        Vibrator vibrator = (Vibrator)context.getSystemService(context.VIBRATOR_SERVICE);

        vibrator.vibrate(2000);

        Toast.makeText(context, "MTH112, says HI", Toast.LENGTH_LONG).show();

         intent = new Intent(context, Login.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        nm = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);



        notification = new Notification.Builder(context)

                .setContentTitle("Go ahead, try it out and clear your doubt")

                .setContentText("Don't give up, don't get tire. Mathematics is everyday")

                .setSmallIcon(R.drawable.bulblight)

                .setContentIntent(pendingIntent)

                .setAutoCancel(true)

                .build();



        nm.notify(notificationID, notification);







    }

}
Note: More about AlarmManager, AlarmReceiver, intent, pending intent and broadcast reciver is explain in the book. Get yours at http://www.laprice.com.ng

Create a new class and name it LoginActivity. Populate it with the following statement
public class Login extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.login_activity);
}
}

Create a layout and name it login_activity. Populate it with the following statement

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="@drawable/regimage">
</RelativeLayout>

It is better for us to understand what we have done. Here is the summary
1. In the MainActivity.java, we change the setContentView(R.layout.activity_main) to setContentView(R.layout.splash_activity).
2. The MainActivity.java enables us to set a repeating alarm everyday at 18:00 through the help of the AlarmManager and also enable us to display the splash screen for 4 seconds through the use of thread. The alarm which we are setting will pop up in the form of notification appearing at the status bar on the screen.
3. The AlarmReceiver.java class enables to set the notification which will be appearing at the status bar.
4. After the Splash screen has being display for 4 seconds, we navigate to the LoginActivity

Create a new class and name it DBAdapter.java. The DBAdapter is a helper class created to save data in android SQL database. We shall be saving just the email and password which will be treated as String type. Popularize it with the following

DBAdapter.java
import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.util.Log;

public class DBAdapter {

    static final String KEY_ROWID = "_id";

    static final String KEY_NAME = "name";

    static final String KEY_EMAIL = "email";

    static final String TAG = "DBAdapter";

    static final String DATABASE_NAME = "MyDB";

    static final String DATABASE_TABLE = "contacts";

    static final int DATABASE_VERSION = 1;

    static final String DATABASE_CREATE =

"create table contacts (_id integer primary key autoincrement, "

            + "name text not null, email text not null);";

    final Context context;

    DatabaseHelper DBHelper;

    SQLiteDatabase db;

    public DBAdapter(Context ctx)

    {

        this.context = ctx;

        DBHelper = new DatabaseHelper(context);

    }

    private static class DatabaseHelper extends SQLiteOpenHelper

    {

        DatabaseHelper(Context context)

        {

            super(context, DATABASE_NAME, null, DATABASE_VERSION);

        }

        @Override

        public void onCreate(SQLiteDatabase db)

        {

            try {

                db.execSQL(DATABASE_CREATE);

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

        @Override

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

        {

            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "

            + newVersion + ", which will destroy all old data");

            db.execSQL("DROP TABLE IF EXISTS contacts");

            onCreate(db);

        }

    }

    //---opens the database---

    public DBAdapter open() throws SQLException

    {

        db = DBHelper.getWritableDatabase();

        return this;

    }

    //---closes the database---

    public void close()

    {

        DBHelper.close();

    }

    //---insert a contact into the database---

    public long insertContact(String name, String email)

    {

        ContentValues initialValues = new ContentValues();

        initialValues.put(KEY_NAME, name);

        initialValues.put(KEY_EMAIL, email);

        return db.insert(DATABASE_TABLE, null, initialValues);

    }

    //---deletes a particular contact---

    public boolean deleteContact(long rowId)

    {

        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;

    }

    //---retrieves all the contacts---

    public Cursor getAllContacts()

    {

        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,

                KEY_EMAIL}, null, null, null, null, null);

    }

    //---retrieves a particular contact---

    public Cursor getContact(long rowId) throws SQLException

    {

        Cursor mCursor =

                db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,

                        KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,

            null, null, null, null);

        if (mCursor != null) {

            mCursor.moveToFirst();

        }

        return mCursor;

    }

    //---updates a contact---

    public boolean updateContact(long rowId, String name, String email)

    {

        ContentValues args = new ContentValues();

        args.put(KEY_NAME, name);

        args.put(KEY_EMAIL, email);

        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;

    }

}

Note: More example regarding DBAdapter and Helper is explain in the book get yours at http://www.laprice.com.ng.

Create a new class and name it RegistrationPage. The registration activity is use to register your email and password to the DBAdapter. Other fields such as name, phone number, age and address is included in the registration page but will not be stored in the database. Only your email and password will be stored as string type in the database. Populate it with the following statement

RegistrationPage.java
import android.app.Activity;

import android.app.Dialog;

import android.content.Intent;

import android.os.Bundle;

import android.support.design.widget.Snackbar;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;



/**

 * Created by user on 14-Nov-17.

 */



public class RegistrationPage extends Activity {

    EditText edname, edemail, edpassword, ednumber, edage, edaddress;

    Button create, update;

    private DBAdapter db;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.registration_page);



        create = (Button)findViewById(R.id.createAccount);

        update = (Button)findViewById(R.id.update);

edname = (EditText)findViewById(R.id.reg1);

        edemail = (EditText)findViewById(R.id.reg2);

        edpassword = (EditText)findViewById(R.id.reg3);

        ednumber = (EditText)findViewById(R.id.reg4);

        edage = (EditText)findViewById(R.id.reg5);

        edaddress = (EditText)findViewById(R.id.reg6);

         db = new DBAdapter(this);





        create.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                String name = edname.getText().toString();

                String email = edemail.getText().toString();

                String password = edpassword.getText().toString();

                String number = (ednumber.getText().toString());

                int age = Integer.parseInt(edage.getText().toString());

                String address = edaddress.getText().toString();

if(name.equals("") || email.equals("")|| password.equals("")||number.equals("") ||

        address.equals("")){

    Snackbar.make(v, "Please Check again...", Snackbar.LENGTH_LONG).show();

        }

        else {

    db.open();

    db.insertContact(email, password);

    Toast.makeText(getApplicationContext(), "Account Successfully Created", Toast.LENGTH_LONG).show();

//    Snackbar.make(v, "Account succesfully created", Snackbar.LENGTH_LONG).show();

    Intent i = new Intent(getApplicationContext(), Login.class);

    startActivity(i);

    finish();

    db.close();

}

            }

        });

        update.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                db.open();

                if (db.deleteContact(1))

                    Toast.makeText(getApplicationContext(), "Delete successful.", Toast.LENGTH_LONG).show();

                else

                    Toast.makeText(getApplicationContext(), "Delete fails.", Toast.LENGTH_LONG).show();

    Toast.makeText(getApplicationContext(), "Create Another Account To Solve The Problem or "+"\n"+

            "1. Navigate to settings"+"\n"+

            "2. Click Application Manager"+"\n"+

            "3. Click on MTH112"+"\n"+

            "4. Click on clear data", Toast.LENGTH_LONG).show();



                db.close();



            }

        });



}

}
Create a new layout and name it registration_page.xml. Populate it with the following

Registration_page.xml
<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    xmlns:ads="http://schemas.android.com/apk/res-auto"

    android:background="@drawable/loginimage">



    <TableRow

        android:layout_marginTop="35dp">



        <TextView

            android:id="@+id/textView3"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Name:"

            android:textColor="@color/cardview_light_background" />



        <EditText

            android:id="@+id/reg1"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:ems="10"

            android:hint="Surname first others"

            android:inputType="textPersonName"
           
android:textColor="@color/cardview_light_background"             android:textColorHint="@android:color/holo_blue_bright" />     </TableRow>     <TableRow android:layout_marginTop="10dp">         <TextView             android:textColor="@color/cardview_light_background"             android:id="@+id/textView5"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="Email:" />         <EditText             android:textColor="@color/cardview_light_background"             android:textColorHint="@android:color/holo_blue_bright"             android:id="@+id/reg2"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:ems="10"             android:hint="example@gmail.com"             android:inputType="textEmailAddress"/> </TableRow>     <TableRow android:layout_marginTop="10dp">         <TextView             android:layout_marginTop="10dp"             android:id="@+id/textView7"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="Password"             android:textColor="@color/cardview_light_background" />         <EditText             android:id="@+id/reg3"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginTop="18dp"             android:ems="10"             android:hint="ABC123"             android:inputType="textPassword"             android:textColor="@color/cardview_light_background"             android:textColorHint="@android:color/holo_blue_bright" />     </TableRow>     <TableRow android:layout_marginTop="10dp">     <TextView         android:textColor="@color/cardview_light_background"         android:id="@+id/regnum"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Phone Number:"/>         <EditText             android:textColor="@color/cardview_light_background"             android:textColorHint="@android:color/holo_blue_bright"             android:id="@+id/reg4"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:ems="10"             android:hint="0123456789"             android:inputType="text" />     </TableRow>     <TableRow android:layout_marginTop="10dp">     <TextView         android:textColor="@color/cardview_light_background"         android:id="@+id/textView10"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Age:" />         <EditText             android:textColor="@color/cardview_light_background"             android:textColorHint="@android:color/holo_blue_bright"             android:id="@+id/reg5"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:ems="10"             android:hint="14"             android:inputType="number" />     </TableRow>     <TableRow android:layout_marginTop="10dp">     <TextView         android:textColor="@color/cardview_light_background"         android:id="@+id/textView13"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Address"/>         <EditText             android:id="@+id/reg6"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:ems="10"             android:hint="university of benin, hall 4"             android:inputType="textPostalAddress"             android:textColor="@color/cardview_light_background"             android:textColorHint="@android:color/holo_blue_bright" />     </TableRow>     <TableRow         android:layout_marginTop="20dp">         <Button             android:id="@+id/createAccount"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:background="@color/colorPrimary"             android:text="Create Account"             android:textColor="@color/cardview_light_background" />         <Button             android:layout_marginLeft="50dp"             android:id="@+id/update"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:background="@color/colorPrimary"             android:text="Delete Account"             android:textColor="@color/cardview_light_background" />     </TableRow> </TableLayout>


Recall the LoginActivity.java. The LoginActivity enable user to login to the GalleryActivity. It check if the registered email and password correspond with the email and password stored in the SQL database and also check if internet connectivity is activated. Populate it with the following statement

LoginActivity.java
public class Login extends Activity {

TextView tvreg;

    EditText eduser, edpassword;

    Button login;

    private DBAdapter db;

    AdView av;

Cursor c;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.login_activity);



        tvreg = (TextView)findViewById(R.id.regtext);

        eduser = (EditText)findViewById(R.id.log1);

        edpassword = (EditText)findViewById(R.id.log2);

        login = (Button)findViewById(R.id.logbut);

        av = (AdView) findViewById(R.id.loginAds);

        AdRequest adRequest = new AdRequest.Builder()

                .build();

        av.loadAd(adRequest);

        db = new DBAdapter(this);

        db = db.open();

         c = db.getAllContacts();



        login.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                ConnectivityManager connect= (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

                if (c.moveToFirst()) {

                    do {

                            String email = eduser.getText().toString();

                            String password = edpassword.getText().toString();

                        String storeEmail = c.getString(1);

                        String storePassword = c.getString(2);

                            if (!password.equals(storePassword) || !email.equals(storeEmail)) {

                               // Snackbar.make(v, "Something is wrong, please check", Snackbar.LENGTH_LONG).show();

                                Toast.makeText(getApplicationContext(), "something is wrong, please check", Toast.LENGTH_SHORT).show();

                            }

                        else if(connect.getNetworkInfo(0).getState()!= NetworkInfo.State.CONNECTED) {

                                //Snackbar.make(v, "Internet Connectivity Unavailable", Snackbar.LENGTH_LONG).show();

                                Toast.makeText(getApplicationContext(), "Internet Connectivity Unavailable", Toast.LENGTH_LONG).show();

                        }

                          else {

                                Intent i = new Intent(getApplicationContext(), GalleryActivity.class);

                                startActivity(i);

                                finish();

                               // Snackbar.make(v, "Login please wait...", Snackbar.LENGTH_LONG).show();

                                Toast.makeText(getApplicationContext(), "Login please wait..", Toast.LENGTH_LONG).show();

                             }

                        //Toast.makeText(getApplicationContext(), "trying " + c.getString(2), Toast.LENGTH_LONG).show();



                    } while (c.moveToNext());

                }

                db.close();





            }

        });



        tvreg.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(), RegistrationPage.class);

                startActivity(i);

            }

        });

    }

}
Populate the layout of the LoginActivity with the following statement
login_activity
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:ads="http://schemas.android.com/apk/res-auto"

    android:background="@drawable/regimage"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <com.google.android.gms.ads.AdView

        android:id="@+id/loginAds"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        ads:adSize="BANNER"

        ads:adUnitId="ca-app-pub-7243139026882115/5642298090"
       
android:layout_alignParentTop="true"         android:layout_centerHorizontal="true">     </com.google.android.gms.ads.AdView>     <EditText         android:id="@+id/log1"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_alignParentTop="true"         android:layout_centerHorizontal="true"         android:layout_marginTop="178dp"         android:ems="10"         android:hint="Email"         android:inputType="textPersonName"         android:textColor="@color/cardview_light_background"         android:textColorHint="@android:color/holo_blue_bright" />     <EditText         android:id="@+id/log2"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_alignLeft="@+id/log1"         android:layout_alignStart="@+id/log1"         android:layout_below="@+id/log1"         android:layout_marginTop="29dp"         android:ems="10"         android:hint="Password"         android:inputType="textPassword"         android:textColor="@color/cardview_light_background"         android:textColorHint="@android:color/holo_blue_bright" />     <Button         android:id="@+id/logbut"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_below="@+id/log2"         android:layout_centerHorizontal="true"         android:layout_marginTop="20dp"         android:background="@color/colorPrimaryDark"         android:text="Login"         android:textColor="@color/cardview_light_background"         android:textStyle="bold" />     <TextView         android:id="@+id/textView16"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_alignParentStart="true"         android:layout_below="@+id/logbut"         android:layout_marginTop="14dp"         android:text="You need internet connectivity to login"         android:textColor="@android:color/holo_red_dark"         android:textSize="20dp"         android:textStyle="bold|italic" />     <TextView         android:id="@+id/regtext"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_alignParentStart="true"         android:layout_below="@+id/textView16"         android:layout_marginTop="16dp"         android:text="forgot password or want to register click here. It's free and require no internet connection"         android:textColor="@android:color/holo_red_dark"         android:textSize="20dp"         android:textStyle="bold|italic" /> </RelativeLayout>

Press ctrl + f10 to run the application or alternatively, press run from the toolbar to run the application




























In the next lesson, we shall talk about Navigation Drawer and how to set up a Google Admob account and start making money. See you in the next tutorial

No comments:

Post a Comment