Code: Part3

MainActivity.java

package org.meicode.meibank;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;

import org.meicode.meibank.Database.DatabaseHelper;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = “MainActivity”;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        SQLiteDatabase db = databaseHelper.getReadableDatabase();
        Cursor cursor = db.query(“items”, null, null, null, null, null, null);
        if (null != cursor) {
            if (cursor.moveToFirst()) {
                Log.d(TAG, “onCreate: name: ” + cursor.getString(cursor.getColumnIndex(“name”)));
            }
        }
    }
}

DatabaseHelper.java

package org.meicode.meibank.Database;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String TAG = “DatabaseHelper”;

    private static final String DB_NAME = “fb_mei_bank”;
    private static final int DB_VERSION = 1;

    public DatabaseHelper(@Nullable Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        Log.d(TAG, “onCreate: started”);
        String createUserTable = “CREATE TABLE users (_id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL, ” +
                “password TEXT NOT NULL, ” +
                “first_name TEXT, last_name TEXT, address TEXT, image_url TEXT, remained_amount DOUBLE)”;

        String createShoppingTable = “CREATE TABLE shopping (_id INTEGER PRIMARY KEY AUTOINCREMENT, item_id INTEGER, ” +
                “user_id INTEGER, transaction_id INTEGER, price DOUBLE, date DATE, description TEXT)”;


        String createInvestmentTable = “CREATE TABLE investments (_id INTEGER PRIMARY KEY AUTOINCREMENT, amount DOUBLE, ” +
                “monthly_roi DOUBLE, name TEXT, init_date DATE, finish_date DATE, user_id INTEGER, transaction_id INTEGER)”;

        String createLoansTable  = “CREATE TABLE loans (_id INTEGER PRIMARY KEY AUTOINCREMENT, init_date DATE, ” +
                “finish_date DATE, init_amount DOUBLE, remained_amount DOUBLE, monthly_payment DOUBLE, monthly_roi DOUBLE,” +
                “name TEXT, user_id INTEGER)”;

        String createTransactionTable = “CREATE TABLE transactions (_id INTEGER PRIMARY KEY AUTOINCREMENT, amount double, ” +
                “date DATE, type TEXT, user_id INTEGER, recipient TEXT, description TEXT)”;

        String createItemsTable = “CREATE TABLE items (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, image_url TEXT,” +
                “description TEXT)”;

        sqLiteDatabase.execSQL(createUserTable);
        sqLiteDatabase.execSQL(createShoppingTable);
        sqLiteDatabase.execSQL(createInvestmentTable);
        sqLiteDatabase.execSQL(createLoansTable);
        sqLiteDatabase.execSQL(createTransactionTable);
        sqLiteDatabase.execSQL(createItemsTable);

        addInitialItems(sqLiteDatabase);
    }

    private void addInitialItems (SQLiteDatabase db) {
        Log.d(TAG, “addInitialItems: started”);
        ContentValues values = new ContentValues();
        values.put(“name”, “Bike”);
        values.put(“image_url”, “https://cdn.shopify.com/s/files/1/0903/4494/products/Smashing-Pumpkin-GX-Eagle-complete-front-white.jpg”);
        values.put(“description”, “The perfect mountain bike”);

        db.insert(“items”, null, values);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

RegisterActivity.java

package org.meicode.meibank.Authentication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.meicode.meibank.Database.DatabaseHelper;
import org.meicode.meibank.MainActivity;
import org.meicode.meibank.Models.User;
import org.meicode.meibank.R;
import org.meicode.meibank.Utils;

public class RegisterActivity extends AppCompatActivity {
    private static final String TAG = “RegisterActivity”;

    private EditText edtTxtEmail, edtTxtPassword, edtTxtAddress, edtTxtName;
    private TextView txtWarning, txtLogin, txtLicence;
    private ImageView firstImage, secondImage, thirdImage, forthImage, fifthImage;
    private Button btnRegister;

    private String image_url;

    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();

        databaseHelper = new DatabaseHelper(this);

        image_url = “first”;
        handleImageUrl();

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initRegister();
            }
        });
    }

    private void handleImageUrl() {
        Log.d(TAG, “handleImageUrl: started”);
        firstImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                image_url = “first”;
            }
        });

        secondImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                image_url = “second”;
            }
        });

        thirdImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                image_url = “third”;
            }
        });

        forthImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                image_url = “forth”;
            }
        });

        fifthImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                image_url = “fifth”;
            }
        });
    }

    private void initRegister() {
        Log.d(TAG, “initRegister: started”);
        String email = edtTxtEmail.getText().toString();
        String password = edtTxtPassword.getText().toString();

        if (email.equals(“”) || password.equals(“”)) {
            txtWarning.setVisibility(View.VISIBLE);
            txtWarning.setText(“Please enter the password and Email”);
        }else {
            txtWarning.setVisibility(View.GONE);


        }
    }

    private class DoesUserExist extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String… strings) {
            try{
                SQLiteDatabase db = databaseHelper.getReadableDatabase();
                Cursor cursor = db.query(“users”, new String[] {“_id”, “email”}, “email=?”,
                        new String[] {strings[0]}, null, null, null);
                if (null != cursor) {
                    if (cursor.moveToFirst()) {
                        if (cursor.getString(cursor.getColumnIndex(“email”)).equals(strings[0])) {
                            cursor.close();
                            db.close();
                            return true;
                        }else {
                            cursor.close();
                            db.close();
                            return false;
                        }
                    }else {
                        cursor.close();
                        db.close();
                        return false;
                    }
                }else {
                    db.close();
                    return true;
                }
            }catch (SQLException e) {
                e.printStackTrace();

                return true;
            }
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);

            if (aBoolean) {
                txtWarning.setVisibility(View.VISIBLE);
                txtWarning.setText(“There is user with this email, please try another email”);
            }else {
                txtWarning.setVisibility(View.GONE);
            }
        }
    }

    private class RegisterUser extends AsyncTask<Void, Void, User> {

        private String email;
        private String password;
        private String address;
        private String first_name;
        private String last_name;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            String email = edtTxtEmail.getText().toString();
            String password = edtTxtPassword.getText().toString();
            String address = edtTxtAddress.getText().toString();
            String name = edtTxtName.getText().toString();

            this.email = email;
            this.password = password;
            this.address = address;

            String[] names = name.split(” “);
            if (names.length >= 1) {
                this.first_name = names[0];
                for (int i=1; i<names.length; i++) {
                    if (i>1) {
                        last_name += ” ” + names[i];
                    }else {
                        last_name += names[i];
                    }
                }
            }else {
                this.first_name = names[0];
            }

        }

        @Override
        protected User doInBackground(Void… voids) {
            try {
                SQLiteDatabase db = databaseHelper.getWritableDatabase();

                ContentValues values = new ContentValues();
                values.put(“email”, this.email);
                values.put(“password”, this.password);
                values.put(“address”, this.address);
                values.put(“first_name”, this.first_name);
                values.put(“last_name”, this.last_name);
                values.put(“remained_amount”, 0.0);
                values.put(“image_url”, image_url);

                long userId = db.insert(“users”, null, values);
                Log.d(TAG, “doInBackground: userId”);

                Cursor cursor = db.query(“users”, null, “_id=?”,
                        new String[] {String.valueOf(userId)}, null, null, null);
                if (null != cursor) {
                    if (cursor.moveToFirst()) {
                        User user = new User();
                        user.set_id(cursor.getInt(cursor.getColumnIndex(“_id”)));
                        user.setEmail(cursor.getString(cursor.getColumnIndex(“email”)));
                        user.setPassword(cursor.getString(cursor.getColumnIndex(“password”)));
                        user.setFirst_name(cursor.getString(cursor.getColumnIndex(“first_name”)));
                        user.setLast_name(cursor.getString(cursor.getColumnIndex(“last_name”)));
                        user.setImage_url(cursor.getString(cursor.getColumnIndex(“image_url”)));
                        user.setAddress(cursor.getString(cursor.getColumnIndex(“address”)));
                        user.setRemained_amount(cursor.getDouble(cursor.getColumnIndex(“remained_amount”)));

                        cursor.close();
                        db.close();
                        return user;
                    }else {
                        cursor.close();
                        db.close();
                        return null;
                    }
                }else {
                    db.close();
                    return null;
                }

            }catch (SQLException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(User user) {
            super.onPostExecute(user);

            if (null != user) {
                Toast.makeText(RegisterActivity.this, “User ” + user.getEmail() + ” registered successfully”, Toast.LENGTH_SHORT).show();
                Utils utils = new Utils(RegisterActivity.this);
                utils.addUserToSharedPreferences(user);
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }else {
                Toast.makeText(RegisterActivity.this, “Wasn’t able to register, please try again later”, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void initViews() {
        Log.d(TAG, “initViews: called”);

        edtTxtEmail = (EditText) findViewById(R.id.edtTxtEmail);
        edtTxtPassword = (EditText) findViewById(R.id.edtTxtPassword);
        edtTxtAddress = (EditText) findViewById(R.id.edtTxtAddress);
        edtTxtName = (EditText) findViewById(R.id.edtTxtName);

        txtWarning = (TextView) findViewById(R.id.txtWarning);
        txtLogin  = (TextView) findViewById(R.id.txtLogin);
        txtLicence = (TextView) findViewById(R.id.txtLicense);

        firstImage = (ImageView) findViewById(R.id.firstImage);
        secondImage = (ImageView) findViewById(R.id.secondImage);
        thirdImage = (ImageView) findViewById(R.id.thirdImage);
        forthImage = (ImageView) findViewById(R.id.forthImage);
        fifthImage = (ImageView) findViewById(R.id.fifthImage);

        btnRegister = (Button) findViewById(R.id.btnRegister);
    }
}



User.java

package org.meicode.meibank.Models;

public class User {
    private int _id;
    private String email;
    private String password;
    private String first_name;
    private String last_name;
    private String address;
    private String image_url;
    private double remained_amount;

    public User(int _id, String email, String password, String first_name, String last_name, String address, String image_url, double remained_amount) {
        this._id = _id;
        this.email = email;
        this.password = password;
        this.first_name = first_name;
        this.last_name = last_name;
        this.address = address;
        this.image_url = image_url;
        this.remained_amount = remained_amount;
    }

    public User() {
    }

    public int get_id() {
        return _id;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getImage_url() {
        return image_url;
    }

    public void setImage_url(String image_url) {
        this.image_url = image_url;
    }

    public double getRemained_amount() {
        return remained_amount;
    }

    public void setRemained_amount(double remained_amount) {
        this.remained_amount = remained_amount;
    }

    @Override
    public String toString() {
        return “User{” +
                “_id=” + _id +
                “, email='” + email + ‘\” +
                “, password='” + password + ‘\” +
                “, first_name='” + first_name + ‘\” +
                “, last_name='” + last_name + ‘\” +
                “, address='” + address + ‘\” +
                “, image_url='” + image_url + ‘\” +
                “, remained_amount=” + remained_amount +
                ‘}’;
    }
}

Utils.java

package org.meicode.meibank;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;

import org.meicode.meibank.Models.User;

public class Utils {
    private static final String TAG = “Utils”;

    private Context context;

    public Utils(Context context) {
        this.context = context;
    }

    public void addUserToSharedPreferences (User user) {
        Log.d(TAG, “addUserToSharedPreferences: adding: ” + user.toString());
        SharedPreferences sharedPreferences = context.getSharedPreferences(“logged_in_user”, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        Gson gson = new Gson();

        editor.putString(“user”, gson.toJson(user));
        editor.apply();
    }
}



activity_register.xml

<?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”
    tools:context=”.Authentication.RegisterActivity”>

    <RelativeLayout
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_centerInParent=”true”>

        <Button
            android:id=”@+id/btnRegister”
            android:layout_width=”wrap_content”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/imagesRelLayout”
            android:layout_centerHorizontal=”true”
            android:layout_marginTop=”20dp”
            android:background=”@color/orange”
            android:text=”Register” />

        <EditText
            android:id=”@+id/edtTxtPassword”
            android:layout_width=”match_parent”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/edtTxtEmail”
            android:layout_marginLeft=”30dp”
            android:layout_marginTop=”10dp”
            android:layout_marginRight=”30dp”
            android:hint=”Password”
            android:inputType=”textPassword” />

        <EditText
            android:id=”@+id/edtTxtName”
            android:layout_width=”match_parent”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/edtTxtPassword”
            android:layout_marginLeft=”30dp”
            android:layout_marginTop=”10dp”
            android:layout_marginRight=”30dp”
            android:hint=”Name” />

        <EditText
            android:id=”@+id/edtTxtAddress”
            android:layout_width=”match_parent”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/edtTxtName”
            android:layout_marginLeft=”30dp”
            android:layout_marginTop=”10dp”
            android:layout_marginRight=”30dp”
            android:hint=”Address”
            android:lines=”2″ />

        <EditText
            android:id=”@+id/edtTxtEmail”
            android:layout_width=”match_parent”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/logo”
            android:layout_marginLeft=”30dp”
            android:layout_marginTop=”50dp”
            android:layout_marginRight=”30dp”
            android:hint=”Email”
            android:inputType=”textEmailAddress” />

        <ImageView
            android:id=”@+id/logo”
            android:layout_width=”100dp”
            android:layout_height=”50dp”
            android:layout_centerHorizontal=”true”
            android:src=”@mipmap/meicode” />

        <RelativeLayout
            android:id=”@+id/imagesRelLayout”
            android:layout_width=”wrap_content”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/edtTxtAddress”
            android:layout_centerHorizontal=”true”
            android:layout_marginTop=”10dp”>

            <ImageView
                android:id=”@+id/firstImage”
                android:layout_width=”50dp”
                android:layout_height=”50dp”
                android:src=”@mipmap/boy” />

            <ImageView
                android:id=”@+id/secondImage”
                android:layout_width=”50dp”
                android:layout_height=”50dp”
                android:layout_marginLeft=”10dp”
                android:layout_toRightOf=”@+id/firstImage”
                android:src=”@mipmap/girl” />

            <ImageView
                android:id=”@+id/thirdImage”
                android:layout_width=”50dp”
                android:layout_height=”50dp”
                android:layout_marginLeft=”10dp”
                android:layout_toRightOf=”@+id/secondImage”
                android:src=”@mipmap/man” />

            <ImageView
                android:id=”@+id/forthImage”
                android:layout_width=”50dp”
                android:layout_height=”50dp”
                android:layout_marginLeft=”10dp”
                android:layout_toRightOf=”@+id/thirdImage”
                android:src=”@mipmap/woman” />

            <ImageView
                android:id=”@+id/fifthImage”
                android:layout_width=”50dp”
                android:layout_height=”50dp”
                android:layout_marginLeft=”10dp”
                android:layout_toRightOf=”@+id/forthImage”
                android:src=”@mipmap/secon_girl” />

        </RelativeLayout>

        <TextView
            android:id=”@+id/txtWarning”
            android:layout_width=”wrap_content”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/btnRegister”
            android:layout_centerHorizontal=”true”
            android:layout_marginTop=”20dp”
            android:text=”Warning”
            android:textColor=”@color/colorAccent”
            android:visibility=”gone” />

        <TextView
            android:id=”@+id/txtLogin”
            android:layout_width=”wrap_content”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/txtWarning”
            android:layout_centerHorizontal=”true”
            android:layout_marginTop=”50dp”
            android:text=”Have an account? login from here”
            android:textColor=”@color/blue” />

    </RelativeLayout>

    <TextView
        android:id=”@+id/txtLicense”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignParentBottom=”true”
        android:layout_centerHorizontal=”true”
        android:layout_marginBottom=”10dp”
        android:text=”Developed By Meisam at meiCode.org”
        android:textStyle=”italic” />

</RelativeLayout>


activity_register.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<androidx.constraintlayout.widget.ConstraintLayout 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”
    tools:context=”.MainActivity”>

    <TextView
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:text=”Hello World!”
        app:layout_constraintBottom_toBottomOf=”parent”
        app:layout_constraintLeft_toLeftOf=”parent”
        app:layout_constraintRight_toRightOf=”parent”
        app:layout_constraintTop_toTopOf=”parent” />

</androidx.constraintlayout.widget.ConstraintLayout>


AndroidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
    package=”org.meicode.meibank”>

    <application
        android:allowBackup=”true”
        android:icon=”@mipmap/ic_launcher”
        android:label=”@string/app_name”
        android:roundIcon=”@mipmap/ic_launcher_round”
        android:supportsRtl=”true”
        android:theme=”@style/AppTheme”>
        <activity android:name=”.Authentication.RegisterActivity”></activity>
        <activity android:name=”.MainActivity”>
            <intent-filter>
                <action android:name=”android.intent.action.MAIN” />

                <category android:name=”android.intent.category.LAUNCHER” />
            </intent-filter>
        </activity>
    </application>

</manifest>


build.gradle

apply plugin: ‘com.android.application’

android {
    compileSdkVersion 29
    buildToolsVersion “29.0.2”
    defaultConfig {
        applicationId “org.meicode.meibank”
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName “1.0”
        testInstrumentationRunner “androidx.test.runner.AndroidJUnitRunner”
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’
        }
    }
}

dependencies {
    implementation fileTree(dir: ‘libs’, include: [‘*.jar’])

    //gson library
    implementation ‘com.google.code.gson:gson:2.8.5’

    implementation ‘androidx.appcompat:appcompat:1.1.0’
    implementation ‘androidx.constraintlayout:constraintlayout:1.1.3’
    testImplementation ‘junit:junit:4.12’
    androidTestImplementation ‘androidx.test:runner:1.2.0’
    androidTestImplementation ‘androidx.test.espresso:espresso-core:3.2.0’
}



Subscribe To Our Newsletter
Get updates and learn from the best

Leave a Reply

Your email address will not be published. Required fields are marked *

Andriod Course

Table of Contents