> call, Throwable t) {
51 | Log.e("TKD", "Error: " + t);
52 | }
53 | });
54 |
55 | new CountDownTimer(10000, 5000) {
56 |
57 | @Override
58 | public void onTick(long millisUntilFinished) {
59 |
60 | }
61 |
62 | @Override
63 | public void onFinish() {
64 | getElections();
65 | }
66 | }.start();
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/dummy/DummyContent.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting.dummy;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | /**
9 | * Helper class for providing sample content for user interfaces created by
10 | * Android template wizards.
11 | *
12 | * TODO: Replace all uses of this class before publishing your app.
13 | */
14 | public class DummyContent {
15 |
16 | /**
17 | * An array of sample (dummy) items.
18 | */
19 | public static final List ITEMS = new ArrayList();
20 |
21 | /**
22 | * A map of sample (dummy) items, by ID.
23 | */
24 | public static final Map ITEM_MAP = new HashMap();
25 |
26 | private static final int COUNT = 25;
27 |
28 | static {
29 | // Add some sample items.
30 | for (int i = 1; i <= COUNT; i++) {
31 | addItem(createDummyItem(i));
32 | }
33 | }
34 |
35 | private static void addItem(DummyItem item) {
36 | ITEMS.add(item);
37 | ITEM_MAP.put(item.id, item);
38 | }
39 |
40 | private static DummyItem createDummyItem(int position) {
41 | return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position));
42 | }
43 |
44 | private static String makeDetails(int position) {
45 | StringBuilder builder = new StringBuilder();
46 | builder.append("Details about Item: ").append(position);
47 | for (int i = 0; i < position; i++) {
48 | builder.append("\nMore details information here.");
49 | }
50 | return builder.toString();
51 | }
52 |
53 | /**
54 | * A dummy item representing a piece of content.
55 | */
56 | public static class DummyItem {
57 | public final String id;
58 | public final String content;
59 | public final String details;
60 |
61 | public DummyItem(String id, String content, String details) {
62 | this.id = id;
63 | this.content = content;
64 | this.details = details;
65 | }
66 |
67 | @Override
68 | public String toString() {
69 | return content;
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/rest/AddCandidateRequest.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting.rest;
2 |
3 | import java.io.Serializable;
4 | import com.google.gson.annotations.Expose;
5 | import com.google.gson.annotations.SerializedName;
6 |
7 | import org.apache.commons.lang3.builder.ToStringBuilder;
8 |
9 |
10 | public class AddCandidateRequest implements Serializable
11 | {
12 |
13 | @SerializedName("name")
14 | @Expose
15 | private String name;
16 | @SerializedName("sign")
17 | @Expose
18 | private String sign;
19 | @SerializedName("imgAddress")
20 | @Expose
21 | private String imgAddress;
22 | @SerializedName("electionId")
23 | @Expose
24 | private String electionId;
25 | private final static long serialVersionUID = -1785708481179338667L;
26 |
27 | /**
28 | * No args constructor for use in serialization
29 | *
30 | */
31 | public AddCandidateRequest() {
32 | }
33 |
34 | /**
35 | *
36 | * @param electionId
37 | * @param name
38 | * @param sign
39 | * @param imgAddress
40 | */
41 | public AddCandidateRequest(String name, String sign, String imgAddress, String electionId) {
42 | super();
43 | this.name = name;
44 | this.sign = sign;
45 | this.imgAddress = imgAddress;
46 | this.electionId = electionId;
47 | }
48 |
49 | public String getName() {
50 | return name;
51 | }
52 |
53 | public void setName(String name) {
54 | this.name = name;
55 | }
56 |
57 | public String getSign() {
58 | return sign;
59 | }
60 |
61 | public void setSign(String sign) {
62 | this.sign = sign;
63 | }
64 |
65 | public String getImgAddress() {
66 | return imgAddress;
67 | }
68 |
69 | public void setImgAddress(String imgAddress) {
70 | this.imgAddress = imgAddress;
71 | }
72 |
73 | public String getElectionId() {
74 | return electionId;
75 | }
76 |
77 | public void setElectionId(String electionId) {
78 | this.electionId = electionId;
79 | }
80 |
81 | @Override
82 | public String toString() {
83 | return new ToStringBuilder(this).append("name", name).append("sign", sign).append("imgAddress", imgAddress).append("electionId", electionId).toString();
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/election_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
10 |
11 |
18 |
19 |
23 |
24 |
33 |
34 |
39 |
40 |
46 |
47 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'com.google.gms.google-services'
3 |
4 | android {
5 | compileSdkVersion 28
6 | defaultConfig {
7 | applicationId "com.example.tkd.zvoting"
8 | minSdkVersion 21
9 | targetSdkVersion 28
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | compileOptions {
21 | sourceCompatibility = 1.8
22 | targetCompatibility = 1.8
23 | }
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 | implementation 'com.google.android.material:material:1.0.0'
29 | implementation 'androidx.appcompat:appcompat:1.1.0'
30 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
31 | implementation 'com.google.firebase:firebase-auth:19.2.0'
32 | implementation 'androidx.legacy:legacy-support-v4:1.0.0'
33 | implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
34 | implementation 'com.google.firebase:firebase-database:19.2.0'
35 | testImplementation 'junit:junit:4.12'
36 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
37 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
38 | implementation 'androidx.recyclerview:recyclerview:1.1.0'
39 |
40 | def lifecycle_version = "1.1.1"
41 | implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
42 | annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.1.0'
43 |
44 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
45 | implementation 'com.sdsmdg.harjot:materialshadows:1.2.5'
46 |
47 | implementation 'com.balysv:material-ripple:1.0.2'
48 |
49 | implementation 'com.squareup.retrofit2:retrofit:2.7.1'
50 | implementation 'com.squareup.retrofit2:converter-gson:2.7.1'
51 | implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
52 | implementation 'io.reactivex.rxjava2:rxjava:2.2.17'
53 | implementation 'com.squareup.retrofit2:adapter-rxjava2:2.7.1'
54 |
55 | implementation 'org.apache.commons:commons-lang3:3.9'
56 | implementation 'androidx.appcompat:appcompat:1.2.0-alpha01'
57 |
58 | implementation 'com.github.bumptech.glide:glide:4.11.0'
59 | annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
60 | }
61 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/ElectionsFragment.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import androidx.lifecycle.Observer;
4 | import androidx.lifecycle.ViewModelProviders;
5 |
6 | import android.os.Bundle;
7 |
8 | import androidx.annotation.NonNull;
9 | import androidx.annotation.Nullable;
10 | import androidx.fragment.app.Fragment;
11 | import androidx.recyclerview.widget.RecyclerView;
12 |
13 | import android.view.LayoutInflater;
14 | import android.view.View;
15 | import android.view.ViewGroup;
16 |
17 | import com.example.tkd.zvoting.model.Election;
18 | import com.example.tkd.zvoting.model.User;
19 |
20 | import java.util.ArrayList;
21 |
22 | public class ElectionsFragment extends Fragment {
23 |
24 | private ElectionsViewModel mViewModel;
25 | User user;
26 |
27 | public static ElectionsFragment newInstance() {
28 | return new ElectionsFragment();
29 | }
30 |
31 | RecyclerView electionList;
32 |
33 | @Override
34 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
35 | @Nullable Bundle savedInstanceState) {
36 |
37 |
38 | View view = inflater.inflate(R.layout.elections_fragment, container, false);
39 | initializeViews(view);
40 |
41 | return view;
42 | }
43 |
44 | private void initializeViews(View root) {
45 | electionList = root.findViewById(R.id.electionList);
46 | }
47 |
48 | @Override
49 | public void onResume() {
50 | super.onResume();
51 |
52 | mViewModel.mDataViewModel.mainfragment.setValue(DataViewModel.ElectionsFragment);
53 |
54 | mViewModel.getElections();
55 |
56 | mViewModel.mDataViewModel.liveUser.observe(this, new Observer() {
57 | @Override
58 | public void onChanged(User currentUser) {
59 | ElectionsFragment.this.user = currentUser;
60 |
61 | mViewModel.liveElections.observe(ElectionsFragment.this, new Observer>() {
62 | @Override
63 | public void onChanged(ArrayList elections) {
64 | electionList.setAdapter(new ElectionListAdapter(ElectionsFragment.this, elections, user));
65 | }
66 | });
67 | }
68 | });
69 | }
70 |
71 | @Override
72 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
73 | super.onActivityCreated(savedInstanceState);
74 | mViewModel = ViewModelProviders.of(this).get(ElectionsViewModel.class);
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/model/Vote.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting.model;
2 |
3 | import com.google.gson.annotations.Expose;
4 | import com.google.gson.annotations.SerializedName;
5 |
6 | import org.apache.commons.lang3.builder.ToStringBuilder;
7 |
8 | import java.io.Serializable;
9 |
10 | public class Vote implements Serializable
11 | {
12 |
13 | @SerializedName("id")
14 | @Expose
15 | private String id;
16 | @SerializedName("voterID")
17 | @Expose
18 | private String voterID;
19 | @SerializedName("values")
20 | @Expose
21 | private String values;
22 | @SerializedName("electionID")
23 | @Expose
24 | private String electionID;
25 | @SerializedName("doctype")
26 | @Expose
27 | private String doctype;
28 | private final static long serialVersionUID = 3009877941632861163L;
29 |
30 | /**
31 | * No args constructor for use in serialization
32 | *
33 | */
34 | public Vote() {
35 | }
36 |
37 | /**
38 | *
39 | * @param doctype
40 | * @param electionID
41 | * @param values
42 | * @param voterID
43 | * @param id
44 | */
45 | public Vote(String id, String voterID, String values, String electionID, String doctype) {
46 | super();
47 | this.id = id;
48 | this.voterID = voterID;
49 | this.values = values;
50 | this.electionID = electionID;
51 | this.doctype = doctype;
52 | }
53 |
54 | public String getId() {
55 | return id;
56 | }
57 |
58 | public void setId(String id) {
59 | this.id = id;
60 | }
61 |
62 | public String getVoterID() {
63 | return voterID;
64 | }
65 |
66 | public void setVoterID(String voterID) {
67 | this.voterID = voterID;
68 | }
69 |
70 | public String getValues() {
71 | return values;
72 | }
73 |
74 | public void setValues(String values) {
75 | this.values = values;
76 | }
77 |
78 | public String getElectionID() {
79 | return electionID;
80 | }
81 |
82 | public void setElectionID(String electionID) {
83 | this.electionID = electionID;
84 | }
85 |
86 | public String getDoctype() {
87 | return doctype;
88 | }
89 |
90 | public void setDoctype(String doctype) {
91 | this.doctype = doctype;
92 | }
93 |
94 | @Override
95 | public String toString() {
96 | return new ToStringBuilder(this).append("id", id).append("voterID", voterID).append("values", values).append("electionID", electionID).append("doctype", doctype).toString();
97 | }
98 |
99 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/my_election_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
10 |
11 |
18 |
19 |
24 |
25 |
30 |
31 |
41 |
42 |
49 |
50 |
51 |
56 |
57 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/EmptyFragment.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import androidx.lifecycle.ViewModelProviders;
4 |
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 |
8 | import androidx.annotation.NonNull;
9 | import androidx.annotation.Nullable;
10 | import androidx.fragment.app.Fragment;
11 |
12 | import android.view.LayoutInflater;
13 | import android.view.View;
14 | import android.view.ViewGroup;
15 | import android.view.animation.Animation;
16 | import android.view.animation.AnimationUtils;
17 | import android.widget.Button;
18 | import android.widget.ImageView;
19 | import android.widget.TextView;
20 |
21 | public class EmptyFragment extends Fragment {
22 |
23 | private DataViewModel mDataViewModel;
24 | TextView pagetitle, pagesubtitle;
25 | Button btnguide;
26 | Animation atg, atgtwo, atgthree;
27 | ImageView imageView3;
28 |
29 | public static EmptyFragment newInstance() {
30 | return new EmptyFragment();
31 | }
32 |
33 | @Override
34 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
35 | @Nullable Bundle savedInstanceState) {
36 | return inflater.inflate(R.layout.empty_fragment, container, false);
37 | }
38 |
39 | @Override
40 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
41 | super.onActivityCreated(savedInstanceState);
42 | DataViewModelFactory factory = new DataViewModelFactory(getActivity().getApplication());
43 | mDataViewModel = ViewModelProviders.of(this, factory).get(DataViewModel.class);
44 |
45 | initializeViews(getView());
46 |
47 | btnguide.setOnClickListener(new View.OnClickListener() {
48 | @Override
49 | public void onClick(View v) {
50 | Intent a = new Intent(getActivity(),PackageAct.class);
51 | startActivity(a);
52 | }
53 | });
54 |
55 | // pass an animation
56 | imageView3.startAnimation(atg);
57 | pagetitle.startAnimation(atgtwo);
58 | pagesubtitle.startAnimation(atgtwo);
59 | btnguide.startAnimation(atgthree);
60 | }
61 |
62 | private void initializeViews(View view) {
63 | //animations
64 | atg = AnimationUtils.loadAnimation(getContext(), R.anim.atg);
65 | atgtwo = AnimationUtils.loadAnimation(getContext(), R.anim.atgtwo);
66 | atgthree = AnimationUtils.loadAnimation(getContext(), R.anim.atgthree);
67 |
68 | //animation contents
69 | imageView3 = view.findViewById(R.id.cuteRobot);
70 | pagetitle = view.findViewById(R.id.pagetitle);
71 | pagesubtitle = view.findViewById(R.id.pagesubtitle);
72 | btnguide = view.findViewById(R.id.btnAddElection);
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/empty_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
20 |
32 |
33 |
50 |
51 |
65 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/rest/AddVoterRequest.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting.rest;
2 |
3 | import java.io.Serializable;
4 | import com.google.gson.annotations.Expose;
5 | import com.google.gson.annotations.SerializedName;
6 |
7 | import org.apache.commons.lang3.builder.ToStringBuilder;
8 |
9 | public class AddVoterRequest implements Serializable
10 | {
11 |
12 | @SerializedName("name")
13 | @Expose
14 | private String name;
15 | @SerializedName("email")
16 | @Expose
17 | private String email;
18 | @SerializedName("v1")
19 | @Expose
20 | private String v1;
21 | @SerializedName("v2")
22 | @Expose
23 | private String v2;
24 | @SerializedName("v3")
25 | @Expose
26 | private String v3;
27 | @SerializedName("electionId")
28 | @Expose
29 | private String electionId;
30 | private final static long serialVersionUID = 7733090181673195717L;
31 |
32 | /**
33 | * No args constructor for use in serialization
34 | *
35 | */
36 | public AddVoterRequest() {
37 | }
38 |
39 | /**
40 | *
41 | * @param electionId
42 | * @param name
43 | * @param v1
44 | * @param v2
45 | * @param v3
46 | * @param email
47 | */
48 | public AddVoterRequest(String name, String email, String v1, String v2, String v3, String electionId) {
49 | super();
50 | this.name = name;
51 | this.email = email;
52 | this.v1 = v1;
53 | this.v2 = v2;
54 | this.v3 = v3;
55 | this.electionId = electionId;
56 | }
57 |
58 | public String getName() {
59 | return name;
60 | }
61 |
62 | public void setName(String name) {
63 | this.name = name;
64 | }
65 |
66 | public String getEmail() {
67 | return email;
68 | }
69 |
70 | public void setEmail(String email) {
71 | this.email = email;
72 | }
73 |
74 | public String getV1() {
75 | return v1;
76 | }
77 |
78 | public void setV1(String v1) {
79 | this.v1 = v1;
80 | }
81 |
82 | public String getV2() {
83 | return v2;
84 | }
85 |
86 | public void setV2(String v2) {
87 | this.v2 = v2;
88 | }
89 |
90 | public String getV3() {
91 | return v3;
92 | }
93 |
94 | public void setV3(String v3) {
95 | this.v3 = v3;
96 | }
97 |
98 | public String getElectionId() {
99 | return electionId;
100 | }
101 |
102 | public void setElectionId(String electionId) {
103 | this.electionId = electionId;
104 | }
105 |
106 | @Override
107 | public String toString() {
108 | return new ToStringBuilder(this).append("name", name).append("email", email).append("v1", v1).append("v2", v2).append("v3", v3).append("electionId", electionId).toString();
109 | }
110 |
111 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/LoginFragment.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import androidx.lifecycle.ViewModelProviders;
4 | import android.os.Bundle;
5 | import androidx.annotation.NonNull;
6 | import androidx.annotation.Nullable;
7 | import androidx.fragment.app.Fragment;
8 | import android.view.LayoutInflater;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 | import android.widget.Button;
12 | import android.widget.EditText;
13 | import android.widget.LinearLayout;
14 |
15 | import com.google.android.gms.tasks.OnFailureListener;
16 | import com.google.android.gms.tasks.OnSuccessListener;
17 | import com.google.android.material.snackbar.Snackbar;
18 | import com.google.firebase.auth.AuthResult;
19 | import com.google.firebase.auth.FirebaseAuth;
20 |
21 | public class LoginFragment extends Fragment {
22 |
23 | private DataViewModel mDataViewModel;
24 |
25 | public static LoginFragment newInstance() {
26 | return new LoginFragment();
27 | }
28 |
29 | EditText editEmail, editPassword;
30 | Button btnLogin;
31 | FirebaseAuth firebaseAuth;
32 | View linkRegister;
33 |
34 | @Override
35 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
36 | @Nullable Bundle savedInstanceState) {
37 | View view = inflater.inflate(R.layout.login_fragment, container, false);
38 |
39 | linkRegister = view.findViewById(R.id.linkRegister);
40 |
41 | firebaseAuth = FirebaseAuth.getInstance();
42 |
43 | editEmail = view.findViewById(R.id.editEmail);
44 | editPassword = view.findViewById(R.id.editPassword);
45 | btnLogin = view.findViewById(R.id.btnLogin);
46 |
47 |
48 | return view;
49 | }
50 |
51 | @Override
52 | public void onStart() {
53 | super.onStart();
54 | }
55 |
56 | @Override
57 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
58 | super.onActivityCreated(savedInstanceState);
59 | DataViewModelFactory factory = new DataViewModelFactory(getActivity().getApplication());
60 | mDataViewModel = ViewModelProviders.of(this, factory).get(DataViewModel.class);
61 |
62 | btnLogin.setOnClickListener((v)->{
63 | String email = editEmail.getText().toString();
64 | String password = editPassword.getText().toString();
65 |
66 | firebaseAuth.signInWithEmailAndPassword(email, password).addOnFailureListener(e -> {
67 | Snackbar.make(v, "Login Error: "+e.getMessage(), Snackbar.LENGTH_LONG).show();
68 | });
69 | });
70 |
71 | mDataViewModel.mainfragment.setValue("LoginFragment");
72 |
73 |
74 | linkRegister.setOnClickListener((v)->{
75 | if( getActivity() instanceof AuthActivity) {
76 | AuthActivity authActivity = (AuthActivity) getActivity();
77 | authActivity.loadRegisterFragment();
78 | }
79 | });
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/MyItemRecyclerViewAdapter.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import androidx.recyclerview.widget.RecyclerView;
4 |
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.TextView;
9 |
10 | import com.example.tkd.zvoting.ElectionResultsFragment.OnListFragmentInteractionListener;
11 | import com.example.tkd.zvoting.dummy.DummyContent.DummyItem;
12 |
13 | import java.util.List;
14 |
15 | /**
16 | * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
17 | * specified {@link OnListFragmentInteractionListener}.
18 | * TODO: Replace the implementation with code for your data type.
19 | */
20 | public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter {
21 |
22 | private final List mValues;
23 | private final OnListFragmentInteractionListener mListener;
24 |
25 | public MyItemRecyclerViewAdapter(List items, OnListFragmentInteractionListener listener) {
26 | mValues = items;
27 | mListener = listener;
28 | }
29 |
30 | @Override
31 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
32 | View view = LayoutInflater.from(parent.getContext())
33 | .inflate(R.layout.fragment_item, parent, false);
34 | return new ViewHolder(view);
35 | }
36 |
37 | @Override
38 | public void onBindViewHolder(final ViewHolder holder, int position) {
39 | holder.mItem = mValues.get(position);
40 | holder.mIdView.setText(mValues.get(position).id);
41 | holder.mContentView.setText(mValues.get(position).content);
42 |
43 | holder.mView.setOnClickListener(new View.OnClickListener() {
44 | @Override
45 | public void onClick(View v) {
46 | if (null != mListener) {
47 | // Notify the active callbacks interface (the activity, if the
48 | // fragment is attached to one) that an item has been selected.
49 | mListener.onListFragmentInteraction(holder.mItem);
50 | }
51 | }
52 | });
53 | }
54 |
55 | @Override
56 | public int getItemCount() {
57 | return mValues.size();
58 | }
59 |
60 | public class ViewHolder extends RecyclerView.ViewHolder {
61 | public final View mView;
62 | public final TextView mIdView;
63 | public final TextView mContentView;
64 | public DummyItem mItem;
65 |
66 | public ViewHolder(View view) {
67 | super(view);
68 | mView = view;
69 | mIdView = (TextView) view.findViewById(R.id.item_number);
70 | mContentView = (TextView) view.findViewById(R.id.content);
71 | }
72 |
73 | @Override
74 | public String toString() {
75 | return super.toString() + " '" + mContentView.getText() + "'";
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/model/Election.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting.model;
2 |
3 | import java.io.Serializable;
4 |
5 | import com.google.gson.annotations.Expose;
6 | import com.google.gson.annotations.SerializedName;
7 |
8 | import org.apache.commons.lang3.builder.ToStringBuilder;
9 |
10 |
11 | public class Election implements Serializable {
12 |
13 | @SerializedName("doctype")
14 | @Expose
15 | private String doctype;
16 | @SerializedName("duration")
17 | @Expose
18 | private String duration;
19 | @SerializedName("id")
20 | @Expose
21 | private String id;
22 | @SerializedName("name")
23 | @Expose
24 | private String name;
25 | @SerializedName("startTime")
26 | @Expose
27 | private String startTime;
28 | private final static long serialVersionUID = -7241196734610954202L;
29 |
30 | public boolean isFresh() {
31 | long startTimeSecond = Long.parseLong(startTime);
32 | long currenttimeSecond = System.currentTimeMillis()/1000;
33 |
34 | return startTime.equals("0") || currenttimeSecond=startTimeSecond) &&
44 | (currenttimeSecond<=(startTimeSecond+durationSeond));
45 | }
46 |
47 | public boolean isOver() {
48 | return !isFresh() && !isRunning();
49 | }
50 |
51 | public String getDoctype() {
52 | return doctype;
53 | }
54 |
55 | public void setDoctype(String doctype) {
56 | this.doctype = doctype;
57 | }
58 |
59 | public String getDuration() {
60 | return duration;
61 | }
62 |
63 | public void setDuration(String duration) {
64 | this.duration = duration;
65 | }
66 |
67 | public String getId() {
68 | return id;
69 | }
70 |
71 | public void setId(String id) {
72 | this.id = id;
73 | }
74 |
75 | public String getName() {
76 | return name;
77 | }
78 |
79 | public void setName(String name) {
80 | this.name = name;
81 | }
82 |
83 | public String getStartTime() {
84 | return startTime;
85 | }
86 |
87 | public void setStartTime(String startTime) {
88 | this.startTime = startTime;
89 | }
90 |
91 | @Override
92 | public String toString() {
93 | return new ToStringBuilder(this).append("doctype", doctype).append("duration", duration).append("id", id).append("name", name).append("startTime", startTime).toString();
94 | }
95 |
96 | public long getRemainingTime() {
97 | long startTimeSecond = Long.parseLong(startTime);
98 | long durationSeond = Long.parseLong(duration);
99 | long currenttimeSecond = System.currentTimeMillis()/1000;
100 |
101 | return startTimeSecond+durationSeond-currenttimeSecond;
102 | }
103 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/PackageAct.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import androidx.appcompat.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.view.animation.Animation;
6 | import android.view.animation.AnimationUtils;
7 | import android.widget.ImageView;
8 | import android.widget.SeekBar;
9 | import android.widget.TextView;
10 |
11 | public class PackageAct extends AppCompatActivity {
12 |
13 | TextView pagetitle, pagesubtitle;
14 | ImageView packagePlace;
15 | SeekBar packageRange;
16 | Animation atg, packageimg;
17 |
18 | @Override
19 | protected void onCreate(Bundle savedInstanceState) {
20 | super.onCreate(savedInstanceState);
21 | setContentView(R.layout.activity_package);
22 |
23 | atg = AnimationUtils.loadAnimation(this, R.anim.atg);
24 | packageimg = AnimationUtils.loadAnimation(this, R.anim.packageimg);
25 |
26 | pagetitle = findViewById(R.id.pagetitle);
27 | pagesubtitle = findViewById(R.id.pagesubtitle);
28 |
29 | packagePlace = findViewById(R.id.packagePlace);
30 |
31 | packageRange = findViewById(R.id.packageRange);
32 |
33 | packageRange.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
34 | @Override
35 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
36 | if(progress == 35){
37 | pagetitle.setText("Starter Guy");
38 | pagesubtitle.setText("The simply text be dummies too good and easier");
39 | packagePlace.setImageResource(R.drawable.icstarter);
40 |
41 | // pass animation
42 | packagePlace.startAnimation(packageimg);
43 | pagetitle.startAnimation(atg);
44 | pagesubtitle.startAnimation(atg);
45 | }
46 | else if(progress == 75){
47 | pagetitle.setText("Business Player");
48 | pagesubtitle.setText("The simply text be dummies too good and easier");
49 | packagePlace.setImageResource(R.drawable.icbusinessplayer);
50 |
51 | // pass animation
52 | packagePlace.startAnimation(packageimg);
53 | pagetitle.startAnimation(atg);
54 | pagesubtitle.startAnimation(atg);
55 | }
56 | else if(progress == 100){
57 | pagetitle.setText("Legend of VIP");
58 | pagesubtitle.setText("The simply text be dummies too good and easier");
59 | packagePlace.setImageResource(R.drawable.icvip);
60 |
61 | // pass animation
62 | packagePlace.startAnimation(packageimg);
63 | pagetitle.startAnimation(atg);
64 | pagesubtitle.startAnimation(atg);
65 | }
66 | }
67 |
68 | @Override
69 | public void onStartTrackingTouch(SeekBar seekBar) {
70 |
71 | }
72 |
73 | @Override
74 | public void onStopTrackingTouch(SeekBar seekBar) {
75 |
76 | }
77 | });
78 |
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/AuthActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import androidx.annotation.NonNull;
4 | import androidx.appcompat.app.AppCompatActivity;
5 | import androidx.fragment.app.Fragment;
6 | import androidx.fragment.app.FragmentManager;
7 | import androidx.fragment.app.FragmentTransaction;
8 | import androidx.lifecycle.ViewModelProviders;
9 |
10 | import android.content.Intent;
11 | import android.os.Bundle;
12 | import android.util.Log;
13 |
14 | import com.google.firebase.auth.FirebaseAuth;
15 |
16 | public class AuthActivity extends AppCompatActivity {
17 | FragmentManager fragmentManager;
18 | FirebaseAuth firebaseAuth;
19 | private DataViewModel mDataViewModel;
20 |
21 | @Override
22 | protected void onCreate(Bundle savedInstanceState) {
23 | super.onCreate(savedInstanceState);
24 | setContentView(R.layout.activity_start);
25 |
26 | DataViewModelFactory factory = new DataViewModelFactory(getApplication());
27 | mDataViewModel = ViewModelProviders.of(this, factory).get(DataViewModel.class);
28 |
29 | mDataViewModel.activity.setValue("AuthActivity");
30 |
31 | firebaseAuth = FirebaseAuth.getInstance();
32 | firebaseAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
33 | @Override
34 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
35 | if(firebaseAuth.getCurrentUser()!=null) {
36 | startActivity(new Intent(AuthActivity.this, MasterActivity.class));
37 | finish();
38 | }
39 | }
40 | });
41 |
42 | fragmentManager = getSupportFragmentManager();
43 |
44 | Log.e("TKD", "" + getSupportFragmentManager().getBackStackEntryCount());
45 |
46 | loadLoginFragment();
47 | // loadRegisterFragment();
48 | }
49 |
50 | public void loadLoginFragment() {
51 | FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
52 | fragmentTransaction.setCustomAnimations(R.animator.fade_appear, R.animator.fade_disappear,R.animator.fade_appear, R.animator.fade_disappear);
53 |
54 | Fragment loginFragment = new LoginFragment();
55 | fragmentTransaction.replace(android.R.id.content, loginFragment);
56 | fragmentTransaction.addToBackStack("Login");
57 | fragmentTransaction.commit();
58 | }
59 |
60 |
61 | public void loadRegisterFragment() {
62 | FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
63 | fragmentTransaction.setCustomAnimations(R.animator.fade_appear, R.animator.fade_disappear,R.animator.fade_appear, R.animator.fade_disappear);
64 |
65 | Fragment loginFragment = RegisterFragment.newInstance();
66 | fragmentTransaction.replace(android.R.id.content, loginFragment);
67 | fragmentTransaction.addToBackStack("Register");
68 |
69 | fragmentTransaction.commit();
70 | }
71 |
72 | @Override
73 | public void onBackPressed() {
74 | int count = getSupportFragmentManager().getBackStackEntryCount();
75 | if (count == 1) {
76 | finish();
77 | } else {
78 | getSupportFragmentManager().popBackStack();
79 | }
80 |
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/model/ElectionResult.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting.model;
2 |
3 | import com.google.gson.annotations.Expose;
4 | import com.google.gson.annotations.SerializedName;
5 |
6 | import org.apache.commons.lang3.builder.ToStringBuilder;
7 |
8 | import java.io.Serializable;
9 | import java.util.List;
10 |
11 | public class ElectionResult implements Serializable
12 | {
13 |
14 | @SerializedName("id")
15 | @Expose
16 | private String id;
17 | @SerializedName("publisherID")
18 | @Expose
19 | private String publisherID;
20 | @SerializedName("values")
21 | @Expose
22 | private List values = null;
23 | @SerializedName("electionID")
24 | @Expose
25 | private String electionID;
26 | @SerializedName("doctype")
27 | @Expose
28 | private String doctype;
29 | @SerializedName("candidates")
30 | @Expose
31 | private List candidates = null;
32 | private final static long serialVersionUID = 7616455984523407376L;
33 |
34 | /**
35 | * No args constructor for use in serialization
36 | *
37 | */
38 | public ElectionResult() {
39 | }
40 |
41 | /**
42 | *
43 | * @param doctype
44 | * @param electionID
45 | * @param candidates
46 | * @param publisherID
47 | * @param values
48 | * @param id
49 | */
50 | public ElectionResult(String id, String publisherID, List values, String electionID, String doctype, List candidates) {
51 | super();
52 | this.id = id;
53 | this.publisherID = publisherID;
54 | this.values = values;
55 | this.electionID = electionID;
56 | this.doctype = doctype;
57 | this.candidates = candidates;
58 | }
59 |
60 | public String getId() {
61 | return id;
62 | }
63 |
64 | public void setId(String id) {
65 | this.id = id;
66 | }
67 |
68 | public String getPublisherID() {
69 | return publisherID;
70 | }
71 |
72 | public void setPublisherID(String publisherID) {
73 | this.publisherID = publisherID;
74 | }
75 |
76 | public List getValues() {
77 | return values;
78 | }
79 |
80 | public void setValues(List values) {
81 | this.values = values;
82 | }
83 |
84 | public String getElectionID() {
85 | return electionID;
86 | }
87 |
88 | public void setElectionID(String electionID) {
89 | this.electionID = electionID;
90 | }
91 |
92 | public String getDoctype() {
93 | return doctype;
94 | }
95 |
96 | public void setDoctype(String doctype) {
97 | this.doctype = doctype;
98 | }
99 |
100 | public List getCandidates() {
101 | return candidates;
102 | }
103 |
104 | public void setCandidates(List candidates) {
105 | this.candidates = candidates;
106 | }
107 |
108 | @Override
109 | public String toString() {
110 | return new ToStringBuilder(this).append("id", id).append("publisherID", publisherID).append("values", values).append("electionID", electionID).append("doctype", doctype).append("candidates", candidates).toString();
111 | }
112 |
113 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/login_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
20 |
21 |
32 |
33 |
44 |
45 |
54 |
55 |
64 |
65 |
70 |
71 |
78 |
79 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/model/Voter.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting.model;
2 |
3 | import com.google.gson.annotations.Expose;
4 | import com.google.gson.annotations.SerializedName;
5 |
6 | import org.apache.commons.lang3.builder.ToStringBuilder;
7 |
8 | import java.io.Serializable;
9 |
10 | public class Voter implements Serializable
11 | {
12 |
13 | @SerializedName("doctype")
14 | @Expose
15 | private String doctype;
16 | @SerializedName("electionID")
17 | @Expose
18 | private String electionID;
19 | @SerializedName("email")
20 | @Expose
21 | private String email;
22 | @SerializedName("id")
23 | @Expose
24 | private String id;
25 | @SerializedName("name")
26 | @Expose
27 | private String name;
28 | @SerializedName("v1")
29 | @Expose
30 | private String v1;
31 | @SerializedName("v2")
32 | @Expose
33 | private String v2;
34 | @SerializedName("v3")
35 | @Expose
36 | private String v3;
37 | private final static long serialVersionUID = -8333242822293631593L;
38 |
39 | /**
40 | * No args constructor for use in serialization
41 | *
42 | */
43 | public Voter() {
44 | }
45 |
46 | /**
47 | *
48 | * @param doctype
49 | * @param electionID
50 | * @param name
51 | * @param id
52 | * @param v1
53 | * @param v2
54 | * @param v3
55 | * @param email
56 | */
57 | public Voter(String doctype, String electionID, String email, String id, String name, String v1, String v2, String v3) {
58 | super();
59 | this.doctype = doctype;
60 | this.electionID = electionID;
61 | this.email = email;
62 | this.id = id;
63 | this.name = name;
64 | this.v1 = v1;
65 | this.v2 = v2;
66 | this.v3 = v3;
67 | }
68 |
69 | public String getDoctype() {
70 | return doctype;
71 | }
72 |
73 | public void setDoctype(String doctype) {
74 | this.doctype = doctype;
75 | }
76 |
77 | public String getElectionID() {
78 | return electionID;
79 | }
80 |
81 | public void setElectionID(String electionID) {
82 | this.electionID = electionID;
83 | }
84 |
85 | public String getEmail() {
86 | return email;
87 | }
88 |
89 | public void setEmail(String email) {
90 | this.email = email;
91 | }
92 |
93 | public String getId() {
94 | return id;
95 | }
96 |
97 | public void setId(String id) {
98 | this.id = id;
99 | }
100 |
101 | public String getName() {
102 | return name;
103 | }
104 |
105 | public void setName(String name) {
106 | this.name = name;
107 | }
108 |
109 | public String getV1() {
110 | return v1;
111 | }
112 |
113 | public void setV1(String v1) {
114 | this.v1 = v1;
115 | }
116 |
117 | public String getV2() {
118 | return v2;
119 | }
120 |
121 | public void setV2(String v2) {
122 | this.v2 = v2;
123 | }
124 |
125 | public String getV3() {
126 | return v3;
127 | }
128 |
129 | public void setV3(String v3) {
130 | this.v3 = v3;
131 | }
132 |
133 | @Override
134 | public String toString() {
135 | return new ToStringBuilder(this).append("doctype", doctype).append("electionID", electionID).append("email", email).append("id", id).append("name", name).append("v1", v1).append("v2", v2).append("v3", v3).toString();
136 | }
137 |
138 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/DataViewModel.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.app.Application;
4 | import android.util.Log;
5 |
6 | import androidx.lifecycle.AndroidViewModel;
7 | import androidx.annotation.NonNull;
8 | import androidx.lifecycle.MutableLiveData;
9 | import androidx.lifecycle.ViewModel;
10 | import androidx.lifecycle.ViewModelProvider;
11 |
12 | import com.example.tkd.zvoting.model.User;
13 | import com.google.firebase.auth.FirebaseAuth;
14 | import com.google.firebase.database.DataSnapshot;
15 | import com.google.firebase.database.DatabaseError;
16 | import com.google.firebase.database.DatabaseReference;
17 | import com.google.firebase.database.FirebaseDatabase;
18 | import com.google.firebase.database.ValueEventListener;
19 |
20 |
21 | class DataViewModelFactory implements ViewModelProvider.Factory {
22 |
23 | private Application application;
24 |
25 | public DataViewModelFactory(Application application) {
26 | this.application = application;
27 | }
28 |
29 | @NonNull
30 | @Override
31 | public T create(@NonNull Class modelClass) {
32 | return (T) DataViewModel.getInstance(application);
33 | }
34 | }
35 |
36 | public class DataViewModel extends AndroidViewModel {
37 |
38 | public static long n = 1000000007;
39 | public static String URL="http://52.191.210.249:3000";
40 | public static String MyElectionsFragment="MyElectionsFragment";
41 | public static String ElectionResultsFragment="ElectionResultsFragment";
42 | public static String ElectionsFragment="ElectionsFragment";
43 | public String userEmailStr;
44 | public String userNameStr;
45 | public FirebaseAuth firebaseAuth;
46 | public MutableLiveData liveUser;
47 | public DatabaseReference databaseReference;
48 |
49 | public MutableLiveData activity, mainfragment;
50 |
51 |
52 | private static DataViewModel instance;
53 |
54 | public static DataViewModel getInstance(@NonNull Application application) {
55 | if(instance==null) instance = new DataViewModel(application);
56 | return instance;
57 | }
58 |
59 | DataViewModel(@NonNull Application application) {
60 | super(application);
61 | firebaseAuth = FirebaseAuth.getInstance();
62 | databaseReference = FirebaseDatabase.getInstance().getReference();
63 |
64 | liveUser = new MutableLiveData<>();
65 | liveUser.setValue( new User(userNameStr, userEmailStr) );
66 | activity = new MutableLiveData<>();
67 | mainfragment = new MutableLiveData<>();
68 |
69 |
70 | firebaseAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
71 | @Override
72 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
73 | if(firebaseAuth.getCurrentUser()!=null) {
74 | String uid = firebaseAuth.getCurrentUser().getUid();
75 | databaseReference.child("user").child(uid).addValueEventListener(new ValueEventListener() {
76 | @Override
77 | public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
78 | User user = (User) dataSnapshot.getValue(User.class);
79 | liveUser.setValue( user );
80 | Log.e("TKD", "USER FOUND");
81 | }
82 |
83 | @Override
84 | public void onCancelled(@NonNull DatabaseError databaseError) {
85 |
86 | }
87 | });
88 | }
89 | }
90 | });
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/OperationsViewModel.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.app.Application;
4 | import android.os.CountDownTimer;
5 | import android.util.Log;
6 |
7 | import androidx.annotation.NonNull;
8 | import androidx.lifecycle.AndroidViewModel;
9 | import androidx.lifecycle.MutableLiveData;
10 | import androidx.lifecycle.ViewModel;
11 |
12 | import com.example.tkd.zvoting.model.Election;
13 | import com.example.tkd.zvoting.rest.ApiClient;
14 | import com.example.tkd.zvoting.rest.ApiInterface;
15 | import com.google.firebase.auth.FirebaseAuth;
16 | import com.google.firebase.database.DatabaseReference;
17 | import com.google.firebase.database.FirebaseDatabase;
18 |
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 | import retrofit2.Call;
23 | import retrofit2.Callback;
24 | import retrofit2.Response;
25 |
26 | public class OperationsViewModel extends AndroidViewModel {
27 | DataViewModel mDataViewModel;
28 | ApiInterface apiInterface;
29 | MutableLiveData> liveElections;
30 |
31 | MutableLiveData> liveMyElections;
32 |
33 | DatabaseReference db;
34 | FirebaseAuth firebaseAuth;
35 | MutableLiveData> liveMyElectionIds;
36 |
37 | public OperationsViewModel(@NonNull Application application) {
38 | super(application);
39 |
40 | db = FirebaseDatabase.getInstance().getReference();
41 | firebaseAuth = FirebaseAuth.getInstance();
42 |
43 | mDataViewModel = DataViewModel.getInstance(application);
44 |
45 | liveElections = new MutableLiveData<>(new ArrayList<>());
46 | liveMyElections = new MutableLiveData<>(new ArrayList<>());
47 | liveMyElectionIds = new MutableLiveData<>(new ArrayList<>());
48 |
49 | mDataViewModel = DataViewModel.getInstance(application);
50 | apiInterface = ApiClient.getClient().create(ApiInterface.class);
51 |
52 | getElections();
53 | }
54 |
55 | public void getElections() {
56 | Call> call = apiInterface.getElections();
57 | call.enqueue(new Callback>() {
58 | @Override
59 | public void onResponse(Call> call, Response> response) {
60 | List body = response.body();
61 |
62 | ArrayList elections = new ArrayList<>();
63 | elections.addAll(body);
64 |
65 | if (!elections.equals(liveElections.getValue())) {
66 | liveElections.setValue(elections);
67 | }
68 |
69 |
70 | if (liveMyElectionIds.getValue() != null && liveMyElectionIds.getValue().size() > 0) {
71 | ArrayList myElectionIds = liveMyElectionIds.getValue();
72 | ArrayList myElections = new ArrayList<>();
73 |
74 | for (Election election : elections) {
75 | if (myElectionIds.contains(election.getId())) {
76 | myElections.add(election);
77 | }
78 | }
79 | liveMyElections.setValue(myElections);
80 |
81 | }
82 | }
83 |
84 | @Override
85 | public void onFailure(Call> call, Throwable t) {
86 | Log.e("TKD", "Error: " + t);
87 | }
88 | });
89 |
90 | new CountDownTimer(10000, 1000) {
91 |
92 | @Override
93 | public void onTick(long millisUntilFinished) {
94 |
95 | }
96 |
97 | @Override
98 | public void onFinish() {
99 | getElections();
100 | }
101 | }.start();
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_register.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
20 |
21 |
31 |
32 |
43 |
44 |
55 |
56 |
65 |
66 |
75 |
76 |
81 |
82 |
89 |
90 |
91 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | xmlns:android
14 |
15 | ^$
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | xmlns:.*
25 |
26 | ^$
27 |
28 |
29 | BY_NAME
30 |
31 |
32 |
33 |
34 |
35 |
36 | .*:id
37 |
38 | http://schemas.android.com/apk/res/android
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | .*:name
48 |
49 | http://schemas.android.com/apk/res/android
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | name
59 |
60 | ^$
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | style
70 |
71 | ^$
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | .*
81 |
82 | ^$
83 |
84 |
85 | BY_NAME
86 |
87 |
88 |
89 |
90 |
91 |
92 | .*
93 |
94 | http://schemas.android.com/apk/res/android
95 |
96 |
97 | ANDROID_ATTRIBUTE_ORDER
98 |
99 |
100 |
101 |
102 |
103 |
104 | .*
105 |
106 | .*
107 |
108 |
109 | BY_NAME
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/rest/VoterLoginRequest.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting.rest;
2 |
3 | import java.io.Serializable;
4 | import com.google.gson.annotations.Expose;
5 | import com.google.gson.annotations.SerializedName;
6 | import org.apache.commons.lang3.builder.ToStringBuilder;
7 |
8 | public class VoterLoginRequest implements Serializable
9 | {
10 |
11 | @SerializedName("email")
12 | @Expose
13 | private String email;
14 | @SerializedName("x")
15 | @Expose
16 | private String x;
17 | @SerializedName("a1")
18 | @Expose
19 | private String a1;
20 | @SerializedName("a2")
21 | @Expose
22 | private String a2;
23 | @SerializedName("a3")
24 | @Expose
25 | private String a3;
26 | @SerializedName("v1")
27 | @Expose
28 | private String v1;
29 | @SerializedName("v2")
30 | @Expose
31 | private String v2;
32 | @SerializedName("v3")
33 | @Expose
34 | private String v3;
35 | @SerializedName("y1")
36 | @Expose
37 | private String y1;
38 | private final static long serialVersionUID = -4618438202281495886L;
39 |
40 | /**
41 | * No args constructor for use in serialization
42 | *
43 | */
44 | public VoterLoginRequest() {
45 | }
46 |
47 | /**
48 | *
49 | * @param a1
50 | * @param a2
51 | * @param a3
52 | * @param x
53 | * @param y1
54 | * @param v1
55 | * @param v2
56 | * @param v3
57 | * @param email
58 | */
59 | public VoterLoginRequest(String email, String x, String a1, String a2, String a3, String v1, String v2, String v3, String y1) {
60 | super();
61 | this.email = email;
62 | this.x = x;
63 | this.a1 = a1;
64 | this.a2 = a2;
65 | this.a3 = a3;
66 | this.v1 = v1;
67 | this.v2 = v2;
68 | this.v3 = v3;
69 | this.y1 = y1;
70 | }
71 |
72 | String str(long val) {
73 | return String.valueOf(val);
74 | }
75 |
76 | public VoterLoginRequest(String email, long x, long a1, long a2, long a3, long v1, long v2, long v3, long y1) {
77 | this.email = email;
78 | this.x = str(x);
79 | this.a1 = str(a1);
80 | this.a2 = str(a2);
81 | this.a3 = str(a3);
82 | this.v1 = str(v1);
83 | this.v2 = str(v2);
84 | this.v3 = str(v3);
85 | this.y1 = str(y1);
86 | }
87 |
88 | public String getEmail() {
89 | return email;
90 | }
91 |
92 | public void setEmail(String email) {
93 | this.email = email;
94 | }
95 |
96 | public String getX() {
97 | return x;
98 | }
99 |
100 | public void setX(String x) {
101 | this.x = x;
102 | }
103 |
104 | public String getA1() {
105 | return a1;
106 | }
107 |
108 | public void setA1(String a1) {
109 | this.a1 = a1;
110 | }
111 |
112 | public String getA2() {
113 | return a2;
114 | }
115 |
116 | public void setA2(String a2) {
117 | this.a2 = a2;
118 | }
119 |
120 | public String getA3() {
121 | return a3;
122 | }
123 |
124 | public void setA3(String a3) {
125 | this.a3 = a3;
126 | }
127 |
128 | public String getV1() {
129 | return v1;
130 | }
131 |
132 | public void setV1(String v1) {
133 | this.v1 = v1;
134 | }
135 |
136 | public String getV2() {
137 | return v2;
138 | }
139 |
140 | public void setV2(String v2) {
141 | this.v2 = v2;
142 | }
143 |
144 | public String getV3() {
145 | return v3;
146 | }
147 |
148 | public void setV3(String v3) {
149 | this.v3 = v3;
150 | }
151 |
152 | public String getY1() {
153 | return y1;
154 | }
155 |
156 | public void setY1(String y1) {
157 | this.y1 = y1;
158 | }
159 |
160 | @Override
161 | public String toString() {
162 | return new ToStringBuilder(this).append("email", email).append("x", x).append("a1", a1).append("a2", a2).append("a3", a3).append("v1", v1).append("v2", v2).append("v3", v3).append("y1", y1).toString();
163 | }
164 |
165 | }
166 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/RegisterFragment.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.os.Bundle;
4 | import android.view.LayoutInflater;
5 | import android.view.View;
6 | import android.view.ViewGroup;
7 | import android.widget.Button;
8 | import android.widget.EditText;
9 |
10 | import androidx.annotation.NonNull;
11 | import androidx.annotation.Nullable;
12 | import androidx.fragment.app.Fragment;
13 | import androidx.lifecycle.ViewModelProviders;
14 |
15 | import com.example.tkd.zvoting.model.User;
16 | import com.google.android.gms.tasks.OnFailureListener;
17 | import com.google.android.gms.tasks.OnSuccessListener;
18 | import com.google.android.material.snackbar.Snackbar;
19 | import com.google.firebase.auth.AuthResult;
20 | import com.google.firebase.auth.FirebaseAuth;
21 | import com.google.firebase.database.DatabaseReference;
22 | import com.google.firebase.database.FirebaseDatabase;
23 |
24 |
25 | public class RegisterFragment extends Fragment {
26 | private FirebaseAuth firebaseAuth;
27 | private EditText editEmail;
28 | private EditText editPassword;
29 | private EditText editName;
30 | private Button btnRegister;
31 | private String email;
32 | private String password;
33 | private String name;
34 |
35 | DatabaseReference db;
36 | private DataViewModel mDataViewModel;
37 |
38 |
39 | public static RegisterFragment newInstance() {
40 | return new RegisterFragment();
41 | }
42 |
43 | @Override
44 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
45 | @Nullable Bundle savedInstanceState) {
46 | View view = inflater.inflate(R.layout.fragment_register, container, false);
47 | view.findViewById(R.id.linkLogin).setOnClickListener((v)->{
48 | if(getActivity() instanceof AuthActivity) {
49 | ((AuthActivity) getActivity()).loadLoginFragment();
50 | }
51 | });
52 |
53 | firebaseAuth = FirebaseAuth.getInstance();
54 |
55 | editName = view.findViewById(R.id.editName);
56 | editEmail = view.findViewById(R.id.editEmail);
57 | editPassword = view.findViewById(R.id.editPassword);
58 | btnRegister = view.findViewById(R.id.btnRegister);
59 |
60 | return view;
61 | }
62 |
63 | @Override
64 | public void onStart() {
65 | super.onStart();
66 | }
67 |
68 | @Override
69 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
70 | super.onActivityCreated(savedInstanceState);
71 | DataViewModelFactory factory = new DataViewModelFactory(getActivity().getApplication());
72 | mDataViewModel = ViewModelProviders.of(this, factory).get(DataViewModel.class);
73 |
74 | mDataViewModel.mainfragment.setValue("RegisterFragment");
75 |
76 |
77 | btnRegister.setOnClickListener((v)->{
78 | name = editName.getText().toString();
79 | email = editEmail.getText().toString();
80 | password = editPassword.getText().toString();
81 |
82 | firebaseAuth.createUserWithEmailAndPassword(email, password).addOnFailureListener(new OnFailureListener() {
83 | @Override
84 | public void onFailure(@NonNull Exception e) {
85 | Snackbar.make(v, "Login Error: "+e.getMessage(), Snackbar.LENGTH_LONG).show();
86 | }
87 | }).addOnSuccessListener(new OnSuccessListener() {
88 | @Override
89 | public void onSuccess(AuthResult authResult) {
90 | String uid = authResult.getUser().getUid();
91 | User user = new User(name, email);
92 | user.s1 = ( String.valueOf((uid+"1").hashCode()).replaceAll("-", "1") );
93 | user.s2 = ( String.valueOf((uid+"2").hashCode()).replaceAll("-", "2") );
94 | user.s3 = ( String.valueOf((uid+"3").hashCode()).replaceAll("-","3") );
95 |
96 | db = FirebaseDatabase.getInstance().getReference();
97 | db.child("user").child(uid).setValue(user);
98 | }
99 | });
100 |
101 | });
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_package.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
32 |
33 |
44 |
45 |
59 |
60 |
77 |
78 |
92 |
93 |
109 |
110 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/ElectionResultsViewModel.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.app.Application;
4 | import android.os.CountDownTimer;
5 | import android.util.Log;
6 |
7 | import androidx.annotation.NonNull;
8 | import androidx.lifecycle.AndroidViewModel;
9 | import androidx.lifecycle.MutableLiveData;
10 | import androidx.lifecycle.ViewModel;
11 |
12 | import com.example.tkd.zvoting.model.Election;
13 | import com.example.tkd.zvoting.rest.ApiClient;
14 | import com.example.tkd.zvoting.rest.ApiInterface;
15 | import com.google.firebase.auth.FirebaseAuth;
16 | import com.google.firebase.database.DataSnapshot;
17 | import com.google.firebase.database.DatabaseError;
18 | import com.google.firebase.database.DatabaseReference;
19 | import com.google.firebase.database.FirebaseDatabase;
20 | import com.google.firebase.database.ValueEventListener;
21 |
22 | import java.util.ArrayList;
23 | import java.util.List;
24 | import java.util.TreeMap;
25 |
26 | import retrofit2.Call;
27 | import retrofit2.Callback;
28 | import retrofit2.Response;
29 |
30 | public class ElectionResultsViewModel extends AndroidViewModel {
31 | DataViewModel mDataViewModel;
32 | ApiInterface apiInterface;
33 | MutableLiveData> liveElections;
34 |
35 | MutableLiveData> liveMyElections;
36 |
37 | DatabaseReference db;
38 | FirebaseAuth firebaseAuth;
39 | MutableLiveData> liveMyElectionIds;
40 |
41 | public ElectionResultsViewModel(@NonNull Application application) {
42 | super(application);
43 | db = FirebaseDatabase.getInstance().getReference();
44 | firebaseAuth = FirebaseAuth.getInstance();
45 |
46 | mDataViewModel = DataViewModel.getInstance(application);
47 |
48 | liveElections = new MutableLiveData<>(new ArrayList<>());
49 | liveMyElections = new MutableLiveData<>(new ArrayList<>());
50 | liveMyElectionIds = new MutableLiveData<>(new ArrayList<>());
51 |
52 | mDataViewModel = DataViewModel.getInstance(application);
53 | apiInterface = ApiClient.getClient().create(ApiInterface.class);
54 |
55 |
56 | getElections();
57 |
58 | db.child("ownedElection").child(firebaseAuth.getUid()).addValueEventListener(new ValueEventListener() {
59 | @Override
60 | public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
61 | ArrayList myElectionIds = new ArrayList<>();
62 |
63 | for (DataSnapshot child : dataSnapshot.getChildren()) {
64 | myElectionIds.add(child.getKey());
65 | }
66 |
67 | liveMyElectionIds.setValue(myElectionIds);
68 |
69 | if (liveElections.getValue() != null && liveElections.getValue().size() > 0) {
70 | ArrayList myElections = new ArrayList<>();
71 |
72 | for (Election election : liveElections.getValue()) {
73 | if (myElectionIds.contains(election.getId())) {
74 | myElections.add(election);
75 | }
76 | }
77 | liveMyElections.setValue(myElections);
78 | }
79 | }
80 |
81 | @Override
82 | public void onCancelled(@NonNull DatabaseError databaseError) {
83 |
84 | }
85 | });
86 | }
87 |
88 | public void getElections() {
89 | Call> call = apiInterface.getElections();
90 | call.enqueue(new Callback>() {
91 | @Override
92 | public void onResponse(Call> call, Response> response) {
93 | List body = response.body();
94 |
95 | ArrayList elections = new ArrayList<>();
96 | elections.addAll(body);
97 |
98 | if (!elections.equals(liveElections.getValue())) {
99 | liveElections.setValue(elections);
100 | }
101 |
102 |
103 | if (liveMyElectionIds.getValue() != null && liveMyElectionIds.getValue().size() > 0) {
104 | ArrayList myElectionIds = liveMyElectionIds.getValue();
105 | ArrayList myElections = new ArrayList<>();
106 |
107 | for (Election election : elections) {
108 | if (myElectionIds.contains(election.getId())) {
109 | myElections.add(election);
110 | }
111 | }
112 | liveMyElections.setValue(myElections);
113 |
114 | }
115 | }
116 |
117 | @Override
118 | public void onFailure(Call> call, Throwable t) {
119 | Log.e("TKD", "Error: " + t);
120 | }
121 | });
122 |
123 | new CountDownTimer(10000, 1000) {
124 |
125 | @Override
126 | public void onTick(long millisUntilFinished) {
127 |
128 | }
129 |
130 | @Override
131 | public void onFinish() {
132 | getElections();
133 | }
134 | }.start();
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/OperationsFragment.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import androidx.appcompat.app.AlertDialog;
4 | import androidx.lifecycle.Observer;
5 | import androidx.lifecycle.ViewModelProviders;
6 |
7 | import android.app.ProgressDialog;
8 | import android.os.Bundle;
9 |
10 | import androidx.annotation.NonNull;
11 | import androidx.annotation.Nullable;
12 | import androidx.fragment.app.Fragment;
13 | import androidx.recyclerview.widget.RecyclerView;
14 |
15 | import android.view.LayoutInflater;
16 | import android.view.View;
17 | import android.view.ViewGroup;
18 | import android.widget.EditText;
19 |
20 | import com.example.tkd.zvoting.model.Election;
21 | import com.example.tkd.zvoting.rest.ApiClient;
22 | import com.example.tkd.zvoting.rest.ApiInterface;
23 | import com.example.tkd.zvoting.rest.CreateElectionRequest;
24 | import com.example.tkd.zvoting.rest.CreateElectionResponse;
25 | import com.google.android.material.snackbar.Snackbar;
26 |
27 | import java.util.ArrayList;
28 |
29 | import retrofit2.Call;
30 | import retrofit2.Callback;
31 | import retrofit2.Response;
32 |
33 | public class OperationsFragment extends Fragment {
34 |
35 | private OperationsViewModel mViewModel;
36 | AlertDialog alertDialog;
37 | DataViewModel mDataViewModel;
38 |
39 | ApiInterface apiInterface;
40 | View root;
41 | private RecyclerView list;
42 |
43 | public static OperationsFragment newInstance() {
44 | return new OperationsFragment();
45 | }
46 |
47 | private void displayAddElectionDialog() {
48 |
49 | AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
50 | // Get the layout inflater
51 | LayoutInflater inflater = requireActivity().getLayoutInflater();
52 |
53 | View layout = inflater.inflate(R.layout.add_election_layout, null);
54 | EditText editElectionName = (EditText) layout.findViewById(R.id.editElectionName);
55 | EditText editElectionDuration = (EditText) layout.findViewById(R.id.editElectionDuration);
56 |
57 | // Inflate and set the layout for the dialog
58 | // Pass null as the parent view because its going in the dialog layout
59 | builder.setView(layout)
60 | // Add action buttons
61 | .setPositiveButton("Create Election", (dialog, id) -> {
62 | String electionName=editElectionName.getText().toString();
63 | String electionDuration=editElectionDuration.getText().toString();
64 |
65 | ProgressDialog progress = new ProgressDialog(getContext());
66 | progress.setTitle("Loading");
67 | progress.setMessage("Wait while loading...");
68 | progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
69 | progress.show();
70 |
71 | apiInterface.createElection(new CreateElectionRequest(electionName, electionDuration)).enqueue(new Callback() {
72 | @Override
73 | public void onResponse(Call call, Response response) {
74 | Snackbar.make(root, "Election Created", Snackbar.LENGTH_LONG).show();
75 | progress.dismiss();
76 | }
77 |
78 | @Override
79 | public void onFailure(Call call, Throwable t) {
80 | Snackbar.make(root, "Error: " + t, Snackbar.LENGTH_LONG).show();
81 | progress.dismiss();
82 | }
83 | });
84 | })
85 | .setNegativeButton("Cancel", (dialog, id) -> {
86 | OperationsFragment.this.alertDialog.cancel();
87 | });
88 |
89 | alertDialog = builder.create();
90 | alertDialog.show();
91 | }
92 |
93 | @Override
94 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
95 | @Nullable Bundle savedInstanceState) {
96 | root = inflater.inflate(R.layout.operations_fragment, container, false);
97 |
98 | apiInterface = ApiClient.getClient().create(ApiInterface.class);
99 | list = root.findViewById(R.id.list);
100 |
101 | root.findViewById(R.id.btnAddElection).setOnClickListener(v -> displayAddElectionDialog());
102 | return root;
103 | }
104 |
105 | @Override
106 | public void onResume() {
107 | super.onResume();
108 | mDataViewModel.mainfragment.setValue(DataViewModel.ElectionResultsFragment);
109 |
110 |
111 | mViewModel.liveElections.observe(this, new Observer>() {
112 | @Override
113 | public void onChanged(ArrayList elections) {
114 | list.setAdapter(new OperationsAdapter(OperationsFragment.this, elections, mViewModel.mDataViewModel.liveUser.getValue()));
115 | }
116 | });
117 | }
118 |
119 | @Override
120 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
121 | super.onActivityCreated(savedInstanceState);
122 | mViewModel = ViewModelProviders.of(this).get(OperationsViewModel.class);
123 | mDataViewModel = DataViewModel.getInstance(null);
124 | }
125 |
126 | }
127 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/MasterActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.content.Intent;
4 |
5 | import androidx.annotation.NonNull;
6 | import androidx.appcompat.app.AppCompatActivity;
7 | import androidx.fragment.app.Fragment;
8 | import androidx.lifecycle.Observer;
9 | import androidx.lifecycle.ViewModelProviders;
10 | import androidx.viewpager.widget.ViewPager;
11 |
12 | import android.graphics.Typeface;
13 | import android.os.Bundle;
14 | import android.util.Log;
15 | import android.view.View;
16 | import android.widget.ImageView;
17 | import android.widget.TextView;
18 |
19 | import com.example.tkd.zvoting.dummy.DummyContent;
20 | import com.example.tkd.zvoting.model.User;
21 | import com.google.firebase.auth.FirebaseAuth;
22 |
23 | import java.util.ArrayList;
24 | import java.util.List;
25 |
26 | public class MasterActivity extends AppCompatActivity implements ElectionResultsFragment.OnListFragmentInteractionListener {
27 |
28 | TextView nameUser, emailUser, review, network, plugins, myapps, mainmenus;
29 |
30 | private FirebaseAuth firebaseAuth;
31 | private DataViewModel mDataViewModel;
32 | ImageView logoutIcon;
33 | View linkLogout, linkElections, linkMyElections, linkElectionResults;
34 | private ImageView electionsIcon, myElectionsIcon, electionResultsIcon;
35 | private TextView electionsText, myElectionsText, electionResultsText;
36 |
37 | ViewPager viewPager;
38 | MasterPageAdapter pageAdapter;
39 |
40 | private void initializeViews() {
41 | //header section
42 | nameUser = findViewById(R.id.nameuser);
43 | emailUser = findViewById(R.id.walletuser);
44 |
45 | //main menu
46 | linkElections = findViewById(R.id.linkElections);
47 | electionsIcon = findViewById(R.id.electionsIcon);
48 | electionsText = findViewById(R.id.electionsText);
49 |
50 | linkMyElections = findViewById(R.id.linkMyElections);
51 | myElectionsIcon = findViewById(R.id.myElectionsIcon);
52 | myElectionsText = findViewById(R.id.myElectionsText);
53 |
54 | linkElectionResults = findViewById(R.id.linkElectionResults);
55 | electionResultsIcon = findViewById(R.id.electionResultsIcon);
56 | electionResultsText = findViewById(R.id.electionResultsText);
57 |
58 | linkLogout = findViewById(R.id.linkLogout);
59 | logoutIcon = findViewById(R.id.logoutIcon);
60 |
61 | viewPager = findViewById(R.id.viewPager);
62 |
63 | }
64 |
65 | @Override
66 | protected void onCreate(Bundle savedInstanceState) {
67 | super.onCreate(savedInstanceState);
68 | setContentView(R.layout.activity_master);
69 |
70 | DataViewModelFactory factory = new DataViewModelFactory(getApplication());
71 | mDataViewModel = ViewModelProviders.of(this, factory).get(DataViewModel.class);
72 |
73 | firebaseAuth = FirebaseAuth.getInstance();
74 | firebaseAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
75 | @Override
76 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
77 | if (firebaseAuth.getCurrentUser() == null) {
78 | startActivity(new Intent(MasterActivity.this, AuthActivity.class));
79 | finish();
80 | }
81 | }
82 | });
83 |
84 | mDataViewModel.activity.setValue("MasterActivity");
85 | mDataViewModel.mainfragment.observe(this, new Observer() {
86 | @Override
87 | public void onChanged(String s) {
88 | Log.e("TKD", s);
89 | electionsText.setTypeface(null, (s.equals(DataViewModel.ElectionsFragment)? Typeface.BOLD:Typeface.NORMAL));
90 | myElectionsText.setTypeface(null, (s.equals(DataViewModel.MyElectionsFragment)? Typeface.BOLD:Typeface.NORMAL));
91 | electionResultsText.setTypeface(null, (s.equals(DataViewModel.ElectionResultsFragment)? Typeface.BOLD:Typeface.NORMAL));
92 | }
93 | });
94 |
95 | initializeViews();
96 |
97 | List fragments= createFragments();
98 | pageAdapter = new MasterPageAdapter(getSupportFragmentManager(), fragments);
99 | viewPager.setAdapter(pageAdapter);
100 |
101 | viewPager.setCurrentItem(0);
102 |
103 | mDataViewModel.liveUser.observe(this, new Observer() {
104 | @Override
105 | public void onChanged(User user) {
106 | nameUser.setText(user.name);
107 | emailUser.setText(user.email);
108 | }
109 | });
110 |
111 |
112 | linkElections.setOnClickListener(v->viewPager.setCurrentItem(0, true));
113 | linkMyElections.setOnClickListener(v->viewPager.setCurrentItem(1, true));
114 | linkElectionResults.setOnClickListener(v->viewPager.setCurrentItem(2, true));
115 |
116 | linkLogout.setOnClickListener((v) -> {
117 | mDataViewModel.firebaseAuth.signOut();
118 | });
119 | }
120 |
121 | private List createFragments() {
122 | List fragments = new ArrayList<>();
123 | fragments.add(ElectionsFragment.newInstance());
124 | fragments.add(MyElectionsFragment.newInstance());
125 | fragments.add(OperationsFragment.newInstance());
126 | return fragments;
127 | }
128 |
129 | @Override
130 | public void onListFragmentInteraction(DummyContent.DummyItem item) {
131 |
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/ElectionResultsFragment.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.content.Context;
4 | import android.content.DialogInterface;
5 | import android.os.Bundle;
6 |
7 | import androidx.annotation.Nullable;
8 | import androidx.appcompat.app.AlertDialog;
9 | import androidx.fragment.app.Fragment;
10 | import androidx.lifecycle.ViewModelProviders;
11 | import androidx.recyclerview.widget.GridLayoutManager;
12 | import androidx.recyclerview.widget.LinearLayoutManager;
13 | import androidx.recyclerview.widget.RecyclerView;
14 |
15 | import android.util.Log;
16 | import android.view.LayoutInflater;
17 | import android.view.View;
18 | import android.view.ViewGroup;
19 | import android.widget.EditText;
20 |
21 | import com.example.tkd.zvoting.dummy.DummyContent;
22 | import com.example.tkd.zvoting.dummy.DummyContent.DummyItem;
23 | import com.example.tkd.zvoting.model.ElectionResult;
24 | import com.google.android.material.floatingactionbutton.FloatingActionButton;
25 |
26 | import java.util.List;
27 |
28 | import static android.content.Context.LAYOUT_INFLATER_SERVICE;
29 |
30 | /**
31 | * A fragment representing a list of Items.
32 | *
33 | * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
34 | * interface.
35 | */
36 | public class ElectionResultsFragment extends Fragment {
37 |
38 | // TODO: Customize parameter argument names
39 | private static final String ARG_COLUMN_COUNT = "column-count";
40 | // TODO: Customize parameters
41 | private int mColumnCount = 2;
42 | private OnListFragmentInteractionListener mListener;
43 | private ElectionResultsViewModel mViewModel;
44 |
45 | FloatingActionButton btnAddElection;
46 | AlertDialog alertDialog;
47 |
48 | /**
49 | * Mandatory empty constructor for the fragment manager to instantiate the
50 | * fragment (e.g. upon screen orientation changes).
51 | */
52 | public ElectionResultsFragment() {
53 | }
54 |
55 | // TODO: Customize parameter initialization
56 | @SuppressWarnings("unused")
57 | public static ElectionResultsFragment newInstance(int columnCount) {
58 | ElectionResultsFragment fragment = new ElectionResultsFragment();
59 | Bundle args = new Bundle();
60 | args.putInt(ARG_COLUMN_COUNT, columnCount);
61 | fragment.setArguments(args);
62 | return fragment;
63 | }
64 |
65 | @Override
66 | public void onCreate(Bundle savedInstanceState) {
67 | super.onCreate(savedInstanceState);
68 |
69 | if (getArguments() != null) {
70 | mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
71 | }
72 | }
73 |
74 | @Override
75 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
76 | Bundle savedInstanceState) {
77 | View root = inflater.inflate(R.layout.fragment_item_list, container, false);
78 | // root.findViewById(R.id.btnAddElection).setOnClickListener(v->{
79 | // displayAddElectionDialog();
80 | // });
81 |
82 | View view = root.findViewById(R.id.list);
83 |
84 | // Set the adapter
85 | if (view instanceof RecyclerView) {
86 | Context context = view.getContext();
87 | RecyclerView recyclerView = (RecyclerView) view;
88 | if (mColumnCount <= 1) {
89 | recyclerView.setLayoutManager(new LinearLayoutManager(context));
90 | } else {
91 | recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
92 | }
93 |
94 |
95 | recyclerView.setAdapter(new MyItemRecyclerViewAdapter(DummyContent.ITEMS, mListener));
96 | }
97 | return view;
98 | }
99 |
100 |
101 | @Override
102 | public void onAttach(Context context) {
103 | super.onAttach(context);
104 | if (context instanceof OnListFragmentInteractionListener) {
105 | mListener = (OnListFragmentInteractionListener) context;
106 | } else {
107 | throw new RuntimeException(context.toString()
108 | + " must implement OnListFragmentInteractionListener");
109 | }
110 | }
111 |
112 | @Override
113 | public void onDetach() {
114 | super.onDetach();
115 | mListener = null;
116 | }
117 |
118 | @Override
119 | public void onResume() {
120 | super.onResume();
121 | mViewModel.mDataViewModel.mainfragment.setValue(DataViewModel.ElectionResultsFragment);
122 | }
123 |
124 | @Override
125 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
126 | super.onActivityCreated(savedInstanceState);
127 | mViewModel = ViewModelProviders.of(this).get(ElectionResultsViewModel.class);
128 | }
129 |
130 | /**
131 | * This interface must be implemented by activities that contain this
132 | * fragment to allow an interaction in this fragment to be communicated
133 | * to the activity and potentially other fragments contained in that
134 | * activity.
135 | *
136 | * See the Android Training lesson Communicating with Other Fragments for more information.
139 | */
140 | public interface OnListFragmentInteractionListener {
141 | // TODO: Update argument type and name
142 | void onListFragmentInteraction(DummyItem item);
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/ElectionListAdapter.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.view.LayoutInflater;
4 | import android.view.View;
5 | import android.view.ViewGroup;
6 | import android.widget.Button;
7 | import android.widget.TextView;
8 |
9 | import androidx.annotation.NonNull;
10 | import androidx.fragment.app.Fragment;
11 | import androidx.recyclerview.widget.RecyclerView;
12 |
13 | import com.example.tkd.zvoting.model.Election;
14 | import com.example.tkd.zvoting.model.ResponseMessage;
15 | import com.example.tkd.zvoting.model.User;
16 | import com.example.tkd.zvoting.rest.AddCandidateRequest;
17 | import com.example.tkd.zvoting.rest.AddVoterRequest;
18 | import com.example.tkd.zvoting.rest.ApiClient;
19 | import com.example.tkd.zvoting.rest.ApiInterface;
20 | import com.google.android.material.snackbar.Snackbar;
21 | import com.google.firebase.auth.FirebaseAuth;
22 | import com.google.firebase.database.DatabaseReference;
23 | import com.google.firebase.database.FirebaseDatabase;
24 |
25 | import java.util.ArrayList;
26 |
27 | import retrofit2.Call;
28 | import retrofit2.Callback;
29 | import retrofit2.Response;
30 |
31 | class ElectionListAdapter extends RecyclerView.Adapter {
32 |
33 | class ViewHolder extends RecyclerView.ViewHolder {
34 | View v;
35 | TextView electionNameTxt;
36 | Button btnAddCandidate;
37 | Button btnAddVoter;
38 |
39 | public ViewHolder(@NonNull View itemView) {
40 | super(itemView);
41 | v = itemView;
42 | electionNameTxt = v.findViewById(R.id.txtElectionName);
43 | btnAddCandidate = v.findViewById(R.id.btnAddCandidate);
44 | btnAddVoter = v.findViewById(R.id.btnAddVoter);
45 | }
46 | }
47 |
48 | User user;
49 | ArrayList elections;
50 | Fragment context;
51 | ApiInterface apiInterface;
52 | DataViewModel mDataViewModel;
53 | AddCandidateRequest addCandidateRequest;
54 | View clickedView;
55 | DatabaseReference db;
56 | FirebaseAuth firebaseAuth;
57 |
58 | public ElectionListAdapter(Fragment context, ArrayList elections, User user) {
59 | this.context = context;
60 | this.elections = elections;
61 | this.user = user;
62 | apiInterface = ApiClient.getClient().create(ApiInterface.class);
63 | mDataViewModel = DataViewModel.getInstance(null);
64 | db = FirebaseDatabase.getInstance().getReference();
65 | firebaseAuth = FirebaseAuth.getInstance();
66 | }
67 |
68 | @NonNull
69 | @Override
70 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
71 | return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.election_item, parent, false));
72 | }
73 |
74 | @Override
75 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
76 | Election election = elections.get(position);
77 | holder.electionNameTxt.setText(election.getName());
78 |
79 |
80 | holder.btnAddCandidate.setOnClickListener((v) -> {
81 | clickedView = v;
82 |
83 | if (firebaseAuth.getUid() != null)
84 | db.child("ownElection").child(firebaseAuth.getUid()).child(elections.get(position).getId()).setValue(elections.get(position));
85 |
86 | String imgAddress = "https://i7.pngguru.com/preview/1001/200/876/voting-election-computer-icons-electoral-symbol-politics-politics.jpg";
87 | addCandidateRequest = new AddCandidateRequest(user.name, user.name, imgAddress, elections.get(position).getId());
88 |
89 | Call responseMessageCall = apiInterface.addCandidate(addCandidateRequest);
90 | responseMessageCall.enqueue(new Callback() {
91 | @Override
92 | public void onResponse(Call call, Response response) {
93 | Snackbar.make(clickedView, "Candidate added", Snackbar.LENGTH_LONG).show();
94 | }
95 |
96 | @Override
97 | public void onFailure(Call call, Throwable t) {
98 | Snackbar.make(clickedView, "Failure: " + t, Snackbar.LENGTH_LONG).show();
99 | }
100 | });
101 | });
102 |
103 | holder.btnAddVoter.setOnClickListener((v) -> {
104 | clickedView = v;
105 |
106 | Long n = DataViewModel.n;
107 |
108 | long s1 = Long.parseLong(user.s1);
109 | String v1 = calculateV(n, s1);
110 |
111 | long s2 = Long.parseLong(user.s2);
112 | String v2 = calculateV(n, s2);
113 |
114 | long s3 = Long.parseLong(user.s3);
115 | String v3 = calculateV(n, s3);
116 |
117 |
118 | if (firebaseAuth.getUid() != null)
119 | db.child("ownElection").child(firebaseAuth.getUid()).child(elections.get(position).getId()).setValue(elections.get(position));
120 |
121 | AddVoterRequest addVoterRequest = new AddVoterRequest(user.name, user.email, v1, v2, v3, elections.get(position).getId());
122 |
123 | Call responseMessageCall = apiInterface.registerVoter(addVoterRequest);
124 | responseMessageCall.enqueue(new Callback() {
125 | @Override
126 | public void onResponse(Call call, Response response) {
127 | Snackbar.make(clickedView, "Voter Registration Successful", Snackbar.LENGTH_LONG).show();
128 | }
129 |
130 | @Override
131 | public void onFailure(Call call, Throwable t) {
132 | Snackbar.make(clickedView, "Failure: " + t, Snackbar.LENGTH_LONG).show();
133 | }
134 | });
135 |
136 | });
137 | }
138 |
139 | private static String calculateV(Long n, long s1) {
140 | s1 %= n;
141 | s1 += n;
142 | s1 %= n;
143 |
144 | long v1 = (s1 * s1) % n;
145 | return String.valueOf(v1);
146 | }
147 |
148 | @Override
149 | public int getItemCount() {
150 | return elections.size();
151 | }
152 |
153 |
154 | }
155 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/MyElectionsViewModel.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.app.Application;
4 | import android.os.CountDownTimer;
5 | import android.util.Log;
6 |
7 | import androidx.annotation.NonNull;
8 | import androidx.lifecycle.AndroidViewModel;
9 | import androidx.lifecycle.MutableLiveData;
10 | import androidx.lifecycle.ViewModel;
11 |
12 | import com.example.tkd.zvoting.model.Candidate;
13 | import com.example.tkd.zvoting.model.Election;
14 | import com.example.tkd.zvoting.rest.ApiClient;
15 | import com.example.tkd.zvoting.rest.ApiInterface;
16 | import com.example.tkd.zvoting.rest.GetCandidatesRequest;
17 | import com.google.firebase.auth.FirebaseAuth;
18 | import com.google.firebase.database.DataSnapshot;
19 | import com.google.firebase.database.DatabaseError;
20 | import com.google.firebase.database.DatabaseReference;
21 | import com.google.firebase.database.FirebaseDatabase;
22 | import com.google.firebase.database.ValueEventListener;
23 |
24 | import java.util.ArrayList;
25 | import java.util.List;
26 | import java.util.TreeMap;
27 |
28 | import retrofit2.Call;
29 | import retrofit2.Callback;
30 | import retrofit2.Response;
31 |
32 | public class MyElectionsViewModel extends AndroidViewModel {
33 | DataViewModel mDataViewModel;
34 |
35 | MutableLiveData> liveElections;
36 | MutableLiveData>> liveMyElectionsCandidates;
37 | ApiInterface apiInterface;
38 |
39 | MutableLiveData> liveMyElections;
40 |
41 | DatabaseReference db;
42 | FirebaseAuth firebaseAuth;
43 | private MutableLiveData> liveMyElectionIds;
44 |
45 | public MyElectionsViewModel(@NonNull Application application) {
46 | super(application);
47 | db = FirebaseDatabase.getInstance().getReference();
48 | firebaseAuth = FirebaseAuth.getInstance();
49 |
50 | mDataViewModel = DataViewModel.getInstance(application);
51 |
52 | liveElections = new MutableLiveData<>(new ArrayList<>());
53 | liveMyElections = new MutableLiveData<>(new ArrayList<>());
54 | liveMyElectionsCandidates = new MutableLiveData<>(new TreeMap<>());
55 | liveMyElectionIds = new MutableLiveData<>(new ArrayList<>());
56 |
57 | apiInterface = ApiClient.getClient().create(ApiInterface.class);
58 |
59 | getElections();
60 |
61 |
62 | db.child("ownElection").child(firebaseAuth.getUid()).addValueEventListener(new ValueEventListener() {
63 | @Override
64 | public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
65 | ArrayList myElectionIds = new ArrayList<>();
66 |
67 | for (DataSnapshot child : dataSnapshot.getChildren()) {
68 | myElectionIds.add(child.getKey());
69 | }
70 |
71 | liveMyElectionIds.setValue(myElectionIds);
72 |
73 | if (liveElections.getValue() != null && liveElections.getValue().size() > 0) {
74 | ArrayList myElections = new ArrayList<>();
75 |
76 | for (Election election : liveElections.getValue()) {
77 | if (myElectionIds.contains(election.getId())) {
78 | myElections.add(election);
79 | }
80 | }
81 | liveMyElections.setValue(myElections);
82 | }
83 | }
84 |
85 | @Override
86 | public void onCancelled(@NonNull DatabaseError databaseError) {
87 |
88 | }
89 | });
90 | }
91 |
92 | // private void getCandidates(String key) {
93 | // Call> call = apiInterface.getCandidates(new GetCandidatesRequest(key));
94 | // call.enqueue(new Callback>() {
95 | // @Override
96 | // public void onResponse(Call> call, Response> response) {
97 | // assert response.body() != null;
98 | // ArrayList candidates = new ArrayList<>(response.body());
99 | //
100 | // if(candidates.size()>0) {
101 | // String key = candidates.get(0).getElectionID();
102 | // liveMyElectionsCandidates.getValue().put(key, candidates);
103 | // }
104 | //
105 | // }
106 | //
107 | // @Override
108 | // public void onFailure(Call> call, Throwable t) {
109 | //
110 | // }
111 | // });
112 | // }
113 |
114 | public void getElections() {
115 | Call> call = apiInterface.getElections();
116 | call.enqueue(new Callback>() {
117 | @Override
118 | public void onResponse(Call> call, Response> response) {
119 | List body = response.body();
120 |
121 | ArrayList elections = new ArrayList<>();
122 | elections.addAll(body);
123 |
124 | if (!elections.equals(liveElections.getValue())) {
125 | liveElections.setValue(elections);
126 | }
127 |
128 |
129 |
130 | if (liveMyElectionIds.getValue() != null && liveMyElectionIds.getValue().size() > 0) {
131 | ArrayList myElectionIds = liveMyElectionIds.getValue();
132 | ArrayList myElections = new ArrayList<>();
133 |
134 | for (Election election : elections) {
135 | if (myElectionIds.contains(election.getId())) {
136 | myElections.add(election);
137 | }
138 | }
139 | liveMyElections.setValue(myElections);
140 |
141 | }
142 | }
143 |
144 | @Override
145 | public void onFailure(Call> call, Throwable t) {
146 | Log.e("TKD", "Error: " + t);
147 | }
148 | });
149 |
150 | new CountDownTimer(10000, 1000) {
151 |
152 | @Override
153 | public void onTick(long millisUntilFinished) {
154 |
155 | }
156 |
157 | @Override
158 | public void onFinish() {
159 | getElections();
160 | }
161 | }.start();
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_master.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
21 |
22 |
23 |
32 |
33 |
45 |
46 |
58 |
59 |
75 |
76 |
85 |
86 |
96 |
97 |
103 |
104 |
112 |
113 |
114 |
115 |
125 |
126 |
132 |
133 |
141 |
142 |
143 |
144 |
154 |
155 |
161 |
162 |
171 |
172 |
173 |
174 |
184 |
185 |
191 |
192 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
218 |
219 |
220 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/tkd/zvoting/MyElectionsListAdapter.java:
--------------------------------------------------------------------------------
1 | package com.example.tkd.zvoting;
2 |
3 | import android.app.Dialog;
4 | import android.content.DialogInterface;
5 | import android.os.CountDownTimer;
6 | import android.util.Log;
7 | import android.view.LayoutInflater;
8 | import android.view.View;
9 | import android.view.ViewGroup;
10 | import android.widget.Button;
11 | import android.widget.TextView;
12 | import android.widget.Toast;
13 |
14 | import androidx.annotation.NonNull;
15 | import androidx.appcompat.app.AlertDialog;
16 | import androidx.fragment.app.Fragment;
17 | import androidx.recyclerview.widget.RecyclerView;
18 |
19 | import com.example.tkd.zvoting.model.Candidate;
20 | import com.example.tkd.zvoting.model.Election;
21 | import com.example.tkd.zvoting.model.ElectionResult;
22 | import com.example.tkd.zvoting.model.LoginChallenge;
23 | import com.example.tkd.zvoting.model.User;
24 | import com.example.tkd.zvoting.rest.AddCandidateRequest;
25 | import com.example.tkd.zvoting.rest.ApiClient;
26 | import com.example.tkd.zvoting.rest.ApiInterface;
27 | import com.example.tkd.zvoting.rest.CalculateResultRequest;
28 | import com.example.tkd.zvoting.rest.CastVoteRequest;
29 | import com.example.tkd.zvoting.rest.CastVoteResponse;
30 | import com.example.tkd.zvoting.rest.GetCandidatesRequest;
31 | import com.example.tkd.zvoting.rest.LoginResponse;
32 | import com.example.tkd.zvoting.rest.VoterLoginRequest;
33 | import com.google.android.material.snackbar.Snackbar;
34 | import com.google.firebase.auth.FirebaseAuth;
35 | import com.google.firebase.database.DatabaseReference;
36 | import com.google.firebase.database.FirebaseDatabase;
37 | import com.google.gson.Gson;
38 |
39 | import java.util.ArrayList;
40 | import java.util.List;
41 | import java.util.Random;
42 | import java.util.concurrent.TimeUnit;
43 |
44 | import retrofit2.Call;
45 | import retrofit2.Callback;
46 | import retrofit2.Response;
47 |
48 | class MyElectionsListAdapter extends RecyclerView.Adapter {
49 |
50 | private ElectionResult electionResult;
51 |
52 | class ViewHolder extends RecyclerView.ViewHolder {
53 | View v;
54 | TextView electionNameTxt;
55 | TextView txtElectionStatus;
56 | Button btnVote;
57 |
58 | public ViewHolder(@NonNull View itemView) {
59 | super(itemView);
60 | v = itemView;
61 | electionNameTxt = v.findViewById(R.id.txtElectionName);
62 | txtElectionStatus = v.findViewById(R.id.txtElectionStatus);
63 | btnVote = v.findViewById(R.id.btnVote);
64 | }
65 | }
66 |
67 | User user;
68 | ArrayList elections;
69 | Fragment context;
70 | ApiInterface apiInterface;
71 | DataViewModel mDataViewModel;
72 | AddCandidateRequest addCandidateRequest;
73 | View clickedView;
74 | DatabaseReference db;
75 | FirebaseAuth firebaseAuth;
76 | int pos;
77 |
78 | public MyElectionsListAdapter(Fragment context, ArrayList elections, User user) {
79 | this.context = context;
80 | this.elections = elections;
81 | this.user = user;
82 | apiInterface = ApiClient.getClient().create(ApiInterface.class);
83 | mDataViewModel = DataViewModel.getInstance(null);
84 | db = FirebaseDatabase.getInstance().getReference();
85 | firebaseAuth = FirebaseAuth.getInstance();
86 | }
87 |
88 | private int checkedItem;
89 | private String[] candidateData;
90 | Dialog alertDialog = null;
91 |
92 |
93 | private void displayResultDialog(ElectionResult data) {
94 |
95 |
96 | AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context.getActivity());
97 |
98 | dialogBuilder.setTitle("Here is the election result");
99 |
100 | String[] results = new String[data.getCandidates().size()];
101 | for (int i = 0; i < results.length; i++) {
102 | results[i] = data.getCandidates().get(i).getName() + " got " + data.getValues().get(i) + " votes.";
103 | }
104 |
105 | dialogBuilder.setItems(results, (dialog, which) -> {
106 |
107 | });
108 |
109 | Log.e("TKD", "total candidates: " + results.length);
110 |
111 | dialogBuilder.setPositiveButton("ok", (dialog, which) -> {
112 | });
113 | dialogBuilder.setNegativeButton("Cancel", (dialog, which) -> {
114 | });
115 |
116 | alertDialog = dialogBuilder.create();
117 | alertDialog.show();
118 | }
119 |
120 | private void displayVoteDialog(ArrayList data, Election election) {
121 | String[] names = new String[data.size()];
122 | for (int i = 0; i < data.size(); i++) {
123 | names[i] = data.get(i).getName();
124 | }
125 | candidateData = names;
126 |
127 | AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context.getActivity());
128 |
129 | dialogBuilder.setTitle("Whom do you want to vote for?");
130 |
131 | dialogBuilder.setSingleChoiceItems(candidateData, checkedItem,
132 | (dialogInterface, which) -> {
133 | checkedItem = which;
134 | });
135 | dialogBuilder.setPositiveButton("Vote Now", (dialog, which) -> castVote(election));
136 | dialogBuilder.setNegativeButton("Cancel", (dialog, which) -> cancelDialog());
137 |
138 | alertDialog = dialogBuilder.create();
139 | alertDialog.show();
140 | }
141 |
142 | private void cancelDialog() {
143 | //Toast.makeText(context.getActivity(), "You selected: " + candidateData[checkedItem], Toast.LENGTH_SHORT).show();
144 | }
145 |
146 | long bigmod(long base, long power, long n) {
147 | if (power == 0) return 1 % n;
148 | if (power % 2 == 1) return (base * bigmod(base, power - 1, n)) % n;
149 | long rt = bigmod(base, power / 2, n);
150 | return (rt * rt) % n;
151 | }
152 |
153 | private void castVote(Election election) {
154 | apiInterface.getLoginChallenge().enqueue(new Callback() {
155 | @Override
156 | public void onResponse(Call call, Response response) {
157 | LoginChallenge loginChallenge = response.body();
158 | long a1 = loginChallenge.getA1();
159 | long a2 = loginChallenge.getA2();
160 | long a3 = loginChallenge.getA3();
161 |
162 | long n = DataViewModel.n;
163 |
164 | User user = mDataViewModel.liveUser.getValue();
165 |
166 | String email = user.email;
167 |
168 | long r = new Random(System.currentTimeMillis()).nextLong();
169 | r %= n;
170 |
171 | long x = (r * r) % n;
172 |
173 | long s1 = Long.parseLong(user.s1), s2 = Long.parseLong(user.s2), s3 = Long.parseLong(user.s3);
174 | s1 %= n;
175 | s2 %= n;
176 | s3 %= n;
177 |
178 | long v1 = (s1 * s1) % n, v2 = (s2 * s2) % n, v3 = (s3 * s3) % n;
179 |
180 | long y1 = r;
181 | y1 *= bigmod(s1, a1, n);
182 | y1 %= n;
183 | y1 *= bigmod(s2, a2, n);
184 | y1 %= n;
185 | y1 *= bigmod(s3, a3, n);
186 | y1 %= n;
187 |
188 | VoterLoginRequest voterLoginRequest;
189 | voterLoginRequest = new VoterLoginRequest(email, x, a1, a2, a3, v1, v2, v3, y1);
190 |
191 | apiInterface.voterLogin(voterLoginRequest).enqueue(new Callback() {
192 | @Override
193 | public void onResponse(Call call, Response response) {
194 | Log.e("TKD", "LOGIN SUCCESSFUL");
195 |
196 | Gson gson = new Gson();
197 |
198 | int[] voteContent = new int[candidateData.length];
199 | voteContent[checkedItem] = 1;
200 |
201 | Log.e("TKD", gson.toJson(voteContent));
202 |
203 | CastVoteRequest castVoteRequest = new CastVoteRequest(user.email, election.getId(), gson.toJson(voteContent));
204 | apiInterface.castVote(castVoteRequest).enqueue(new Callback() {
205 | @Override
206 | public void onResponse(Call call, Response response) {
207 | if (response.body().getStatus().equals("Successful"))
208 | Snackbar.make(clickedView, "Vote Cast Successful", Snackbar.LENGTH_LONG).show();
209 | }
210 |
211 | @Override
212 | public void onFailure(Call call, Throwable t) {
213 |
214 | }
215 | });
216 | }
217 |
218 | @Override
219 | public void onFailure(Call call, Throwable t) {
220 |
221 | }
222 | });
223 |
224 | }
225 |
226 | @Override
227 | public void onFailure(Call call, Throwable t) {
228 |
229 | }
230 | });
231 | Toast.makeText(context.getActivity(), "You selected: " + candidateData[checkedItem], Toast.LENGTH_SHORT).show();
232 | }
233 |
234 | @NonNull
235 | @Override
236 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
237 | return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_election_item, parent, false));
238 | }
239 |
240 | @Override
241 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
242 | pos = position;
243 | Election election = elections.get(position);
244 | holder.electionNameTxt.setText(election.getName());
245 |
246 |
247 | holder.btnVote.setOnClickListener(v -> {
248 | clickedView = v;
249 | if (election.isOver()) {
250 | apiInterface.calculateResult(new CalculateResultRequest(election.getId())).enqueue(new Callback() {
251 | @Override
252 | public void onResponse(Call call, Response response) {
253 | electionResult = response.body();
254 | displayResultDialog(electionResult);
255 | }
256 |
257 | @Override
258 | public void onFailure(Call call, Throwable t) {
259 |
260 | }
261 | });
262 | } else if (election.isRunning()) {
263 |
264 | Call> call = apiInterface.getCandidates(new GetCandidatesRequest(election.getId()));
265 | call.enqueue(new Callback>() {
266 | @Override
267 | public void onResponse(Call> call, Response> response) {
268 | ArrayList candidates = new ArrayList<>(response.body());
269 | displayVoteDialog(candidates, election);
270 | }
271 |
272 | @Override
273 | public void onFailure(Call> call, Throwable t) {
274 |
275 | }
276 | });
277 | }
278 | });
279 |
280 |
281 | if (election.isFresh()) {
282 | holder.btnVote.setText("Coming!!!");
283 | holder.btnVote.setEnabled(false);
284 | holder.txtElectionStatus.setText("Election hasn't started yet...");
285 | }
286 |
287 | if (election.isOver()) {
288 | holder.btnVote.setText("View Result");
289 | holder.btnVote.setEnabled(true);
290 | holder.txtElectionStatus.setText("Election is over...");
291 | }
292 |
293 | if (election.isRunning()) {
294 | holder.btnVote.setText("Vote Now");
295 | holder.btnVote.setEnabled(true);
296 | final TextView electionStatus = holder.txtElectionStatus;
297 | String statusTxt = "Election Running...";
298 | electionStatus.setText(statusTxt);
299 |
300 |
301 | long timeRemaining = election.getRemainingTime();
302 |
303 | new CountDownTimer(timeRemaining * 1000, 1000) {
304 | @Override
305 | public void onTick(long millisUntilFinished) {
306 | long seconds = millisUntilFinished / 1000;
307 |
308 | int day = (int) TimeUnit.SECONDS.toDays(seconds);
309 | long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24);
310 | long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60);
311 | long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60);
312 |
313 | String statusTxt = "Election Running. " + day + " days " + hours + ":" + minute + ":" + second + " remaining";
314 |
315 | electionStatus.setText(statusTxt);
316 | }
317 |
318 | @Override
319 | public void onFinish() {
320 | electionStatus.setText("Finished");
321 | }
322 | }.start();
323 | }
324 | }
325 |
326 | private static String calculateV(Long n, long s1) {
327 | s1 %= n;
328 | s1 += n;
329 | s1 %= n;
330 |
331 | long v1 = (s1 * s1) % n;
332 | return String.valueOf(v1);
333 | }
334 |
335 | @Override
336 | public int getItemCount() {
337 | return elections.size();
338 | }
339 |
340 |
341 | }
342 |
--------------------------------------------------------------------------------