From 2786f650eedc256199829724e7a947d73040471e Mon Sep 17 00:00:00 2001 From: asfi50 Date: Sat, 11 May 2024 02:22:04 +0600 Subject: [PATCH 1/4] get contractor by id 2 --- .../src/controllers/contractor.controller.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/express-server/src/controllers/contractor.controller.ts b/express-server/src/controllers/contractor.controller.ts index c291315..1af3a86 100644 --- a/express-server/src/controllers/contractor.controller.ts +++ b/express-server/src/controllers/contractor.controller.ts @@ -146,6 +146,23 @@ router.get('/contractor/:id', auth.required, async (req: Request, res: Response) } }); +router.get('/contractor2/:id', auth.required, async (req: Request, res: Response) => { + try { + const contractor = await prisma.contractor.findUnique({ + where: { + id: Number(req.params.id) + }, + include: { + managers: true, + employees: true, + } + }); + res.status(200).json(contractor); + } catch (error) { + res.status(400).json({ message: error.message }); + } +}); + // delete a contractor by id router.delete('/contractor/:id', auth.required,auth.isSystemAdmin, async (req: Request, res: Response) => { try { From bd084dba25a7a34d67abc3851cda5b5c4c89cbda Mon Sep 17 00:00:00 2001 From: JHM69 Date: Fri, 10 May 2024 14:44:44 -0700 Subject: [PATCH 2/4] App Notification and Issue Implemented --- .../ui/activities/issue/Address.java | 0 .../ui/activities/issue/Example.java | 0 .../activities/issue/GeocodingResponse.java | 0 .../activities/issue/GoogleMapsApiClient.java | 0 .../issue/GoogleMapsApiService.java | 0 .../activities/issue/OpenMapsApiClient.java | 32 + .../activities/issue/OpenMapsApiService.java | 13 + .../activities/{ => nearbysts}/MapView.java | 0 .../ui/activities/nearbysts/NearbySts.java | 147 ++ .../nearbysts/NearbyStsService.java | 0 .../activities/nearbysts/RetrofitClient.java | 0 .../ui/activities/quiz/AnimatorListener.java | 21 - .../ui/activities/quiz/BattleModel.java | 134 -- .../ui/activities/quiz/PlayQuiz.java | 210 --- .../ui/activities/quiz/Player.java | 1 - .../ui/activities/quiz/QuizBattle.java | 1253 ----------------- .../ui/activities/quiz/Ranking.java | 1 - .../ui/activities/quiz/Result.java | 102 -- .../ui/activities/quiz/ResultActivity.java | 417 ------ .../ui/activities/quiz/SelectTopic.java | 156 -- .../ui/activities/quiz/StepView.java | 996 ------------- .../ui/activities/quiz/SubTopic.java | 110 -- .../{friends => volunteer}/FriendProfile.java | 0 .../ui/activities/volunteer/Ranking.java | 1 + .../SearchUsersActivity.java | 0 .../{friends => volunteer}/quiz_history.java | 0 .../main/res/drawable/border_background.xml | 4 + .../res/layout/activity_issue_details.xml | 0 .../app/src/main/res/layout/frag_admin.xml | 0 android-app/app/src/main/res/xml/issue.xml | 0 30 files changed, 197 insertions(+), 3401 deletions(-) create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/Address.java create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/Example.java create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GeocodingResponse.java create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GoogleMapsApiClient.java create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GoogleMapsApiService.java create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/OpenMapsApiClient.java create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/OpenMapsApiService.java rename android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/{ => nearbysts}/MapView.java (100%) create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/NearbySts.java create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/NearbyStsService.java create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/RetrofitClient.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/AnimatorListener.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/BattleModel.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/PlayQuiz.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Player.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/QuizBattle.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Ranking.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Result.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/ResultActivity.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/SelectTopic.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/StepView.java delete mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/SubTopic.java rename android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/{friends => volunteer}/FriendProfile.java (100%) create mode 100644 android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/Ranking.java rename android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/{friends => volunteer}/SearchUsersActivity.java (100%) rename android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/{friends => volunteer}/quiz_history.java (100%) create mode 100644 android-app/app/src/main/res/drawable/border_background.xml create mode 100644 android-app/app/src/main/res/layout/activity_issue_details.xml create mode 100644 android-app/app/src/main/res/layout/frag_admin.xml create mode 100644 android-app/app/src/main/res/xml/issue.xml diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/Address.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/Address.java new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/Example.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/Example.java new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GeocodingResponse.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GeocodingResponse.java new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GoogleMapsApiClient.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GoogleMapsApiClient.java new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GoogleMapsApiService.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/GoogleMapsApiService.java new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/OpenMapsApiClient.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/OpenMapsApiClient.java new file mode 100644 index 0000000..06d9a3a --- /dev/null +++ b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/OpenMapsApiClient.java @@ -0,0 +1,32 @@ +package com.quantum_guys.dncc_eco_sync.ui.activities.issue; + +import java.io.IOException; + +import retrofit2.Call; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class GoogleMapsApiClient { + private static final String BASE_URL = "https://maps.googleapis.com/"; + private GoogleMapsApiService service; + + public GoogleMapsApiClient() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl(BASE_URL) + .addConverterFactory(GsonConverterFactory.create()) + .build(); + + service = retrofit.create(GoogleMapsApiService.class); + } + + public String reverseGeocode(String latlng, String apiKey) throws IOException { + Call call = service.reverseGeocode(latlng, apiKey); + GeocodingResponse response = call.execute().body(); + + if (response != null && response.getResults().size() > 0) { + return response.getResults().get(0).getFormattedAddress(); + } else { + return "No results found"; + } + } +} diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/OpenMapsApiService.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/OpenMapsApiService.java new file mode 100644 index 0000000..7db317d --- /dev/null +++ b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/OpenMapsApiService.java @@ -0,0 +1,13 @@ +package com.quantum_guys.dncc_eco_sync.ui.activities.issue; + +import retrofit2.Call; +import retrofit2.http.GET; +import retrofit2.http.Query; + +public interface GoogleMapsApiService { + @GET("maps/api/geocode/json") + Call reverseGeocode( + @Query("latlng") String latlng, + @Query("key") String apiKey + ); +} diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/MapView.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/MapView.java similarity index 100% rename from android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/MapView.java rename to android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/MapView.java diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/NearbySts.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/NearbySts.java new file mode 100644 index 0000000..af59165 --- /dev/null +++ b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/NearbySts.java @@ -0,0 +1,147 @@ +package com.quantum_guys.dncc_eco_sync.ui.activities.nearbysts; + + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + + +public class NearbySts implements Serializable +{ + +@SerializedName("id") +@Expose +private Integer id; +@SerializedName("name") +@Expose +private String name; +@SerializedName("wardNumber") +@Expose +private String wardNumber; +@SerializedName("capacity") +@Expose +private Integer capacity; +@SerializedName("currentWasteVolume") +@Expose +private Integer currentWasteVolume; +@SerializedName("lat") +@Expose +private Double lat; +@SerializedName("lon") +@Expose +private Double lon; +@SerializedName("address") +@Expose +private Object address; +@SerializedName("logo") +@Expose +private Object logo; +@SerializedName("fine") +@Expose +private Integer fine; +@SerializedName("startTime") +@Expose +private Integer startTime; +@SerializedName("endTime") +@Expose +private Integer endTime; +private final static long serialVersionUID = 4238233360176200559L; + +public Integer getId() { +return id; +} + +public void setId(Integer id) { +this.id = id; +} + +public String getName() { +return name; +} + +public void setName(String name) { +this.name = name; +} + +public String getWardNumber() { +return wardNumber; +} + +public void setWardNumber(String wardNumber) { +this.wardNumber = wardNumber; +} + +public Integer getCapacity() { +return capacity; +} + +public void setCapacity(Integer capacity) { +this.capacity = capacity; +} + +public Integer getCurrentWasteVolume() { +return currentWasteVolume; +} + +public void setCurrentWasteVolume(Integer currentWasteVolume) { +this.currentWasteVolume = currentWasteVolume; +} + +public Double getLat() { +return lat; +} + +public void setLat(Double lat) { +this.lat = lat; +} + +public Double getLon() { +return lon; +} + +public void setLon(Double lon) { +this.lon = lon; +} + +public Object getAddress() { +return address; +} + +public void setAddress(Object address) { +this.address = address; +} + +public Object getLogo() { +return logo; +} + +public void setLogo(Object logo) { +this.logo = logo; +} + +public Integer getFine() { +return fine; +} + +public void setFine(Integer fine) { +this.fine = fine; +} + +public Integer getStartTime() { +return startTime; +} + +public void setStartTime(Integer startTime) { +this.startTime = startTime; +} + +public Integer getEndTime() { +return endTime; +} + +public void setEndTime(Integer endTime) { +this.endTime = endTime; +} + +} \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/NearbyStsService.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/NearbyStsService.java new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/RetrofitClient.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/nearbysts/RetrofitClient.java new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/AnimatorListener.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/AnimatorListener.java deleted file mode 100644 index 82b7935..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/AnimatorListener.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import android.animation.Animator; - -public class AnimatorListener implements Animator.AnimatorListener { - @Override - public void onAnimationStart(Animator animator) { - } - - @Override - public void onAnimationEnd(Animator animator) { - } - - @Override - public void onAnimationCancel(Animator animator) { - } - - @Override - public void onAnimationRepeat(Animator animator) { - } -} diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/BattleModel.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/BattleModel.java deleted file mode 100644 index 6a53e5f..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/BattleModel.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import androidx.annotation.NonNull; -import androidx.room.Entity; -import androidx.room.Ignore; -import androidx.room.PrimaryKey; -import androidx.room.TypeConverters; - -import com.quantum_guys.dncc_eco_sync.models.Question; -import com.quantum_guys.dncc_eco_sync.utils.BooleanLiatConverter; -import com.quantum_guys.dncc_eco_sync.utils.DataTypeConverterQuestion; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -@SuppressWarnings("NotNullFieldNotInitialized") -@Entity -public class BattleModel implements Serializable { - - public String topic; - @TypeConverters(BooleanLiatConverter.class) - public - ArrayList receiverList; - @TypeConverters(BooleanLiatConverter.class) - public ArrayList senderAnswerList; - String senderUid, receiverUid; - String timestamp; - String winner; - Boolean scoreUpdated; - @TypeConverters(DataTypeConverterQuestion.class) - List questionList; - @PrimaryKey - @NonNull - String battleId; - - @Ignore - public BattleModel() { - } - - public BattleModel(String senderUid, String receiverUid, List questionList, ArrayList senderAnswerList, ArrayList receiverList, String timestamp, String winner, @NonNull String battleId, String topic, Boolean scoreUpdated) { - this.senderUid = senderUid; - this.receiverUid = receiverUid; - this.questionList = questionList; - this.senderAnswerList = senderAnswerList; - this.receiverList = receiverList; - this.timestamp = timestamp; - this.winner = winner; - this.battleId = battleId; - this.topic = topic; - this.scoreUpdated = scoreUpdated; - } - - public String getSenderUid() { - return senderUid; - } - - public void setSenderUid(String senderUid) { - this.senderUid = senderUid; - } - - public String getReceiverUid() { - return receiverUid; - } - - public void setReceiverUid(String receiverUid) { - this.receiverUid = receiverUid; - } - - public List getQuestionList() { - return questionList; - } - - public void setQuestionList(List questionList) { - this.questionList = questionList; - } - - public ArrayList getSenderAnswerList() { - return senderAnswerList; - } - - public void setSenderAnswerList(ArrayList senderAnswerList) { - this.senderAnswerList = senderAnswerList; - } - - public List getReceiverList() { - return receiverList; - } - - public void setReceiverList(ArrayList receiverList) { - this.receiverList = receiverList; - } - - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - public String getWinner() { - return winner; - } - - public void setWinner(String winner) { - this.winner = winner; - } - - @SuppressWarnings("NullableProblems") - public String getBattleId() { - return battleId; - } - - public void setBattleId(@NonNull String battleId) { - this.battleId = battleId; - } - - public String getTopic() { - return topic; - } - - public void setTopic(String topic) { - this.topic = topic; - } - - public Boolean getScoreUpdated() { - return scoreUpdated; - } - - public void setScoreUpdated(Boolean scoreUpdated) { - this.scoreUpdated = scoreUpdated; - } -} \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/PlayQuiz.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/PlayQuiz.java deleted file mode 100644 index 4e8cd91..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/PlayQuiz.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import static com.quantum_guys.dncc_eco_sync.ui.activities.MainActivity.inHome; - -import android.annotation.SuppressLint; -import android.app.ActivityOptions; -import android.content.Intent; -import android.os.Bundle; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; -import androidx.lifecycle.ViewModelProviders; -import androidx.paging.PagedList; -import androidx.recyclerview.widget.DefaultItemAnimator; -import androidx.recyclerview.widget.DividerItemDecoration; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.RequestOptions; -import com.firebase.ui.firestore.paging.FirestorePagingAdapter; -import com.firebase.ui.firestore.paging.FirestorePagingOptions; -import com.firebase.ui.firestore.paging.LoadingState; -import com.github.marlonlom.utilities.timeago.TimeAgo; -import com.google.firebase.auth.FirebaseAuth; -import com.google.firebase.firestore.FirebaseFirestore; -import com.google.firebase.firestore.Query; - -import com.quantum_guys.dncc_eco_sync.R; -import com.quantum_guys.dncc_eco_sync.adapters.PlayerAdapter; -import com.quantum_guys.dncc_eco_sync.models.Player; -import com.quantum_guys.dncc_eco_sync.viewmodel.UserViewModel; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import es.dmoral.toasty.Toasty; - -/** - * Created by jhm69 - */ - -public class PlayQuiz extends Fragment { - List usersId; - UserViewModel userViewModel; - long myType; - private FirebaseFirestore firestore; - private RecyclerView mRecyclerView; - private SwipeRefreshLayout refreshLayout; - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - return inflater.inflate(R.layout.send_message_fragment, container, false); - } - - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - - firestore = FirebaseFirestore.getInstance(); - - usersId = new ArrayList<>(); - mRecyclerView = view.findViewById(R.id.messageList); - refreshLayout = view.findViewById(R.id.refreshLayout); - - userViewModel = ViewModelProviders.of(requireActivity()).get(UserViewModel.class); - - myType = userViewModel.getUser().getType(); - - mRecyclerView.setItemAnimator(new DefaultItemAnimator()); - mRecyclerView.setLayoutManager(new LinearLayoutManager(view.getContext())); - mRecyclerView.setHasFixedSize(true); - mRecyclerView.addItemDecoration(new DividerItemDecoration(view.getContext(), DividerItemDecoration.VERTICAL)); - - refreshLayout.setOnRefreshListener(this::setupAdapter); - setupAdapter(); - } - - @Override - public void onDestroy() { - inHome = true; - super.onDestroy(); - } - - private void setupAdapter() { - PagedList.Config config = new PagedList.Config.Builder() - .setEnablePlaceholders(false) - .setPrefetchDistance(5) - .setPageSize(20) - .build(); - Query mQuery = firestore.collection("Users").whereEqualTo("type", myType) - .orderBy("lastTimestamp", Query.Direction.DESCENDING); - - FirestorePagingOptions options = new FirestorePagingOptions.Builder() - .setLifecycleOwner(this) - .setQuery(mQuery, config, Player.class) - .build(); - // Instantiate Paging Adapter - - //holder.bind(post, holder, position, mmBottomSheetDialog, statsheetView); - FirestorePagingAdapter mAdapter = new FirestorePagingAdapter(options) { - @NonNull - @Override - public PlayerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View view = getLayoutInflater().inflate(R.layout.item_quiz_profile, parent, false); - return new PlayerAdapter.ViewHolder(view); - } - - @SuppressLint({"SetTextI18n", "CheckResult"}) - @Override - protected void onBindViewHolder(@NonNull PlayerAdapter.ViewHolder holder, int position, @NonNull Player user) { - usersId.add(user.getId()); - Objects.requireNonNull(getView()).findViewById(R.id.default_item).setVisibility(View.GONE); - holder.name.setText(user.getName()); - holder.institute.setText(user.getDept() + ", " + user.getInstitute()); - if (user.getDept().equals("")) { - holder.institute.setText(user.getInstitute()); - } else if (user.getInstitute().equals("")) { - holder.institute.setText(user.getDept()); - } else { - holder.institute.setText(user.getDept() + ", " + user.getInstitute()); - } - int score = (int) user.getScore(); - holder.level.setText(String.valueOf(score)); - Glide.with(Objects.requireNonNull(getContext())) - .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) - .load(user.getImage()) - .into(holder.image); - - holder.time.setText(getTimeText(user.getLastTimestamp())); - - holder.mView.setOnClickListener(view -> { - if (Objects.equals(FirebaseAuth.getInstance().getUid(), user.getId())) { - Toasty.error(requireActivity(), "You can't play with yourself. Select someone else", Toasty.LENGTH_SHORT, true); - } else { - Intent goBattle = new Intent(getContext(), SelectTopic.class); - goBattle.putExtra("otherUid", user.getId()); - getContext().startActivity(goBattle, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle()); - } - }); - } - - private String getTimeText(long lastTimestamp) { - String time = TimeAgo.using(lastTimestamp); - time = time.replaceAll("just now", "now") - .replaceAll(" minutes", "m") - .replaceAll(" minute", "1m") - .replaceAll("about", "") - .replaceAll(" hours", "h") - .replaceAll(" hour", "1h") - .replaceAll(" an", "") - .replaceAll("a ", "1 ") - .replaceAll(" ago", "") - .replaceAll("yesterday", "1d") - .replaceAll(" days", "d") - .replaceAll(" day", "1d"); - return time; - } - - @Override - protected void onError(@NonNull Exception e) { - super.onError(e); - Log.e("MainActivity", e.getMessage()); - } - - @Override - protected void onLoadingStateChanged(@NonNull LoadingState state) { - switch (state) { - case LOADING_INITIAL: - case LOADING_MORE: - refreshLayout.setRefreshing(true); - break; - - case LOADED: - if (getItemCount() == 0) { - Objects.requireNonNull(getView()).findViewById(R.id.default_item).setVisibility(View.VISIBLE); - } - refreshLayout.setRefreshing(false); - break; - - case ERROR: - Toast.makeText( - getActivity(), - "Error Occurred!", - Toast.LENGTH_SHORT - ).show(); - - refreshLayout.setRefreshing(false); - break; - case FINISHED: - refreshLayout.setRefreshing(false); - break; - } - } - - }; - mRecyclerView.setAdapter(mAdapter); - - } - -} diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Player.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Player.java deleted file mode 100644 index f1cfbbf..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Player.java +++ /dev/null @@ -1 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; import com.quantum_guys.dncc_eco_sync.models.Users; public class Player extends Users { String name, uid, image; public Player() { } public Player(String name, String uid, String image) { this.name = name; this.uid = uid; this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } } \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/QuizBattle.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/QuizBattle.java deleted file mode 100644 index b913d54..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/QuizBattle.java +++ /dev/null @@ -1,1253 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import static com.quantum_guys.dncc_eco_sync.ui.activities.MainActivity.userId; -import static com.quantum_guys.dncc_eco_sync.ui.activities.quiz.StepView.stepAnsList; - -import android.animation.Animator; -import android.annotation.SuppressLint; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.res.ColorStateList; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.GradientDrawable; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Bundle; -import android.os.CountDownTimer; -import android.transition.Explode; -import android.util.Log; -import android.view.View; -import android.view.Window; -import android.view.animation.DecelerateInterpolator; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.RequiresApi; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.app.AppCompatDelegate; -import androidx.lifecycle.ViewModelProviders; - -import com.afollestad.materialdialogs.MaterialDialog; -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.RequestOptions; -import com.google.firebase.database.ChildEventListener; -import com.google.firebase.database.DataSnapshot; -import com.google.firebase.database.DatabaseError; -import com.google.firebase.database.DatabaseReference; -import com.google.firebase.database.FirebaseDatabase; -import com.google.firebase.database.MutableData; -import com.google.firebase.database.Query; -import com.google.firebase.database.Transaction; -import com.google.firebase.database.ValueEventListener; -import com.google.firebase.firestore.FirebaseFirestore; - -import com.quantum_guys.dncc_eco_sync.R; -import com.quantum_guys.dncc_eco_sync.models.Notification; -import com.quantum_guys.dncc_eco_sync.models.Question; -import com.quantum_guys.dncc_eco_sync.models.Users; -import com.quantum_guys.dncc_eco_sync.notification.APIService; -import com.quantum_guys.dncc_eco_sync.notification.Client; -import com.quantum_guys.dncc_eco_sync.notification.MyResponse; -import com.quantum_guys.dncc_eco_sync.notification.NotificationSender; -import com.quantum_guys.dncc_eco_sync.repository.UserRepository; -import com.quantum_guys.dncc_eco_sync.utils.MathView; -import com.quantum_guys.dncc_eco_sync.viewmodel.BattleViewModel; -import com.quantum_guys.dncc_eco_sync.viewmodel.ResultViewModel; -import com.quantum_guys.dncc_eco_sync.viewmodel.UserViewModel; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; - -import es.dmoral.toasty.Toasty; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; - -public class QuizBattle extends AppCompatActivity { - - public ArrayList SenderAnsList; - public ArrayList reciverAnsList; - public int position; - boolean destroy=false; - public final int JUST_STARTED = -1; - public final int OFFLINE_STARTED = -2; - public final int JUST_IN = -3; - public final int IN_STARTED = -4; - public final int COMPLETED = -5; - BattleViewModel battleViewModel; - ImageView otherUserImage, thisUserImage; - TextView thisUserName, thisUserLevel, otherUserName, otherUserLevel, thisScore, otherScore, topicTV; - String battleIdNew, offlideID; - String thisUid, otherUid; - String MyName, MyImage; - String topic, subtopic; - int question_number; - BattleModel realBattle; - final String timestamp = String.valueOf(System.currentTimeMillis()); - final String battleId = Long.toHexString(Double.doubleToLongBits(Math.random())); - BattleModel offlineBattleSaving; - ResultViewModel viewModel; - UserViewModel userViewModel; - private LinearLayout optionsContainer; - private Button next; - private int count = 0; - long timeLeftInMillis=0; - private LinearLayout question; - private ImageView mcqImg; - private List list; - private int score; - private DatabaseReference mainDB; - FirebaseFirestore mFirestore; - private StepView stepView; - private ProgressDialog mDialog; - private String hisName, hisImage; - private CountDownTimer countDownTimer; - - Users user; - private TextView textViewCountDown; - - /* public boolean isPanelShown(View view) { - return view.getVisibility() == View.VISIBLE; - } - public void hideSolution(final View view, Context context) { - TranslateAnimation animate = new TranslateAnimation( - 0, // fromXDelta - 0, // toXDelta - 0, // fromYDelta - view.getHeight()); // toYDelta - animate.setDuration(500); - animate.setFillAfter(true); - view.startAnimation(animate); - view.setVisibility(View.GONE); - } - public void playSolution(final View view, Context context) { - view.setVisibility(View.VISIBLE); - TranslateAnimation animate = new TranslateAnimation( - 0, // fromXDelta - 0, // toXDelta - view.getHeight(), // fromYDelta - 0); // toYDelta - animate.setDuration(500); - animate.setFillAfter(true); - view.startAnimation(animate); - } - */ - public void randomiseQuestions(DatabaseReference mainDB) { - try { - AsyncTask.execute(() -> mainDB.runTransaction(new Transaction.Handler() { - @NonNull - @Override - public Transaction.Result doTransaction(@NonNull MutableData mutableData) { - long max = mutableData.getChildrenCount(); - for (MutableData data : mutableData.getChildren()) { - Question node = data.getValue(Question.class); - if (node != null) { - node.setIndex((int) (Math.random() * max + 1)); - data.setValue(node); - } - } - return Transaction.success(mutableData); - } - - @Override - public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) { - - } - })); - - } catch (Exception ignored) { - - } - } - - - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - private void playQuestion(final View view, final int value, final String data) { - try { - next.setEnabled(false); - if (list.get(position).getImg().length() > 10) { - mcqImg.setVisibility(View.VISIBLE); - Glide.with(getApplicationContext()) - .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) - .load(list.get(position).getImg()) - .into(mcqImg); - } else { - mcqImg.setVisibility(View.GONE); - } - } catch (NullPointerException ignored) { - - } - changeColor(); - view.animate().alpha(value).scaleX(value).scaleY(value).setDuration(500).setStartDelay(100) - .setInterpolator(new DecelerateInterpolator()).setListener(new Animator.AnimatorListener() { - @Override - public void onAnimationStart(Animator animation) { - if (value == 0 && count < 4) { - String option = ""; - if (count == 0) { - option = list.get(position).getA(); - } else if (count == 1) { - option = list.get(position).getB(); - } else if (count == 2) { - option = list.get(position).getC(); - } else if (count == 3) { - option = list.get(position).getD(); - } - LinearLayout linearLayout = (LinearLayout) optionsContainer.getChildAt(count); - playQuestion(linearLayout, 0, option); - count++; - } - } - - @Override - public void onAnimationEnd(Animator animation) { - if (value == 0) { - LinearLayout layout = (LinearLayout) view; - ((MathView) layout.getChildAt(0)).setDisplayText(data); - view.setTag(data); - playQuestion(view, 1, data); - } - } - - @Override - public void onAnimationCancel(Animator animation) { - - } - - @Override - public void onAnimationRepeat(Animator animation) { - - } - }); - } - - - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - private void playAnim(final View view, int time, final String data) { - // timeLeft(time); - Log.d("showResult", "weds"); - startCountDown(time); - elableOption(true); - playQuestion(view, 0,data); - } - - - private void startCountDown(int t) { - if(countDownTimer!=null){ - countDownTimer.cancel(); - } - countDownTimer = new CountDownTimer(t*1000, 1000) { - @Override - public void onTick(long millisUntilFinished) { - if((millisUntilFinished)<(t*1000*0.4)) destroy=true; - timeLeftInMillis = millisUntilFinished; - updateCountDownText(); - } - @Override - public void onFinish() { - timeLeftInMillis = 0; - countDownTimer.cancel(); - updateCountDownText(); - Toasty.error(getApplicationContext(), "Time over", Toasty.LENGTH_SHORT, true).show(); - next.setEnabled(true); - elableOption(false); - LinearLayout CorrectLayout; - CorrectLayout = (LinearLayout) optionsContainer.getChildAt(list.get(position).getAns()); - CorrectLayout.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#4BBB4F"))); - stepAnsList.add(position, false); - showResult(); - } - }.start(); - } - - @SuppressLint("ResourceAsColor") - private void updateCountDownText() { - int seconds = (int) (timeLeftInMillis / 1000) % 60; - String timeFormatted = String.format(Locale.getDefault(), "%02d", seconds); - textViewCountDown.setText(timeFormatted); - if (timeLeftInMillis < 10000) { - textViewCountDown.setTextColor(Color.RED); - } else { - textViewCountDown.setTextColor(R.color.Timewhite); - } - } - - - - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - @SuppressLint("ResourceAsColor") - private void changeColor() { - LinearLayout op1 = (LinearLayout) optionsContainer.getChildAt(0); - op1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#575757"))); - - LinearLayout op2 = (LinearLayout) optionsContainer.getChildAt(1); - op2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#575757"))); - - LinearLayout op3 = (LinearLayout) optionsContainer.getChildAt(2); - op3.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#575757"))); - - LinearLayout op4 = (LinearLayout) optionsContainer.getChildAt(3); - op4.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#575757"))); - - } - - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - private void elableOption(boolean enable) { - for (int i = 0; i < 4; i++) { - LinearLayout linearLayout = (LinearLayout) optionsContainer.getChildAt(i); - linearLayout.setEnabled(enable); - if (enable) { - LinearLayout layout = (LinearLayout) optionsContainer.getChildAt(i); - layout.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#575757"))); - } - } - } - - @SuppressLint("CheckResult") - private void loadQuestionData() { - try { - mDialog.show(); - if (battleIdNew != null) { - try { - realBattle = battleViewModel.getBattle(battleIdNew); - topic = realBattle.topic; - topicTV.setText(topic); - mDialog.hide(); - Result result = viewModel.getResult(battleIdNew); - if (result.getAction() == IN_STARTED) { - Intent intent = new Intent(this, QuizBattle.class); - intent.putExtra("ofo", battleIdNew); - startActivity(intent); - } else if (result.getAction() == COMPLETED) { - Intent intent = new Intent(getApplicationContext(), ResultActivity.class); - intent.putExtra("resultId", battleIdNew); - startActivity(intent); - } - list = Objects.requireNonNull(realBattle).questionList; - question_number = realBattle.questionList.size(); - if (realBattle.getWinner().length() > 4) { - Intent intent = new Intent(getApplicationContext(), ResultActivity.class); - intent.putExtra("resultId", realBattle.battleId); - Toasty.warning(getApplicationContext(), "You have already completed this Challenge", Toasty.LENGTH_SHORT, true); - startActivity(intent); - finish(); - } - - try { - playAnim(question, list.get(position).getTime(), list.get(position).getQuestion()); - } catch (Exception ignored) { - Toasty.error(getApplicationContext(), "It seems you have already completed.xml this match", Toasty.LENGTH_SHORT, true); - finish(); - } - try { - stepView.getState() - .animationType(StepView.ANIMATION_ALL) - .nextStepCircleEnabled(true) - .stepsNumber(list.size()) - .commit(); - } catch (Exception ignored) { - Toasty.error(getBaseContext(), "It seems you have already completed.xml this match", Toasty.LENGTH_SHORT, true); - finish(); - } - for (int i = 0; i < question_number; i++) { - stepAnsList.add(false); - } - setUserData(otherUserImage, otherUserName, otherUserLevel, realBattle.senderUid, false); - SenderAnsList = realBattle.getSenderAnswerList(); - otherUid = realBattle.getSenderUid(); - offlineBattleSaving = realBattle; - offlineBattleSaving.setWinner("3"); - - } catch (Exception h) { - Query query = mainDB.child("Play").orderByChild("battleId").equalTo(battleIdNew); - query.addListenerForSingleValueEvent(new ValueEventListener() { - @SuppressLint("CheckResult") - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - @Override - public void onDataChange(@NonNull DataSnapshot snapshot) { - if(snapshot.exists()) { - try { - for (DataSnapshot data : snapshot.getChildren()) { - realBattle = data.getValue(BattleModel.class); - } - list = Objects.requireNonNull(realBattle).questionList; - question_number = realBattle.questionList.size(); - if (!realBattle.getWinner().equals("0")) { - Intent intent = new Intent(getApplicationContext(), ResultActivity.class); - intent.putExtra("resultId", realBattle.battleId); - Toasty.warning(getApplicationContext(), "You have already completed this Challenge", Toasty.LENGTH_SHORT, true); - startActivity(intent); - finish(); - } - setUserData(otherUserImage, otherUserName, otherUserLevel, realBattle.senderUid, false); - try { - playAnim(question, list.get(position).getTime(), list.get(position).getQuestion()); - } catch (NullPointerException ignored) { - Toasty.error(getApplicationContext(), "It seems you have already completed.xml this match", Toasty.LENGTH_SHORT, true); - finish(); - } - try { - stepView.getState() - .animationType(StepView.ANIMATION_ALL) - .nextStepCircleEnabled(true) - .stepsNumber(list.size()) - .commit(); - } catch (Exception ignored) { - Toasty.error(getBaseContext(), "It seems you have already completed.xml this match", Toasty.LENGTH_SHORT, true); - finish(); - } - SenderAnsList = realBattle.senderAnswerList; - otherUid = realBattle.getSenderUid(); - offlineBattleSaving = realBattle; - offlineBattleSaving.setWinner("3"); - } catch (Exception h) { - Toasty.error(getApplicationContext(), "Select this battle from main Quiz dashboard, Error Occurs", Toasty.LENGTH_SHORT, true); - finish(); - } - }else{ - Toasty.error(getApplicationContext(), "No battle found, start from Quiz Dashboard page", Toasty.LENGTH_SHORT, true); - finish(); - } - } - - @Override - public void onCancelled(@NonNull DatabaseError error) { - - } - }); - for (int i = 0; i < question_number; i++) { - stepAnsList.add(false); - } - } - - } else if (offlideID != null) { - try { - Toast.makeText(this, "Resuming battle...", Toast.LENGTH_SHORT).show(); - realBattle = battleViewModel.getBattle(offlideID); - mDialog.hide(); - topic = realBattle.topic; - topicTV.setText(topic); - if (realBattle.getWinner().equals("3")) { - position = realBattle.getReceiverList().size(); - score = getScoreCount(realBattle.getReceiverList()); - thisScore.setText(String.valueOf(score)); - otherScore.setText("-"); - list = Objects.requireNonNull(realBattle).questionList; - question_number = realBattle.questionList.size(); - setUserData(otherUserImage, otherUserName, otherUserLevel, realBattle.getSenderUid(), false); - - try { - playAnim(question, list.get(position).getTime(), list.get(position).getQuestion()); - } catch (Exception vhjkj) { - Toasty.error(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); - finish(); - } - try { - stepView.getState() - .animationType(StepView.ANIMATION_ALL) - .nextStepCircleEnabled(true) - .stepsNumber(list.size()) - .commit(); - } catch (Exception xcz) { - Toasty.error(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); - finish(); - } - SenderAnsList = realBattle.senderAnswerList; - reciverAnsList = realBattle.receiverList; - for (int i = 0; i < question_number; i++) { - stepAnsList.add(false); - } - for (int i = 0; i < position; i++) { - stepAnsList.add(i, realBattle.getReceiverList().get(i)); - } - stepView.go(position, true, true); - otherUid = realBattle.getSenderUid(); - offlineBattleSaving = realBattle; - offlineBattleSaving.setWinner("3"); - - } else if (realBattle.getWinner().equals("2")) { - position = realBattle.getSenderAnswerList().size(); - score = getScoreCount(realBattle.getSenderAnswerList()); - thisScore.setText(String.valueOf(score)); - list = Objects.requireNonNull(realBattle).questionList; - question_number = realBattle.questionList.size(); - setUserData(otherUserImage, otherUserName, otherUserLevel, realBattle.receiverUid, false); - - try { - playAnim(question, list.get(position).getTime(), list.get(position).getQuestion()); - } catch (Exception dc) { - Toasty.error(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); - finish(); - } - try { - stepView.getState() - .animationType(StepView.ANIMATION_ALL) - .nextStepCircleEnabled(true) - .stepsNumber(list.size()) - .commit(); - } catch (Exception ignored) { - Toasty.error(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); - finish(); - } - SenderAnsList = realBattle.senderAnswerList; - for (int i = 0; i < question_number; i++) { - stepAnsList.add(false); - } - for (int i = 0; i < position; i++) { - stepAnsList.add(i, realBattle.getSenderAnswerList().get(i)); - } - stepView.go(position, true, true); - otherUid = realBattle.getReceiverUid(); - offlineBattleSaving = realBattle; - offlineBattleSaving.setWinner("2"); - } - } catch (Exception fd) { - Toasty.error(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); - finish(); - } - } else { - try { - String type = "bcs"; - type = getIntent().getStringExtra("type"); - Query query = mainDB.child("Topics").child(type).child(topic).child(subtopic) - .orderByChild("index") - .limitToFirst(question_number); - query.addChildEventListener(new ChildEventListener() { - @Override - public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { - list.add(snapshot.getValue(Question.class)); - Collections.shuffle(list); - stepAnsList.add(false); - mDialog.dismiss(); - playAnim(question, list.get(position).getTime(), list.get(position).getQuestion()); - stepView.getState() - .animationType(StepView.ANIMATION_ALL) - .nextStepCircleEnabled(true) - .stepsNumber(list.size()) - .commit(); - } - - @Override - public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { - - } - - @Override - public void onChildRemoved(@NonNull DataSnapshot snapshot) { - - } - - @Override - public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { - - } - - @Override - public void onCancelled(@NonNull DatabaseError error) { - - } - }); - otherUid = getIntent().getStringExtra("otherUid"); - setUserData(otherUserImage, otherUserName, otherUserLevel, otherUid, false); - offlineBattleSaving = new BattleModel(thisUid, otherUid, list, SenderAnsList, reciverAnsList, timestamp, "0", battleId, topic, false); - } catch (NullPointerException jj) { - Log.d("SSSF", jj.getMessage()); - finish(); - Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show(); - } - } - }catch (Exception h){ - Toasty.error(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); - finish(); - } - } - - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - private void goToNext(int which) { - try { - if (battleIdNew == null) { - stepView.go(which, true, SenderAnsList.get(which - 1)); - } else { - stepView.go(which, true, reciverAnsList.get(which - 1)); - } - next.setEnabled(false); - elableOption(true); - if (which >= list.size()) { - mDialog.show(); - addToNotification(); - } else { - playAnim(question, list.get(which).getTime(), list.get(which).getQuestion()); - } - count = 0; - }catch (Exception d){ - Log.d("Errorrr", d.getMessage()); - finish(); - } - } - - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - private void showResult() { - AsyncTask.execute(() -> { - if (battleIdNew != null) { - reciverAnsList.add(position, false); - realBattle.setReceiverList(reciverAnsList); - realBattle.setWinner("3"); - battleViewModel.insert(realBattle); - Result myResult = new Result(realBattle.battleId, otherUid, userId, score, -2, topic, timestamp, IN_STARTED); - myResult.setBattleId(realBattle.battleId); - if (position + 1 == question_number) { - myResult.setAction(COMPLETED); - myResult.setOtherUid(realBattle.senderUid); - myResult.setOtherScore(getScoreCount(realBattle.senderAnswerList)); - } - viewModel.insert(myResult); - } else if (offlideID != null) { - if (realBattle.getWinner().equals("2")) { - SenderAnsList.add(position, false); - offlineBattleSaving.setSenderAnswerList(SenderAnsList); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(offlideID, userId, otherUid, score, -2, topic, timestamp, OFFLINE_STARTED); - if (position + 1 == question_number) - myResult.setAction(JUST_STARTED); - viewModel.insert(myResult); - } else if (realBattle.getWinner().equals("3")) { - reciverAnsList.add(position, false); - offlineBattleSaving.setSenderAnswerList(reciverAnsList); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(offlideID, otherUid, userId, score, -2, topic, timestamp, IN_STARTED); - if (position + 1 == question_number) { - myResult.setAction(COMPLETED); - myResult.setOtherUid(realBattle.senderUid); - myResult.setOtherScore(getScoreCount(offlineBattleSaving.senderAnswerList)); - } - viewModel.insert(myResult); - } - } else { - SenderAnsList.add(position, false); - offlineBattleSaving.setSenderAnswerList(SenderAnsList); - offlineBattleSaving.setWinner("2"); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(battleId, userId, otherUid, score, -2, topic, timestamp, OFFLINE_STARTED); - if (position + 1 == question_number) - myResult.setAction(JUST_STARTED); - viewModel.insert(myResult); - } - - }); - } - - private Drawable getDrawableWithRadius() { - int[] colors = {Color.parseColor("#8342ED"), Color.parseColor("#5570A0")}; - GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, colors); - gradientDrawable.setCornerRadii(new float[]{20, 20, 20, 20, 20, 20, 20, 20}); - return gradientDrawable; - } - - - - public void onPause() { - super.onPause(); - } - - @SuppressLint("SetTextI18n") - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - @Override - protected void onCreate(Bundle savedInstanceState) { - requestWindowFeature(Window.FEATURE_NO_TITLE); - getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); - getWindow().setEnterTransition(new Explode()); - getWindow().setExitTransition(new Explode()); - super.onCreate(savedInstanceState); - SharedPreferences sharedPreferences = getSharedPreferences("Theme", Context.MODE_PRIVATE); - String themeName = sharedPreferences.getString("ThemeName", "Default"); - if (themeName.equalsIgnoreCase("TealTheme")) { - setTheme(R.style.TealTheme); - } else if (themeName.equalsIgnoreCase("VioleteTheme")) { - setTheme(R.style.VioleteTheme); - } else if (themeName.equalsIgnoreCase("PinkTheme")) { - setTheme(R.style.PinkTheme); - } else if (themeName.equalsIgnoreCase("DelRio")) { - setTheme(R.style.DelRio); - } else if (themeName.equalsIgnoreCase("DarkTheme")) { - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); - setTheme(R.style.Dark); - } else if (themeName.equalsIgnoreCase("Lynch")) { - setTheme(R.style.Lynch); - } else { - setTheme(R.style.AppTheme); - } - setContentView(R.layout.activity_quiz_battle); - stepAnsList = new ArrayList<>(); - thisUid = userId; - offlideID = getIntent().getStringExtra("ofo"); - battleIdNew = getIntent().getStringExtra("battleId"); - topic = getIntent().getStringExtra("topic"); - subtopic = getIntent().getStringExtra("subtopic"); - question_number = getIntent().getIntExtra("question_number", 5); - mainDB = FirebaseDatabase.getInstance().getReference(); - user = new UserRepository(getApplication()).getUser(); - - reciverAnsList = new ArrayList<>(); - thisUserName = findViewById(R.id.thisUserName); - viewModel = ViewModelProviders.of(this).get(ResultViewModel.class); - userViewModel = ViewModelProviders.of(this).get(UserViewModel.class); - thisUserLevel = findViewById(R.id.thisUserLevel); - textViewCountDown = findViewById(R.id.textView3); - thisUserImage = findViewById(R.id.thisUserImage); - thisScore = findViewById(R.id.myScore); - otherUserName = findViewById(R.id.otherUserName); - otherUserLevel = findViewById(R.id.otherUserLevel); - otherUserImage = findViewById(R.id.otherUserImage); - otherScore = findViewById(R.id.otherScore); - topicTV = findViewById(R.id.topic); - question = findViewById(R.id.questionQ); - stepView = findViewById(R.id.step_view); - mcqImg = findViewById(R.id.mcq_img); - list = new ArrayList<>(); - SenderAnsList = new ArrayList<>(); - next = findViewById(R.id.next); - optionsContainer = findViewById(R.id.contaner); - mDialog = new ProgressDialog(this); - mDialog.setMessage("Please wait.."); - mDialog.setIndeterminate(true); - mDialog.setCanceledOnTouchOutside(false); - mDialog.setCancelable(false); - mFirestore = FirebaseFirestore.getInstance(); - setUserData(thisUserImage, thisUserName, thisUserLevel, thisUid, true); - //mcqAnsList = new ArrayList<>(); - position = 0; - thisScore.setText(String.valueOf(0)); - topicTV.setText(topic); - otherScore.setText("-"); - battleViewModel = ViewModelProviders.of(this).get(BattleViewModel.class); - if (list.size() != 4) { - loadQuestionData(); - } else { - try { - playAnim(question, list.get(position).getTime(), list.get(position).getQuestion()); - } catch (ClassCastException svs) { - Toast.makeText(this, "error", Toast.LENGTH_SHORT).show(); - } - } - /* expBtn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (isPanelShown(expCard)) { - hideSolution(expCard, getApplicationContext()); - expBtn.setText("Hint"); - } else { - expTV.setDisplayText(list.get(position).getHint()); - playSolution(expCard, getApplicationContext()); - expBtn.setText("Hide"); - } - } - });*/ - for (int i = 0; i < 4; i++) { - final int selected = i; - optionsContainer.getChildAt(i).setOnClickListener(v -> { - LinearLayout selectedLayout = (LinearLayout) v; - elableOption(false); - next.setEnabled(true); - if (selected == list.get(position).getAns()) { - score++; - thisScore.setText(String.valueOf(score)); - Toasty.success(getApplicationContext(), "Correct", Toasty.LENGTH_SHORT, true).show(); - selectedLayout.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#4BBB4F"))); - stepAnsList.add(position, true); - AsyncTask.execute(() -> { - if (battleIdNew != null) { - reciverAnsList.add(position, true); - realBattle.setReceiverList(reciverAnsList); - realBattle.setWinner("3"); - battleViewModel.insert(realBattle); - Result myResult = new Result(realBattle.battleId, otherUid, userId, score, -2, topic, timestamp, IN_STARTED); - myResult.setBattleId(realBattle.battleId); - if (position + 1 == question_number) { - myResult.setAction(COMPLETED); - myResult.setOtherUid(realBattle.senderUid); - myResult.setOtherScore(getScoreCount(realBattle.senderAnswerList)); - } - viewModel.insert(myResult); - } else if (offlideID != null) { - if (realBattle.getWinner().equals("2")) { - SenderAnsList.add(position, true); - offlineBattleSaving.setSenderAnswerList(SenderAnsList); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(offlideID, userId, otherUid, score, -2, topic, timestamp, OFFLINE_STARTED); - if (position + 1 == question_number) - myResult.setAction(JUST_STARTED); - viewModel.insert(myResult); - } else if (realBattle.getWinner().equals("3")) { - reciverAnsList.add(position, true); - offlineBattleSaving.setSenderAnswerList(reciverAnsList); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(offlideID, otherUid, userId, score, -2, topic, timestamp, IN_STARTED); - if (position + 1 == question_number) { - myResult.setAction(COMPLETED); - myResult.setOtherUid(realBattle.senderUid); - myResult.setOtherScore(getScoreCount(offlineBattleSaving.senderAnswerList)); - } - viewModel.insert(myResult); - } - } else { - SenderAnsList.add(position, true); - offlineBattleSaving.setSenderAnswerList(SenderAnsList); - offlineBattleSaving.setWinner("2"); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(battleId, userId, otherUid, score, -2, topic, timestamp, OFFLINE_STARTED); - if (position + 1 == question_number) - myResult.setAction(JUST_STARTED); - viewModel.insert(myResult); - } - - }); - } else { - Toasty.error(getApplicationContext(), "Wrong", Toasty.LENGTH_SHORT, true).show(); - selectedLayout.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#D32F2F"))); - LinearLayout CorrectLayout = (LinearLayout) optionsContainer.getChildAt(list.get(position).getAns()); - CorrectLayout.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#4BBB4F"))); - stepAnsList.add(position, false); - AsyncTask.execute(() -> { - if (battleIdNew != null) { - reciverAnsList.add(position, false); - realBattle.setReceiverList(reciverAnsList); - realBattle.setWinner("3"); - battleViewModel.insert(realBattle); - Result myResult = new Result(realBattle.battleId, otherUid, userId, score, -2, topic, timestamp, IN_STARTED); - myResult.setBattleId(realBattle.battleId); - if (position + 1 == question_number) { - myResult.setAction(COMPLETED); - myResult.setOtherUid(realBattle.senderUid); - myResult.setOtherScore(getScoreCount(realBattle.senderAnswerList)); - } - viewModel.insert(myResult); - } else if (offlideID != null) { - if (realBattle.getWinner().equals("2")) { - SenderAnsList.add(position, false); - offlineBattleSaving.setSenderAnswerList(SenderAnsList); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(offlideID, userId, otherUid, score, -2, topic, timestamp, OFFLINE_STARTED); - if (position + 1 == question_number) - myResult.setAction(JUST_STARTED); - viewModel.insert(myResult); - } else if (realBattle.getWinner().equals("3")) { - reciverAnsList.add(position, false); - offlineBattleSaving.setSenderAnswerList(reciverAnsList); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(offlideID, otherUid, userId, score, -2, topic, timestamp, IN_STARTED); - if (position + 1 == question_number) { - myResult.setAction(COMPLETED); - myResult.setOtherUid(realBattle.senderUid); - myResult.setOtherScore(getScoreCount(offlineBattleSaving.senderAnswerList)); - } - viewModel.insert(myResult); - } - } else { - SenderAnsList.add(position, false); - offlineBattleSaving.setSenderAnswerList(SenderAnsList); - offlineBattleSaving.setWinner("2"); - battleViewModel.insert(offlineBattleSaving); - Result myResult = new Result(battleId, userId, otherUid, score, -2, topic, timestamp, OFFLINE_STARTED); - if (position + 1 == question_number) - myResult.setAction(JUST_STARTED); - viewModel.insert(myResult); - } - - }); - } - }); - } - next.setOnClickListener(v -> { - if (position < 1) { - updateXP(false); - Toast.makeText(getApplicationContext(), "5 XP reduced", Toast.LENGTH_SHORT).show(); - } - position++; - goToNext(position); - }); - - } - - @Override - protected void onDestroy() { - try{ - if(destroy) showResult(); - }catch (Exception ignored){ - - } - if (countDownTimer != null) { - countDownTimer.cancel(); - } - super.onDestroy(); - } - - private void addScore(int score, String uid, String what, boolean me) { - if(me) { - int newScores = score; - if (what.equals("win")) { - newScores = (int) user.getWin(); - newScores += score; - userViewModel.setWin(newScores); - } - if (what.equals("lose")) { - newScores = (int) user.getLose(); - newScores += score; - userViewModel.setLose(newScores); - } - if (what.equals("draw")) { - newScores = (int) user.getDraw(); - newScores += score; - userViewModel.setDraw(newScores); - } - if (what.equals("score")) { - newScores = (int) user.getScore(); - newScores += score; - userViewModel.setScore(newScores); - } - HashMap scoreMap = new HashMap<>(); - scoreMap.put(what, newScores); - mFirestore.collection("Users") - .document(uid) - .update(scoreMap).addOnSuccessListener(aVoid -> { - }); - }else{ - FirebaseFirestore.getInstance().collection("Users") - .document(uid) - .get() - .addOnSuccessListener(documentSnapshot -> { - int scoreOld = Objects.requireNonNull(documentSnapshot.getLong(what)).intValue(); - int newScore = scoreOld + (score); - HashMap scoreMap = new HashMap<>(); - scoreMap.put(what, newScore); - FirebaseFirestore.getInstance() - .collection("Users") - .document(uid) - .update(scoreMap).addOnSuccessListener(aVoid -> { - }); - }); - } - } - - private void setUserData(ImageView proPic, TextView name, TextView level, String uid, boolean me) { - try { - if (me) { - MyName = user.getUsername(); - MyImage = user.getImage(); - name.setText(MyName); - setLevelByScore(level, (int) user.getScore()); - Glide.with(getApplicationContext()) - .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) - .load(MyImage) - .into(proPic); - } else { - mFirestore.collection("Users") - .document(uid) - .get() - .addOnSuccessListener(documentSnapshot -> { - hisName = documentSnapshot.getString("username"); - name.setText(hisName); - setLevelByScore(level, Integer.parseInt(String.valueOf(documentSnapshot.getLong("score")))); - hisImage = documentSnapshot.getString("image"); - Glide.with(getApplicationContext()) - .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) - .load(hisImage) - .into(proPic); - }); - } - } catch (NullPointerException ignored) { - - } - } - - private void addToNotification() { - if (battleIdNew != null) { - Notification notification = new Notification(realBattle.getBattleId(),realBattle.senderUid, MyName, MyImage, - "accepted your challenge in " + realBattle.topic, - String.valueOf(System.currentTimeMillis()), - "play_result" - , realBattle.battleId, false); - new SendNotificationAsyncTask(notification).execute(); - //realBattle means data with including second player - FirebaseFirestore.getInstance().collection("Users") - .document(otherUid) - .collection("Info_Notifications").document(notification.getId()) - .set(notification) - .addOnSuccessListener(documentReference -> { - //declaring ultimate/final battleResult - thisUid = realBattle.senderUid; - otherUid = userId; - BattleModel battle = new BattleModel(thisUid, otherUid, list, SenderAnsList, reciverAnsList, timestamp, "0", realBattle.battleId, realBattle.getTopic(), true); - //here thisUid (who invited to play) and other is player 2 who got invited and playing now - //none of SenderAnsList(inviter) and receiverAnsList(this) is null - mainDB = FirebaseDatabase.getInstance().getReference(); - //Result senderResult = new Result(battleId, battle.senderUid, userId, getScoreCount(SenderAnsList), getScoreCount(reciverAnsList), topic, timestamp, COMPLETED); - //FirebaseDatabase.getInstance().getReference().child("Result").child(battle.senderUid).child(battle.battleId).setValue(senderResult); - mainDB.child("Play").child(realBattle.battleId).setValue(battle).addOnSuccessListener(aVoid -> { - Intent intent = new Intent(getApplicationContext(), ResultActivity.class); - UpdateFinalResult(battle); - intent.putExtra("FinalResult", battle); - startActivity(intent); - mDialog.dismiss(); - finish(); - }); - }); - - } else if (offlideID != null) { - if (offlineBattleSaving.getWinner().equals("2")) { - Notification notification = new Notification(offlineBattleSaving.getBattleId() ,otherUid, MyName, MyImage, - "challenged you in " + topic, - String.valueOf(System.currentTimeMillis()), - "play" - , battleId, false); - new SendNotificationAsyncTask(notification).execute(); - mFirestore.collection("Users") - .document(otherUid) - .collection("Info_Notifications").document(notification.getId()) - .set(notification) - .addOnSuccessListener(documentReference -> { - thisUid = userId; - BattleModel battleModel; - battleModel = offlineBattleSaving; - battleModel.setSenderAnswerList(SenderAnsList); - battleModel.setWinner("0"); - battleViewModel.insert(battleModel); - Result hisResult = new Result(offlineBattleSaving.battleId, battleModel.getReceiverUid(), userId, getScoreCount(SenderAnsList), -1, topic, timestamp, JUST_IN); - mainDB.child("Result").child(otherUid).child(battleId).setValue(hisResult); - //here thisUid is player who sending invitations and other uid is whom he sending invite - //so senderResult is NonNull and reciverAnsList is Null as he still not able to play. - mainDB = FirebaseDatabase.getInstance().getReference(); - mainDB.child("Play").child(battleId).setValue(battleModel).addOnSuccessListener(aVoid -> { - Intent intent = new Intent(getApplicationContext(), ResultActivity.class); - intent.putExtra("start", battleModel); - startActivity(intent); - mDialog.dismiss(); - finish(); - }); - }); - } else if (offlineBattleSaving.getWinner().equals("3")) { - Notification notification = new Notification(realBattle.getBattleId(),realBattle.senderUid, MyName, MyImage, - "accepted your challenge in " + realBattle.topic, - String.valueOf(System.currentTimeMillis()), - "play_result" - , realBattle.battleId, false); - new SendNotificationAsyncTask(notification).execute(); - mFirestore.collection("Users") - .document(otherUid) - .collection("Info_Notifications").document(notification.getId()) - .set(notification) - .addOnSuccessListener(documentReference -> { - //declaring ultimate/final battleResult - thisUid = realBattle.senderUid; - otherUid = userId; - BattleModel battle = new BattleModel(thisUid, otherUid, list, SenderAnsList, reciverAnsList, timestamp, "0", realBattle.battleId, realBattle.topic, true); - //here thisUid (who invited to play) and other is player 2 who got invited and playing now - //none of SenderAnsList(inviter) and receiverAnsList(this) is null - - // Result senderResult = new Result(realBattle.battleId, realBattle.senderUid, userId, getScoreCount(realBattle.getSenderAnswerList()), getScoreCount(reciverAnsList), topic, timestamp, COMPLETED); - // FirebaseDatabase.getInstance().getReference().child("Result").child(realBattle.senderUid).child(realBattle.battleId).setValue(senderResult); - mainDB.child("Play").child(realBattle.battleId).setValue(battle).addOnSuccessListener(aVoid -> { - Intent intent = new Intent(getApplicationContext(), ResultActivity.class); - UpdateFinalResult(battle); - intent.putExtra("FinalResult", battle); - startActivity(intent); - mDialog.dismiss(); - finish(); - }); - }) - .addOnFailureListener(e -> Log.e("Error", Objects.requireNonNull(e.getLocalizedMessage()))); - } - - } else { - Notification notification = new Notification(battleId,otherUid, MyName, MyImage, - "challenged you in " + topic, - String.valueOf(System.currentTimeMillis()), - "play" - , battleId, false); - new SendNotificationAsyncTask(notification).execute(); - mFirestore.collection("Users") - .document(otherUid) - .collection("Info_Notifications").document(notification.getId()) - .set(notification) - .addOnSuccessListener(documentReference -> { - Result hisResult = new Result(offlineBattleSaving.battleId, offlineBattleSaving.getReceiverUid(), userId, getScoreCount(SenderAnsList), -1, topic, timestamp, JUST_IN); - FirebaseDatabase.getInstance().getReference().child("Result").child(offlineBattleSaving.getReceiverUid()).child(battleId).setValue(hisResult); - mainDB.child("Play").child(offlineBattleSaving.battleId).setValue(offlineBattleSaving).addOnSuccessListener(aVoid -> { - Intent intent = new Intent(getApplicationContext(), ResultActivity.class); - intent.putExtra("start", offlineBattleSaving); - randomiseQuestions(mainDB.child("Topics").child(topic).child(subtopic)); - startActivity(intent); - mDialog.dismiss(); - finish(); - }); - }); - } - } - - private int getScoreCount(List scoreList) { - int score = 0; - for (int i = 0; i < scoreList.size(); i++) { - if (scoreList.get(i)) { - score++; - } - } - return score; - } - - - @SuppressLint("CheckResult") - private void UpdateFinalResult(BattleModel battlePlay) { - int reScore, seScore; - try { - topic = battlePlay.topic; - } catch (NullPointerException ignored) { - - } - reScore = getScoreCount(battlePlay.receiverList); //me 2nd player - seScore = getScoreCount(battlePlay.senderAnswerList); //inviter- 1st player - thisScore.setText(String.valueOf(reScore)); - otherScore.setText(String.valueOf(seScore)); - if (reScore > seScore) { - updateXP(true); - Toasty.success(QuizBattle.this, "Congo, you got 20 XP and 5 point", Toasty.LENGTH_LONG); - addScore(5, battlePlay.receiverUid, "score", true); - addScore(1, battlePlay.receiverUid, "win", true); - addScore(1, battlePlay.senderUid, "lose", false); - Map winner = new HashMap<>(); - winner.put("winner", battlePlay.receiverUid); - battleViewModel.insert(battlePlay); - mainDB.child("Play").child(battlePlay.battleId).updateChildren(winner); - } else if (seScore > reScore) { - Toasty.error(getApplicationContext(), "Damn, you lost", Toasty.LENGTH_LONG); - addScore(1, battlePlay.senderUid, "win", false); - addScore(5, battlePlay.senderUid, "score", false); - addScore(1, battlePlay.receiverUid, "lose", true); - Map winner = new HashMap<>(); - winner.put("winner", battlePlay.senderUid); - battleViewModel.insert(battlePlay); - mainDB.child("Play").child(battlePlay.battleId).updateChildren(winner); - } else { - addScore(2, battlePlay.receiverUid, "score", true); - addScore(2, battlePlay.senderUid, "score", false); - Toasty.info(getApplicationContext(), "Match Drawn", Toasty.LENGTH_LONG); - addScore(1, battlePlay.receiverUid, "draw", true); - addScore(1, battlePlay.senderUid, "draw", false); - Map winner = new HashMap<>(); - winner.put("winner", "draw"); - battleViewModel.insert(battlePlay); - mainDB.child("Play").child(battlePlay.battleId).updateChildren(winner); - } - } - - @Override - public void onBackPressed() { - new MaterialDialog.Builder(this) - .title("Quite?") - .content("Are you sure want to quite and go back, if question time is less than 15s, this question will be count as wrong") - .positiveText("Yes") - .canceledOnTouchOutside(false) - .cancelable(false) - .onPositive((dialog, which) -> { - int seconds = (int) (timeLeftInMillis / 1000) % 60; - if(seconds<15){ - timeLeftInMillis = 0; - countDownTimer.cancel(); - updateCountDownText(); - stepAnsList.add(position, false); - showResult(); - }else{ - countDownTimer.cancel(); - } - finish(); - }) - .negativeText("No") - .show(); - } - - @SuppressLint("SetTextI18n") - public void setLevelByScore(TextView levelTV, int score) { - if (score <= 500) { - levelTV.setText("Level: 1"); - } else if (score <= 1000) { - levelTV.setText("Level: 2"); - } else if (score <= 1500) { - levelTV.setText("Level: 3"); - } else if (score <= 2000) { - levelTV.setText("Level: 4"); - } else if (score <= 2500) { - levelTV.setText("Level: 5"); - } else if (score <= 3500) { - levelTV.setText("Level: 6"); - } else if (score <= 5000) { - levelTV.setText("Level: 7"); - } else { - levelTV.setText("Level: unknown"); - } - } - - private void updateXP( boolean increment) { - int reward = (int) user.getReward(); - if(increment){ - reward+=20; - }else{ - reward-=5; - } - userViewModel.setReward(reward); - HashMap scoreMap = new HashMap<>(); - scoreMap.put("reward", reward); - mFirestore.collection("Users") - .document(userId) - .update(scoreMap).addOnSuccessListener(aVoid -> { - }); - - } - - private static class SendNotificationAsyncTask extends AsyncTask { - final APIService apiService; - final Notification notification; - - private SendNotificationAsyncTask(Notification notification) { - this.notification = notification; - apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class); - } - - @Override - protected Void doInBackground(Void... jk) { - FirebaseDatabase.getInstance().getReference().child("Tokens").child(notification.getNotifyTo()).child("token").addListenerForSingleValueEvent(new ValueEventListener() { - @Override - public void onDataChange(@NonNull DataSnapshot dataSnapshot) { - String usertoken = dataSnapshot.getValue(String.class); - NotificationSender sender = new NotificationSender(notification, usertoken); - apiService.sendNotifcation(sender).enqueue(new Callback() { - @Override - public void onResponse(@NonNull Call call, @NonNull Response response) { - } - - @Override - public void onFailure(@NonNull Call call, @NonNull Throwable t) { - - } - }); - } - - @Override - public void onCancelled(@NonNull DatabaseError databaseError) { - - } - }); - return null; - } - } -} \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Ranking.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Ranking.java deleted file mode 100644 index ff9c362..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Ranking.java +++ /dev/null @@ -1 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; import static com.quantum_guys.dncc_eco_sync.ui.activities.MainActivity.userId; import android.annotation.SuppressLint; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.paging.PagedList; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.firebase.ui.firestore.paging.FirestorePagingAdapter; import com.firebase.ui.firestore.paging.FirestorePagingOptions; import com.firebase.ui.firestore.paging.LoadingState; import com.github.marlonlom.utilities.timeago.TimeAgo; import com.google.android.material.chip.Chip; import com.google.android.material.chip.ChipGroup; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.quantum_guys.dncc_eco_sync.R; import com.quantum_guys.dncc_eco_sync.ui.activities.friends.FriendProfile; import com.quantum_guys.dncc_eco_sync.viewmodel.UserViewModel; import java.util.Objects; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by jhm69 */ public class Ranking extends Fragment { String institu, area, sub, typ; String tag = "All"; private FirebaseFirestore firestore; long t; private RecyclerView mRecyclerView; private SwipeRefreshLayout refreshLayout; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.ranking, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); firestore = FirebaseFirestore.getInstance(); mRecyclerView = view.findViewById(R.id.messageList); refreshLayout = view.findViewById(R.id.refreshLayout); UserViewModel userViewModel = ViewModelProviders.of(requireActivity()).get(UserViewModel.class); Chip location = view.findViewById(R.id.location); Chip institute = view.findViewById(R.id.sub); Chip subject = view.findViewById(R.id.institute); Chip type = view.findViewById(R.id.type); userViewModel.user.observe(getActivity(), users -> { area = users.getLocation(); t = users.getType(); typ = getType(t); institu = users.getInstitute(); sub = users.getDept(); if (area.equals("")) { location.setVisibility(View.GONE); } else { location.setText(area); } if (sub.equals("")) { subject.setVisibility(View.GONE); } else { subject.setText(sub); } if (institu.equals("")) { institute.setVisibility(View.GONE); } else { institute.setText(institu); } if (typ.equals("")) { type.setVisibility(View.GONE); } else { type.setText(typ); } }); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setLayoutManager(new LinearLayoutManager(view.getContext())); mRecyclerView.setHasFixedSize(true); mRecyclerView.addItemDecoration(new DividerItemDecoration(view.getContext(), DividerItemDecoration.VERTICAL)); setupAdapter(tag); ChipGroup chipGroup = view.findViewById(R.id.filter_chip_SS_group); chipGroup.setOnCheckedChangeListener((group, checkedId) -> { try { Chip c = view.findViewById(checkedId); tag = c.getText().toString(); setupAdapter(tag); } catch (NullPointerException ignored) { } }); refreshLayout.setOnRefreshListener(() -> setupAdapter(tag)); } private void setupAdapter(String tag) { PagedList.Config config = new PagedList.Config.Builder() .setEnablePlaceholders(false) .setPrefetchDistance(5) .setPageSize(10) .build(); Query mQuery = firestore.collection("Users") .orderBy("score", Query.Direction.DESCENDING); if (tag.equals("All")) { mQuery = firestore.collection("Users") .orderBy("score", Query.Direction.DESCENDING); } else if (tag.equals(typ)) { mQuery = firestore.collection("Users").whereEqualTo("type", t) .orderBy("score", Query.Direction.DESCENDING); } else if (tag.equals(area)) { mQuery = firestore.collection("Users") .orderBy("score", Query.Direction.DESCENDING).whereEqualTo("location", area); } else if (tag.equals(institu)) { mQuery = firestore.collection("Users") .orderBy("score", Query.Direction.DESCENDING).whereEqualTo("institute", institu); } else if (tag.equals(sub)) { mQuery = firestore.collection("Users") .orderBy("score", Query.Direction.DESCENDING).whereEqualTo("dept", sub); } FirestorePagingOptions options = new FirestorePagingOptions.Builder() .setLifecycleOwner(this) .setQuery(mQuery, config, Player.class) .build(); FirestorePagingAdapter mAdapter = new FirestorePagingAdapter(options) { @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = getLayoutInflater().inflate(R.layout.item_quiz_profile, parent, false); return new ViewHolder(view); } @SuppressLint({"SetTextI18n", "UseCompatLoadingForColorStateLists"}) @Override protected void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull Player user) { requireView().findViewById(R.id.default_item).setVisibility(View.GONE); holder.name.setText(user.getName()); // if(user.getDept().length() > 1 && user.getInstitute().length() > 1) { // holder.institute.setText(user.getDept() + ", " + user.getInstitute()); // }else if (user.getDept().length()<2) { // holder.institute.setText(user.getInstitute()); // } else if (user.getInstitute().length()<2) { // holder.institute.setText(user.getDept()); // } // if(user.getDept().length()<1 && user.getInstitute().length() < 1){ // holder.institute.setVisibility(View.GONE); // } int score = (int) user.getScore(); holder.rank.setVisibility(View.VISIBLE); holder.level.setText(String.valueOf(score)); if (user.getId().equals(userId)) { holder.name.setText("You"); holder.back.setBackgroundColor(Color.parseColor("#DCDCFB")); }else{ holder.back.setBackgroundColor(Color.parseColor("#ffffff")); } holder.time.setText(getTimeText(user.getLastTimestamp())); holder.rank.setText(String.valueOf(position + 1)); Glide.with(requireContext()) .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) .load(user.getImage()) .into(holder.image); holder.mView.setOnClickListener(view -> FriendProfile.startActivity(getContext(), user.getId())); } @Override protected void onError(@NonNull Exception e) { super.onError(e); Log.e("MainActivity", e.getMessage()); } @Override protected void onLoadingStateChanged(@NonNull LoadingState state) { switch (state) { case LOADING_INITIAL: case LOADING_MORE: refreshLayout.setRefreshing(true); break; case LOADED: if (getItemCount() == 0) { requireView().findViewById(R.id.default_item).setVisibility(View.VISIBLE); } refreshLayout.setRefreshing(false); break; case ERROR: Toast.makeText( getActivity(), "Error Occurred!", Toast.LENGTH_SHORT ).show(); refreshLayout.setRefreshing(false); break; case FINISHED: refreshLayout.setRefreshing(false); break; } } }; mRecyclerView.setAdapter(mAdapter); } private String getTimeText(long lastTimestamp) { String time = TimeAgo.using(lastTimestamp); time = time.replaceAll("just now", "now") .replaceAll(" minutes", "m") .replaceAll(" minute", "1m") .replaceAll("about", "") .replaceAll(" hours", "h") .replaceAll(" hour", "1h") .replaceAll(" an", "") .replaceAll("a ", "1 ") .replaceAll(" ago", "") .replaceAll("yesterday", "1d") .replaceAll(" days", "d") .replaceAll(" day", "1d"); return time; } public static class ViewHolder extends RecyclerView.ViewHolder { final View mView; final CircleImageView image; final TextView name; final TextView institute; final TextView level; final TextView rank, time; final ConstraintLayout back; public ViewHolder(View itemView) { super(itemView); mView = itemView; image = mView.findViewById(R.id.image); name = mView.findViewById(R.id.name); institute = mView.findViewById(R.id.institute); level = mView.findViewById(R.id.levelCount); rank = mView.findViewById(R.id.rank); back = mView.findViewById(R.id.back); time = mView.findViewById(R.id.textView4); } } String getType(long t) { if (t == 0) return "bsc"; if (t == 1) return "hsc"; if (t == 2) return "ssc"; else return "bsc"; } } \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Result.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Result.java deleted file mode 100644 index c81d05a..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/Result.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import androidx.annotation.NonNull; -import androidx.room.Entity; -import androidx.room.Ignore; -import androidx.room.PrimaryKey; - -import java.io.Serializable; - -@SuppressWarnings("NotNullFieldNotInitialized") -@Entity -public class Result implements Serializable { - @PrimaryKey - @NonNull - String battleId; - String myUid; - String otherUid; - int myScore, otherScore; - String topic; - String timestamp; - int action; - - @Ignore - public Result() { - } - - public Result(@NonNull String battleId, String myUid, String otherUid, int myScore, int otherScore, String topic, String timestamp, int action) { - this.battleId = battleId; - this.myUid = myUid; - this.otherUid = otherUid; - this.myScore = myScore; - this.otherScore = otherScore; - this.topic = topic; - this.timestamp = timestamp; - this.action = action; - } - - @NonNull - public String getBattleId() { - return battleId; - } - - public void setBattleId(@NonNull String battleId) { - this.battleId = battleId; - } - - public String getMyUid() { - return myUid; - } - - public void setMyUid(String senderUid) { - this.myUid = senderUid; - } - - public String getOtherUid() { - return otherUid; - } - - public void setOtherUid(String otherUid) { - this.otherUid = otherUid; - } - - public int getMyScore() { - return myScore; - } - - public void setMyScore(int myScore) { - this.myScore = myScore; - } - - public int getOtherScore() { - return otherScore; - } - - public void setOtherScore(int otherScore) { - this.otherScore = otherScore; - } - - public String getTopic() { - return topic; - } - - public void setTopic(String topic) { - this.topic = topic; - } - - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - public int getAction() { - return action; - } - - public void setAction(int action) { - this.action = action; - } -} diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/ResultActivity.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/ResultActivity.java deleted file mode 100644 index caa28d4..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/ResultActivity.java +++ /dev/null @@ -1,417 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import static com.quantum_guys.dncc_eco_sync.ui.activities.MainActivity.userId; -import static java.util.Objects.requireNonNull; - -import android.annotation.SuppressLint; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.graphics.Color; -import android.os.Build; -import android.os.Bundle; -import android.util.Log; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.annotation.RequiresApi; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.app.AppCompatDelegate; -import androidx.appcompat.widget.Toolbar; -import androidx.lifecycle.ViewModelProviders; -import androidx.recyclerview.widget.DefaultItemAnimator; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.RequestOptions; -import com.google.firebase.database.DataSnapshot; -import com.google.firebase.database.DatabaseError; -import com.google.firebase.database.DatabaseReference; -import com.google.firebase.database.FirebaseDatabase; -import com.google.firebase.database.Query; -import com.google.firebase.database.ValueEventListener; -import com.google.firebase.firestore.FirebaseFirestore; - -import com.quantum_guys.dncc_eco_sync.R; -import com.quantum_guys.dncc_eco_sync.adapters.ResultEachQuestionAdapter; -import com.quantum_guys.dncc_eco_sync.models.QuestionEachResult; -import com.quantum_guys.dncc_eco_sync.ui.activities.MainActivity; -import com.quantum_guys.dncc_eco_sync.ui.activities.friends.FriendProfile; -import com.quantum_guys.dncc_eco_sync.viewmodel.BattleViewModel; -import com.quantum_guys.dncc_eco_sync.viewmodel.UserViewModel; - -import java.util.ArrayList; -import java.util.List; - -import es.dmoral.toasty.Toasty; - -public class ResultActivity extends AppCompatActivity { - public ProgressDialog mDialog; - String winnerId = "draw"; - Button playAgain; - final List questionEachResultList = new ArrayList<>(); - RecyclerView mRecyclerView; - ResultEachQuestionAdapter resultEachQuestionAdapter; - private BattleModel battlep; - private TextView thisUserName, thisUserLevel, otherUserName, otherUserLevel, thisScore, otherScore, topic, resultText, pointText; - private ImageView otherUserImage, thisUserImage; - - @SuppressLint({"SetTextI18n", "InflateParams"}) - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - SharedPreferences sharedPreferences = getSharedPreferences("Theme", Context.MODE_PRIVATE); - String themeName = sharedPreferences.getString("ThemeName", "Default"); - if (themeName.equalsIgnoreCase("TealTheme")) { - setTheme(R.style.TealTheme); - } else if (themeName.equalsIgnoreCase("VioleteTheme")) { - setTheme(R.style.VioleteTheme); - } else if (themeName.equalsIgnoreCase("PinkTheme")) { - setTheme(R.style.PinkTheme); - } else if (themeName.equalsIgnoreCase("DelRio")) { - setTheme(R.style.DelRio); - } else if (themeName.equalsIgnoreCase("DarkTheme")) { - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); - setTheme(R.style.Dark); - } else if (themeName.equalsIgnoreCase("Lynch")) { - setTheme(R.style.Lynch); - } else { - setTheme(R.style.AppTheme); - } - setContentView(R.layout.activity_result); - Toolbar toolbar = findViewById(R.id.toolbar2); - - - setSupportActionBar(toolbar); - requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); - resultText = findViewById(R.id.resultText); - pointText = findViewById(R.id.textView12); - playAgain = findViewById(R.id.playAgain); - thisUserName = findViewById(R.id.thisUserName); - thisUserLevel = findViewById(R.id.thisUserLevel); - thisUserImage = findViewById(R.id.thisUserImage); - thisScore = findViewById(R.id.myScore); - otherUserName = findViewById(R.id.otherUserName); - - mDialog = new ProgressDialog(this); - mDialog.setMessage("Please wait.."); - mDialog.setIndeterminate(true); - mDialog.setCanceledOnTouchOutside(false); - mDialog.setCancelable(false); - BattleModel battleResult = (BattleModel) getIntent().getSerializableExtra("FinalResult"); - otherUserLevel = findViewById(R.id.otherUserLevel); - otherUserImage = findViewById(R.id.otherUserImage); - otherScore = findViewById(R.id.otherScore); - topic = findViewById(R.id.topic); - BattleViewModel battleViewModel = ViewModelProviders.of(this).get(BattleViewModel.class); - mRecyclerView = findViewById(R.id.jhm69); - String battleIdNew = getIntent().getStringExtra("resultId"); - thisScore.setText(String.valueOf(0)); - resultEachQuestionAdapter = new ResultEachQuestionAdapter(questionEachResultList, ResultActivity.this); - mRecyclerView.setItemAnimator(new DefaultItemAnimator()); - mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); - mRecyclerView.setHasFixedSize(true); - thisScore.setText(String.valueOf(0)); - if (battleIdNew == null && battleResult == null) { - battlep = (BattleModel) getIntent().getSerializableExtra("start"); - try { - for (int i = 0; i < requireNonNull(battlep).questionList.size(); i++) { - QuestionEachResult questionEachResult = new QuestionEachResult(battlep.senderAnswerList.get(i), battlep.questionList.get(i)); - questionEachResultList.add(questionEachResult); - mRecyclerView.setAdapter(resultEachQuestionAdapter); - resultEachQuestionAdapter.notifyDataSetChanged(); - } - } catch (Exception h) { - finish(); - } - - thisScore.setText(String.valueOf(getScoreCount(requireNonNull(battlep).senderAnswerList))); - setUserData(thisUserImage, thisUserName, thisUserLevel, battlep.senderUid, true); - setUserData(otherUserImage, otherUserName, otherUserLevel, battlep.getReceiverUid(), false); - resultText.setTextColor(Color.parseColor("#5570A0")); - playAgain.setText("Go Back to home"); - resultText.setText("Waiting for opponent to play"); - pointText.setText(""); - otherScore.setText("-"); - playAgain.setOnClickListener(view -> startActivity(new Intent(getApplication(), MainActivity.class))); - } else if (battleResult != null) { - try { - doThings(battleResult); - }catch (Exception f){ - Toasty.error(getApplicationContext(), "Battle Result not found", Toast.LENGTH_SHORT).show(); - finish(); - } - } else { - try { - battleViewModel.get(battleIdNew).observe(this, battlep -> { - if(battlep!=null){ - Log.d("TBUG", "fromElse"); - doThingsForMe(requireNonNull(battlep)); - }else{ - Toasty.error(getApplicationContext(), "Battle Result not found", Toast.LENGTH_SHORT).show(); - finish(); - } - }); - } catch (Exception j) { - if (battlep == null && questionEachResultList.size()==0) { - mDialog.show(); - DatabaseReference mDb = FirebaseDatabase.getInstance().getReference(); - Query query = mDb.child("Play").orderByChild("battleId").equalTo(battleIdNew); - query.addListenerForSingleValueEvent(new ValueEventListener() { - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - @Override - public void onDataChange(@NonNull DataSnapshot snapshot) { - for (DataSnapshot data : snapshot.getChildren()) { - battlep = data.getValue(BattleModel.class); - } - doThingsForMe(requireNonNull(battlep)); - mDialog.dismiss(); - } - - @Override - public void onCancelled(@NonNull DatabaseError error) { - } - }); - } - } - } - } - - - private void setUserData(ImageView proPic, TextView name, TextView level, String uid, boolean me) { - try { - if (me) { - UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class); - userViewModel.user.observe(this, me1 -> { - name.setText(me1.getUsername()); - setLevelByScore(level, (int) me1.getScore()); - Glide.with(getApplicationContext()) - .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) - .load(me1.getImage()) - .into(proPic); - }); - } else { - FirebaseFirestore.getInstance().collection("Users") - .document(uid) - .get() - .addOnSuccessListener(documentSnapshot -> { - name.setText(documentSnapshot.getString("username")); - try { - setLevelByScore(level, Integer.parseInt(String.valueOf(documentSnapshot.getLong("score")))); - Glide.with(getApplicationContext()) - .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) - .load(documentSnapshot.getString("image")) - .into(proPic); - }catch (Exception ignored){ - - } - }); - } - } catch (NullPointerException ignored) { - - } - name.setOnClickListener(v ->{ - startActivity(new Intent(getApplicationContext(), FriendProfile.class).putExtra("f_id", uid)); - }); - proPic.setOnClickListener(v -> { - startActivity(new Intent(getApplicationContext(), FriendProfile.class).putExtra("f_id", uid)); - }); - } - - private int getScoreCount(List scoreList) { - int score = 0; - try { - for (int i = 0; i < scoreList.size(); i++) { - if (scoreList.get(i)) { - score++; - } - } - }catch (Exception ignored){ - - } - return score; - } - - - @SuppressLint("SetTextI18n") - private void doThings(BattleModel battlePlay) { - int reScore, seScore; - reScore = getScoreCount(battlePlay.receiverList); //me - seScore = getScoreCount(battlePlay.senderAnswerList); //other - topic.setText(battlePlay.getTopic()); - if (battlePlay.receiverUid.equals(userId)) { - thisScore.setText(String.valueOf(reScore)); - otherScore.setText(String.valueOf(seScore)); - try { - questionEachResultList.clear(); - for (int i = 0; i < battlePlay.questionList.size(); i++) { - QuestionEachResult questionEachResult = new QuestionEachResult(battlePlay.receiverList.get(i), battlePlay.senderAnswerList.get(i), battlePlay.questionList.get(i)); - questionEachResultList.add(questionEachResult); - mRecyclerView.setAdapter(resultEachQuestionAdapter); - resultEachQuestionAdapter.notifyDataSetChanged(); - } - } catch (Exception ignored) { - - } - setUserData(thisUserImage, thisUserName, thisUserLevel, battlePlay.receiverUid, true); - setUserData(otherUserImage, otherUserName, otherUserLevel, battlePlay.senderUid, false); - if (reScore > seScore) { - resultText.setText("Congratulations, You Won!"); - winnerId = battlePlay.receiverUid; - resultText.setTextColor(Color.parseColor("#4BBB4F")); - pointText.setText("you have got 5 point"); - } else if (seScore > reScore) { - winnerId = battlePlay.senderUid; - resultText.setText("Damn, You Lost!"); - resultText.setTextColor(Color.parseColor("#D32F2F")); - pointText.setText("Better luck next time"); - } else { - resultText.setText("Match Drawn!"); - resultText.setTextColor(Color.parseColor("#5570A0")); - pointText.setText("You were too close winning. got 2 point"); - } - playAgain.setOnClickListener(view -> { - Intent goBattle = new Intent(getApplicationContext(), SelectTopic.class); - goBattle.putExtra("otherUid", battlePlay.senderUid); - startActivity(goBattle); - }); - } - topic.setText(battlePlay.topic); - } - - @SuppressLint("SetTextI18n") - private void doThingsForMe(BattleModel battlePlay) { - if (battlePlay.receiverUid.equals(userId)) { - try { - int reScore, seScore; - reScore = getScoreCount(battlePlay.receiverList); //me - seScore = getScoreCount(battlePlay.senderAnswerList); //other - topic.setText(battlePlay.getTopic()); - thisScore.setText(String.valueOf(reScore)); - otherScore.setText(String.valueOf(seScore)); - try { - questionEachResultList.clear(); - for (int i = 0; i < battlePlay.questionList.size(); i++) { - QuestionEachResult questionEachResult = new QuestionEachResult(battlePlay.receiverList.get(i), battlePlay.senderAnswerList.get(i), battlePlay.questionList.get(i)); - questionEachResultList.add(questionEachResult); - mRecyclerView.setAdapter(resultEachQuestionAdapter); - resultEachQuestionAdapter.notifyDataSetChanged(); - } - } catch (Exception ignored) { - - } - setUserData(thisUserImage, thisUserName, thisUserLevel, battlePlay.receiverUid, true); - setUserData(otherUserImage, otherUserName, otherUserLevel, battlePlay.senderUid, false); - if (reScore > seScore) { - resultText.setText("Congratulations, You Won!"); - winnerId = battlePlay.receiverUid; - resultText.setTextColor(Color.parseColor("#4BBB4F")); - pointText.setText("you have got 5 point"); - } else if (seScore > reScore) { - winnerId = battlePlay.senderUid; - resultText.setText("Damn, You Lost!"); - resultText.setTextColor(Color.parseColor("#D32F2F")); - pointText.setText("Better luck next time"); - } else { - resultText.setText("Match Drawn!"); - resultText.setTextColor(Color.parseColor("#5570A0")); - pointText.setText("You were too close winning, Still 2 point"); - } - playAgain.setOnClickListener(view -> { - Intent goBattle = new Intent(getApplicationContext(), SelectTopic.class); - goBattle.putExtra("otherUid", battlePlay.senderUid); - startActivity(goBattle); - }); - }catch (Exception ignored){ - - } - } else { - int reScore, seScore; - reScore = getScoreCount(battlePlay.receiverList); - seScore = getScoreCount(battlePlay.senderAnswerList); - topic.setText(battlePlay.topic); - thisScore.setText(String.valueOf(seScore)); - otherScore.setText(String.valueOf(reScore)); - setUserData(thisUserImage, thisUserName, thisUserLevel, battlePlay.senderUid, true); - setUserData(otherUserImage, otherUserName, otherUserLevel, battlePlay.receiverUid, false); - try { - questionEachResultList.clear(); - for (int i = 0; i < battlePlay.questionList.size(); i++) { - QuestionEachResult questionEachResult = new QuestionEachResult(battlePlay.senderAnswerList.get(i), battlePlay.receiverList.get(i), battlePlay.questionList.get(i)); - questionEachResultList.add(questionEachResult); - mRecyclerView.setAdapter(resultEachQuestionAdapter); - resultEachQuestionAdapter.notifyDataSetChanged(); - } - if (seScore > reScore) { - resultText.setText("Congratulations, You Won!"); - winnerId = battlePlay.senderUid; - resultText.setTextColor(Color.parseColor("#4BBB4F")); - pointText.setText("you have got 5 point"); - } else if (reScore > seScore) { - winnerId = battlePlay.receiverUid; - resultText.setText("Damn, You Lost!"); - resultText.setTextColor(Color.parseColor("#D32F2F")); - pointText.setText("Better luck next time"); - } else { - resultText.setText("Match Drawn!"); - resultText.setTextColor(Color.parseColor("#5570A0")); - pointText.setText("You were too close winning, Still 2 point"); - } - playAgain.setOnClickListener(view -> { - Intent goBattle = new Intent(getApplicationContext(), SelectTopic.class); - goBattle.putExtra("otherUid", battlePlay.receiverUid); - startActivity(goBattle); - }); - } catch (Exception k) { - questionEachResultList.clear(); - for (int i = 0; i < battlePlay.questionList.size(); i++) { - QuestionEachResult questionEachResult = new QuestionEachResult(battlePlay.senderAnswerList.get(i), null, battlePlay.questionList.get(i)); - questionEachResultList.add(questionEachResult); - mRecyclerView.setAdapter(resultEachQuestionAdapter); - resultEachQuestionAdapter.notifyDataSetChanged(); - } - otherScore.setText("-"); - resultText.setText("Waiting..."); - resultText.setTextColor(Color.parseColor("#4BBB4F")); - pointText.setText("Waiting for opponent to play"); - } - } - } - - @SuppressLint("SetTextI18n") - private void setLevelByScore(TextView levelTV, int score) { - if (score <= 500) { - levelTV.setText("Level: 1"); - } else if (score <= 1000) { - levelTV.setText("Level: 2"); - } else if (score <= 1500) { - levelTV.setText("Level: 3"); - } else if (score <= 2000) { - levelTV.setText("Level: 4"); - } else if (score <= 2500) { - levelTV.setText("Level: 5"); - } else if (score <= 3500) { - levelTV.setText("Level: 6"); - } else if (score <= 5000) { - levelTV.setText("Level: 7"); - } else { - levelTV.setText("Level: unknown"); - } - } - - @Override - public void onBackPressed() { - finish(); - super.onBackPressed(); - } - @Override - public boolean onSupportNavigateUp() { - onBackPressed(); - return true; - } -} \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/SelectTopic.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/SelectTopic.java deleted file mode 100644 index 32338b2..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/SelectTopic.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import android.content.Context; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.util.Log; -import android.view.View; -import android.view.Window; -import android.widget.ProgressBar; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.app.AppCompatDelegate; -import androidx.recyclerview.widget.GridLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.google.firebase.database.DataSnapshot; -import com.google.firebase.database.DatabaseError; -import com.google.firebase.database.DatabaseReference; -import com.google.firebase.database.FirebaseDatabase; -import com.google.firebase.database.ValueEventListener; -import com.google.firebase.firestore.DocumentChange; -import com.google.firebase.firestore.FirebaseFirestore; - -import com.quantum_guys.dncc_eco_sync.R; -import com.quantum_guys.dncc_eco_sync.adapters.TopicAdapter; -import com.quantum_guys.dncc_eco_sync.models.Friends; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import es.dmoral.toasty.Toasty; - -public class SelectTopic extends AppCompatActivity { - final List topics = new ArrayList<>(); - long ty; - private RecyclerView recyclerView; - // private RecyclerView.LayoutManager layoutManager; - private TopicAdapter capterAdapter; - private String otherUid; - - @Override - protected void onCreate(Bundle savedInstanceState) { - requestWindowFeature(Window.FEATURE_NO_TITLE); - getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); - - super.onCreate(savedInstanceState); - SharedPreferences sharedPreferences = getSharedPreferences("Theme", Context.MODE_PRIVATE); - String themeName = sharedPreferences.getString("ThemeName", "Default"); - if (themeName.equalsIgnoreCase("TealTheme")) { - setTheme(R.style.TealTheme); - } else if (themeName.equalsIgnoreCase("VioleteTheme")) { - setTheme(R.style.VioleteTheme); - } else if (themeName.equalsIgnoreCase("PinkTheme")) { - setTheme(R.style.PinkTheme); - } else if (themeName.equalsIgnoreCase("DelRio")) { - setTheme(R.style.DelRio); - } else if (themeName.equalsIgnoreCase("DarkTheme")) { - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); - setTheme(R.style.Dark); - } else if (themeName.equalsIgnoreCase("Lynch")) { - setTheme(R.style.Lynch); - } else { - setTheme(R.style.AppTheme); - } - setContentView(R.layout.activity_all_parent_topic); - ProgressBar loading = findViewById(R.id.progressBar2); - recyclerView = findViewById(R.id.rcv); - GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2); - recyclerView.setLayoutManager(gridLayoutManager); - recyclerView.setAdapter(capterAdapter);//set adapter to recyclerview - //recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); - //recyclerView.setLayoutManager(layoutManager); - //layoutManager = new LinearLayoutManager(getApplicationContext()); - // toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccentt)); - recyclerView.setHasFixedSize(true); - - - otherUid = getIntent().getStringExtra("otherUid"); - ty = getIntent().getLongExtra("type", 99); - if (ty == 99) { - Toasty.info(this, "Wait some time...", Toast.LENGTH_SHORT).show(); - FirebaseFirestore firestore = FirebaseFirestore.getInstance(); - firestore.collection("Users").whereEqualTo("id", otherUid) - .get() - .addOnSuccessListener(queryDocumentSnapshots -> { - if (!queryDocumentSnapshots.getDocuments().isEmpty()) { - for (final DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) { - Friends friends = doc.getDocument().toObject(Friends.class).withId(Objects.requireNonNull(doc.getDocument().getString("id"))); - ty = friends.getType(); - } - - String type = getType(ty); - Log.d("Typee-SelectTopic", type); - DatabaseReference itemsRef = FirebaseDatabase.getInstance().getReference().child("Topics").child(type); - ValueEventListener eventListener = new ValueEventListener() { - @Override - public void onDataChange(DataSnapshot dataSnapshot) { - for (DataSnapshot ds : dataSnapshot.getChildren()) { - String name = ds.getKey(); - topics.add(name); - capterAdapter = new TopicAdapter(topics, SelectTopic.this, otherUid, type); - recyclerView.setAdapter(capterAdapter); - capterAdapter.notifyDataSetChanged(); - loading.setVisibility(View.GONE); - } - } - - @Override - public void onCancelled(@NonNull DatabaseError databaseError) { - } - }; - itemsRef.addListenerForSingleValueEvent(eventListener); - } - }) - .addOnFailureListener(e -> { - - }); - } else { - String type = getType(ty); - DatabaseReference itemsRef = FirebaseDatabase.getInstance().getReference().child("Topics").child(type); - ValueEventListener eventListener = new ValueEventListener() { - @Override - public void onDataChange(DataSnapshot dataSnapshot) { - for (DataSnapshot ds : dataSnapshot.getChildren()) { - String name = ds.getKey(); - topics.add(name); - capterAdapter = new TopicAdapter(topics, SelectTopic.this, otherUid, type); - recyclerView.setAdapter(capterAdapter); - capterAdapter.notifyDataSetChanged(); - loading.setVisibility(View.GONE); - } - } - - @Override - public void onCancelled(@NonNull DatabaseError databaseError) { - } - }; - itemsRef.addListenerForSingleValueEvent(eventListener); - } - } - - String getType(long t) { - if (t == 0) return "bsc"; - if (t == 1) return "hsc"; - if (t == 2) return "ssc"; - else return "bsc"; - } - - @Override - public void onBackPressed() { - finish(); - } -} \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/StepView.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/StepView.java deleted file mode 100644 index 24166fc..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/StepView.java +++ /dev/null @@ -1,996 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import android.animation.Animator; -import android.animation.ValueAnimator; -import android.annotation.SuppressLint; -import android.annotation.TargetApi; -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Rect; -import android.graphics.Typeface; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.text.Layout; -import android.text.StaticLayout; -import android.text.TextPaint; -import android.util.AttributeSet; -import android.view.MotionEvent; -import android.view.View; - -import androidx.annotation.ColorInt; -import androidx.annotation.Dimension; -import androidx.annotation.IntDef; -import androidx.annotation.Nullable; -import androidx.core.content.ContextCompat; -import androidx.core.content.res.ResourcesCompat; -import androidx.core.graphics.ColorUtils; -import androidx.core.view.ViewCompat; - -import com.quantum_guys.dncc_eco_sync.R; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.ArrayList; -import java.util.List; - -@SuppressWarnings("IntegerDivisionInFloatingPointContext") -public class StepView extends View { - - public static final int ANIMATION_LINE = 0; - public static final int ANIMATION_CIRCLE = 1; - public static final int ANIMATION_ALL = 2; - public static final int ANIMATION_NONE = 3; - public static final int DISPLAY_MODE_WITH_TEXT = 0; - public static final int DISPLAY_MODE_NO_TEXT = 1; - private static final int ANIMATE_STEP_TRANSITION = 0; - private static final int IDLE = 1; - private static final int START_STEP = 0; - public static List stepAnsList = new ArrayList<>(); - private final List steps = new ArrayList<>(); - private final Paint paint; - private final TextPaint textPaint; - private final Rect bounds = new Rect(); - private OnStepClickListener onStepClickListener; - @DisplayMode - private int displayMode = DISPLAY_MODE_WITH_TEXT; - // for display mode DISPLAY_MODE_NO_TEXT - private int stepsNumber = 0; - private int currentStep = START_STEP; - private int nextAnimatedStep; - private int state = IDLE; - @AnimationType - private int animationType; - @ColorInt - private int selectedCircleColor; - @Dimension - private int selectedCircleRadius; - @ColorInt - private int selectedTextColor; - @ColorInt - private int doneCircleColor; - @Dimension - private int doneCircleRadius; - @ColorInt - private int doneTextColor; - @ColorInt - private int nextTextColor; - @Dimension - private int stepPadding; - @ColorInt - private int nextStepLineColor; - @ColorInt - private int doneStepLineColor; - @Dimension - private int stepLineWidth; - @Dimension(unit = Dimension.SP) - private float textSize; - @Dimension - private int textPadding; - private int selectedStepNumberColor; - @Dimension(unit = Dimension.SP) - private float stepNumberTextSize; - @ColorInt - private int doneStepMarkColor; - private int animationDuration; - private boolean nextStepCircleEnabled; - @ColorInt - private int nextStepCircleColor; - private ValueAnimator animator; - private int[] circlesX; - private int[] startLinesX; - private int[] endLinesX; - private float[] constraints; - private int circlesY; - private int textY; - private float animatedFraction; - private boolean done; - private StaticLayout[] textLayouts; - - public StepView(Context context) { - this(context, null); - } - - public StepView(Context context, AttributeSet attrs) { - this(context, attrs, R.attr.sv_stepViewStyle); - } - - public StepView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - paint = new Paint(Paint.ANTI_ALIAS_FLAG); - paint.setTextAlign(Paint.Align.CENTER); - textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); - textPaint.setTextAlign(Paint.Align.CENTER); - applyStyles(context, attrs, defStyleAttr); - drawEditMode(); - } - - private void applyStyles(Context context, AttributeSet attrs, int defStyleAttr) { - TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.StepView, defStyleAttr, R.style.StepView); - selectedCircleColor = ta.getColor(R.styleable.StepView_sv_selectedCircleColor, 0); - selectedCircleRadius = ta.getDimensionPixelSize(R.styleable.StepView_sv_selectedCircleRadius, 0); - selectedTextColor = ta.getColor(R.styleable.StepView_sv_selectedTextColor, 0); - selectedStepNumberColor = ta.getColor(R.styleable.StepView_sv_selectedStepNumberColor, 0); - doneStepMarkColor = ta.getColor(R.styleable.StepView_sv_doneStepMarkColor, 0); - doneCircleColor = ta.getColor(R.styleable.StepView_sv_doneCircleColor, 0); - doneCircleRadius = ta.getDimensionPixelSize(R.styleable.StepView_sv_doneCircleRadius, 0); - doneTextColor = ta.getColor(R.styleable.StepView_sv_doneTextColor, 0); - nextTextColor = ta.getColor(R.styleable.StepView_sv_nextTextColor, 0); - stepPadding = ta.getDimensionPixelSize(R.styleable.StepView_sv_stepPadding, 0); - nextStepLineColor = ta.getColor(R.styleable.StepView_sv_nextStepLineColor, 0); - doneStepLineColor = ta.getColor(R.styleable.StepView_sv_doneStepLineColor, 0); - stepLineWidth = ta.getDimensionPixelSize(R.styleable.StepView_sv_stepLineWidth, 0); - textPadding = ta.getDimensionPixelSize(R.styleable.StepView_sv_textPadding, 0); - stepNumberTextSize = ta.getDimension(R.styleable.StepView_sv_stepNumberTextSize, 0); - textSize = ta.getDimension(R.styleable.StepView_sv_textSize, 0); - animationDuration = ta.getInteger(R.styleable.StepView_sv_animationDuration, 0); - animationType = ta.getInteger(R.styleable.StepView_sv_animationType, 0); - stepsNumber = ta.getInteger(R.styleable.StepView_sv_stepsNumber, 0); - nextStepCircleEnabled = ta.getBoolean(R.styleable.StepView_sv_nextStepCircleEnabled, false); - nextStepCircleColor = ta.getColor(R.styleable.StepView_sv_nextStepCircleColor, 0); - CharSequence[] descriptions = ta.getTextArray(R.styleable.StepView_sv_steps); - if (descriptions != null) { - for (CharSequence description : descriptions) { - steps.add(description.toString()); - } - displayMode = DISPLAY_MODE_WITH_TEXT; - } else { - displayMode = DISPLAY_MODE_NO_TEXT; - } - Drawable background = ta.getDrawable(R.styleable.StepView_sv_background); - if (background != null) { - setBackgroundDrawable(background); - } - int fontId = ta.getResourceId(R.styleable.StepView_sv_typeface, 0); - if (fontId != 0) { - Typeface typeface = ResourcesCompat.getFont(context, fontId); - setTypeface(typeface); - } - textPaint.setTextSize(textSize); - ta.recycle(); - } - - private void setTypeface(Typeface typeface) { - if (typeface != null) { - textPaint.setTypeface(typeface); - paint.setTypeface(typeface); - } - } - - private void drawEditMode() { - if (isInEditMode()) { - if (displayMode == DISPLAY_MODE_WITH_TEXT) { - if (steps.isEmpty()) { - steps.add("Step 1"); - steps.add("Step 2"); - steps.add("Step 3"); - } - setSteps(steps); - } else { - if (stepsNumber == 0) { - stepsNumber = 4; - } - setStepsNumber(stepsNumber); - } - } - } - - @SuppressLint("ClickableViewAccessibility") - @Override - public boolean onTouchEvent(MotionEvent event) { - final boolean superResult = super.onTouchEvent(event); - if (onStepClickListener != null && isEnabled()) { - final int action = event.getActionMasked(); - if (action == MotionEvent.ACTION_UP) { - float x = event.getX(); - float y = event.getY(); - int step = getStepByPointer(x); - onStepClickListener.onStepClick(step); - } - } - return superResult; - } - - protected int getStepByPointer(float x) { - int count = getStepCount(); - for (int i = 0; i < constraints.length; i++) { - float constraint = constraints[i]; - if (x <= constraint) { - return i; - } - } - return count - 1; - } - - public void setOnStepClickListener(OnStepClickListener listener) { - setClickable(listener != null); - onStepClickListener = listener; - } - - public void setSteps(List steps) { - stepsNumber = 0; - displayMode = DISPLAY_MODE_WITH_TEXT; - this.steps.clear(); - this.steps.addAll(steps); - requestLayout(); - go(START_STEP, false, false); - } - - public void setStepsNumber(int number) { - steps.clear(); - displayMode = DISPLAY_MODE_NO_TEXT; - stepsNumber = number; - requestLayout(); - go(START_STEP, false, false); - } - - public State getState() { - return new State(); - } - - public void go(int step, boolean animate, boolean correct) { - stepAnsList.add(step, correct); - if (step >= START_STEP && step < getStepCount()) { - if (animate && animationType != ANIMATION_NONE && startLinesX != null) { - if (Math.abs(step - currentStep) > 1) { - endAnimation(); - currentStep = step; - invalidate(); - } else { - nextAnimatedStep = step; - state = ANIMATE_STEP_TRANSITION; - animate(step); - invalidate(); - } - } else { - currentStep = step; - invalidate(); - } - } - } - - public void done(boolean isDone) { - done = isDone; - invalidate(); - } - - private void endAnimation() { - if (animator != null && animator.isRunning()) { - animator.end(); - } - } - - private void animate(final int step) { - endAnimation(); - animator = getAnimator(step); - if (animator == null) { - return; - } - animator.addUpdateListener(valueAnimator -> { - animatedFraction = valueAnimator.getAnimatedFraction(); - invalidate(); - }); - animator.addListener(new AnimatorListener() { - @Override - public void onAnimationEnd(Animator animator) { - state = IDLE; - currentStep = step; - invalidate(); - } - }); - animator.setDuration(animationDuration); - animator.start(); - } - - @Nullable - private ValueAnimator getAnimator(int step) { - ValueAnimator animator = null; - final int i; - if (step > currentStep) { - if (animationType == ANIMATION_LINE) { - i = step - 1; - animator = ValueAnimator.ofInt(startLinesX[i], endLinesX[i]); - } else if (animationType == ANIMATION_CIRCLE) { - animator = ValueAnimator.ofInt(0, selectedCircleRadius); - } else if (animationType == ANIMATION_ALL) { - i = step - 1; - animator = ValueAnimator.ofInt(0, (endLinesX[i] - startLinesX[i] + selectedCircleRadius) / 2); - } - } else if (step < currentStep) { - if (animationType == ANIMATION_LINE) { - i = step; - animator = ValueAnimator.ofInt(endLinesX[i], startLinesX[i]); - } else if (animationType == ANIMATION_CIRCLE) { - animator = ValueAnimator.ofInt(0, selectedCircleRadius); - } else if (animationType == ANIMATION_ALL) { - i = step; - animator = ValueAnimator.ofInt(0, (endLinesX[i] - startLinesX[i] + selectedCircleRadius) / 2); - } - } - return animator; - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - if (animator != null && animator.isRunning()) { - animator.cancel(); - } - } - - public int getCurrentStep() { - return currentStep; - } - - public int getStepCount() { - return displayMode == DISPLAY_MODE_WITH_TEXT ? steps.size() : stepsNumber; - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int width = measureWidth(widthMeasureSpec); - if (getStepCount() == 0) { - setMeasuredDimension(width, 0); - return; - } - if (width == 0) { - setMeasuredDimension(width, 0); - return; - } - measureConstraints(width); - int height = measureHeight(heightMeasureSpec); - setMeasuredDimension(width, height); - measureAttributes(); - } - - private int measureWidth(int widthMeasureSpec) { - return MeasureSpec.getSize(widthMeasureSpec); - } - - private void measureConstraints(int width) { - constraints = new float[getStepCount()]; - constraints[0] = width / getStepCount(); - for (int i = 1; i < constraints.length; i++) { - constraints[i] = constraints[0] * (i + 1); - } - } - - private int measureHeight(int heightMeasureSpec) { - int specSize = MeasureSpec.getSize(heightMeasureSpec); - int specMode = MeasureSpec.getMode(heightMeasureSpec); - int desiredSize = getPaddingTop() - + getPaddingBottom() - + (Math.max(selectedCircleRadius, doneCircleRadius)) * 2 - + (displayMode == DISPLAY_MODE_WITH_TEXT ? textPadding : 0); - if (!steps.isEmpty()) { - desiredSize += measureStepsHeight(); - } - int result = 0; - - switch (specMode) { - case MeasureSpec.UNSPECIFIED: - // Parent says we can be as big as we want. - result = desiredSize; - break; - case MeasureSpec.AT_MOST: - // Parent says we can be as big as we want, up to specSize. - // Don't be larger than specSize - result = Math.min(desiredSize, specSize); - break; - case MeasureSpec.EXACTLY: - // No choice. Do what we are told. - result = specSize; - break; - } - - return result; - } - - private int measureStepsHeight() { - textLayouts = new StaticLayout[steps.size()]; - textPaint.setTextSize(textSize); - int max = 0; - for (int i = 0; i < steps.size(); i++) { - String text = steps.get(i); - Layout.Alignment alignment = - isRtl() ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_NORMAL; - textLayouts[i] = new StaticLayout( - text, - textPaint, - getMeasuredWidth() / steps.size(), - alignment, - 1, - 0, - true - ); - int height = textLayouts[i].getHeight(); - max = Math.max(height, max); - } - return max; - } - - @SuppressLint("WrongConstant") - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) - private boolean isRtl() { - return ViewCompat.getLayoutDirection(this) == View.LAYOUT_DIRECTION_RTL; - } - - private void measureAttributes() { - circlesY = getCircleY(); - if (displayMode == DISPLAY_MODE_NO_TEXT) { - circlesY += getPaddingTop(); - } - circlesX = getCirclePositions(); - if (displayMode == DISPLAY_MODE_NO_TEXT) { - paint.setTextSize(stepNumberTextSize); - } else { - paint.setTextSize(stepNumberTextSize); - paint.setTextSize(textSize); - textY = circlesY + selectedCircleRadius + textPadding; - } - measureLines(); - } - - private int getCircleY() { - int availableHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); - if (displayMode == DISPLAY_MODE_NO_TEXT) { - return availableHeight / 2; - } - int maxItemHeight = getMaxTextHeight() + Math.max(selectedCircleRadius, doneCircleRadius) + textPadding; - int additionalPadding = (availableHeight - maxItemHeight) / 2; - return getPaddingTop() + additionalPadding + selectedCircleRadius; - } - - private int getMaxTextHeight() { - int max = 0; - if (textLayouts == null || textLayouts.length == 0) { - return max; - } - for (StaticLayout tl : textLayouts) { - max = Math.max(tl.getHeight(), max); - } - return max; - } - - private int[] getCirclePositions() { - int stepsCount = getStepCount(); - int[] result = new int[stepsCount]; - - if (result.length == 0) { - return result; - } - - result[0] = getStartCirclePosition(); - - if (result.length == 1) { - return result; - } - - result[stepsCount - 1] = getEndCirclePosition(); - - if (result.length < 3) { - return result; - } - - float spaceLeft = isRtl() ? result[0] - result[stepsCount - 1] : result[stepsCount - 1] - result[0]; - int margin = (int) (spaceLeft / (stepsCount - 1)); - - if (isRtl()) { - for (int i = 1; i < stepsCount - 1; i++) { - result[i] = result[i - 1] - margin; - } - } else { - for (int i = 1; i < stepsCount - 1; i++) { - result[i] = result[i - 1] + margin; - } - } - - return result; - } - - private int getStartCirclePosition() { - int result; - if (displayMode == DISPLAY_MODE_WITH_TEXT) { - if (isRtl()) { - result = getMeasuredWidth() - getPaddingRight() - - Math.max(getMaxLineWidth(textLayouts[0]) / 2, selectedCircleRadius); - } else { - result = getPaddingLeft() + Math.max(getMaxLineWidth(textLayouts[0]) / 2, selectedCircleRadius); - } - } else { - if (isRtl()) { - result = getMeasuredWidth() - getPaddingRight() - selectedCircleRadius; - } else { - result = getPaddingLeft() + selectedCircleRadius; - } - } - return result; - } - - private int getMaxLineWidth(StaticLayout layout) { - int lineCount = layout.getLineCount(); - int max = 0; - for (int i = 0; i < lineCount; i++) { - max = (int) Math.max(layout.getLineWidth(i), max); - } - return max; - } - - private int getEndCirclePosition() { - int result; - if (displayMode == DISPLAY_MODE_WITH_TEXT) { - if (isRtl()) { - result = getPaddingLeft() + - Math.max(getMaxLineWidth(last(textLayouts)) / 2, selectedCircleRadius); - } else { - result = getMeasuredWidth() - getPaddingRight() - - Math.max(getMaxLineWidth(last(textLayouts)) / 2, selectedCircleRadius); - } - } else { - if (isRtl()) { - result = getPaddingLeft() + selectedCircleRadius; - } else { - result = getMeasuredWidth() - getPaddingRight() - selectedCircleRadius; - } - } - return result; - } - - private T last(T[] array) { - return array[array.length - 1]; - } - - private void measureLines() { - startLinesX = new int[getStepCount() - 1]; - endLinesX = new int[getStepCount() - 1]; - int padding = stepPadding + selectedCircleRadius; - - for (int i = 1; i < getStepCount(); i++) { - if (isRtl()) { - startLinesX[i - 1] = circlesX[i - 1] - padding; - endLinesX[i - 1] = circlesX[i] + padding; - } else { - startLinesX[i - 1] = circlesX[i - 1] + padding; - endLinesX[i - 1] = circlesX[i] - padding; - } - } - } - - @Override - protected void onDraw(Canvas canvas) { - if (getHeight() == 0) return; - - final int stepSize = getStepCount(); - - if (stepSize == 0) { - return; - } - - for (int i = 0; i < stepSize; i++) { - drawStep(canvas, i, circlesX[i], circlesY, stepAnsList.get(i)); - } - - for (int i = 0; i < startLinesX.length; i++) { - if (state == ANIMATE_STEP_TRANSITION && i == nextAnimatedStep - 1 - && nextAnimatedStep > currentStep && (animationType == ANIMATION_LINE || animationType == ANIMATION_ALL)) { - int animatedX = (int) (startLinesX[i] + animatedFraction * (endLinesX[i] - startLinesX[i])); - drawLine(canvas, startLinesX[i], animatedX, circlesY, true); - drawLine(canvas, animatedX, endLinesX[i], circlesY, false); - } else if (state == ANIMATE_STEP_TRANSITION && i == nextAnimatedStep - && nextAnimatedStep < currentStep && (animationType == ANIMATION_LINE || animationType == ANIMATION_ALL)) { - int animatedX = (int) (endLinesX[i] - animatedFraction * (endLinesX[i] - startLinesX[i])); - drawLine(canvas, startLinesX[i], animatedX, circlesY, true); - drawLine(canvas, animatedX, endLinesX[i], circlesY, false); - } else drawLine(canvas, startLinesX[i], endLinesX[i], circlesY, i < currentStep); - } - } - - private void drawStep(Canvas canvas, int step, int circleCenterX, int circleCenterY, boolean hoiche_naki) { - final String text = displayMode == DISPLAY_MODE_WITH_TEXT ? steps.get(step) : ""; - final boolean isSelected = step == currentStep; - final boolean isDone = done ? step <= currentStep : step < currentStep; - final String number = String.valueOf(step + 1); - - if (isSelected && !isDone) { - paint.setColor(selectedCircleColor); - int radius; - if (state == ANIMATE_STEP_TRANSITION && (animationType == ANIMATION_CIRCLE || animationType == ANIMATION_ALL) - && nextAnimatedStep < currentStep) { - if (!nextStepCircleEnabled || nextStepCircleColor == 0) { - radius = (int) (selectedCircleRadius - selectedCircleRadius * animatedFraction); - } else { - radius = selectedCircleRadius; - } - if (nextStepCircleEnabled && nextStepCircleColor != 0) { - paint.setColor(ColorUtils.blendARGB( - selectedCircleColor, - nextStepCircleColor, - animatedFraction) - ); - } - } else { - radius = selectedCircleRadius; - } - - canvas.drawCircle(circleCenterX, circleCenterY, radius, paint); - paint.setColor(selectedStepNumberColor); - paint.setTextSize(stepNumberTextSize); - drawNumber(canvas, number, circleCenterX, paint); - textPaint.setTextSize(textSize); - textPaint.setColor(selectedTextColor); - drawText(canvas, text, textY, step); - } else if (isDone) { - if (hoiche_naki) { - paint.setColor(ContextCompat.getColor(getContext(), R.color.green)); - canvas.drawCircle(circleCenterX, circleCenterY, doneCircleRadius, paint); - drawCheckMark(canvas, circleCenterX, circleCenterY); - } else { - paint.setColor(ContextCompat.getColor(getContext(), R.color.red)); - canvas.drawCircle(circleCenterX, circleCenterY, doneCircleRadius, paint); - drawUnCheckMark(canvas, circleCenterX, circleCenterY); - } - - if (state == ANIMATE_STEP_TRANSITION && step == nextAnimatedStep && nextAnimatedStep < currentStep) { - paint.setColor(selectedTextColor); - int alpha = Math.max(Color.alpha(doneTextColor), (int) (animatedFraction * 255)); - paint.setAlpha(alpha); - } else { - paint.setColor(doneTextColor); - } - textPaint.setTextSize(textSize); - textPaint.setColor(doneTextColor); - //drawText(canvas, text, textY, step); - } else { - if (state == ANIMATE_STEP_TRANSITION && step == nextAnimatedStep && nextAnimatedStep > currentStep) { - if (animationType == ANIMATION_CIRCLE || animationType == ANIMATION_ALL) { - if (nextStepCircleEnabled && nextStepCircleColor != 0) { - paint.setColor(ColorUtils.blendARGB( - nextStepCircleColor, - selectedCircleColor, - animatedFraction) - ); - canvas.drawCircle(circleCenterX, circleCenterY, selectedCircleRadius, paint); - } else { - int animatedRadius = (int) (selectedCircleRadius * animatedFraction); - paint.setColor(selectedCircleColor); - canvas.drawCircle(circleCenterX, circleCenterY, animatedRadius, paint); - } - } - if (animationType != ANIMATION_NONE) { - if (animationType == ANIMATION_CIRCLE || animationType == ANIMATION_ALL) { - paint.setColor(selectedStepNumberColor); - int alpha = (int) (animatedFraction * 255); - paint.setAlpha(alpha); - paint.setTextSize(stepNumberTextSize * animatedFraction); - } else { - paint.setTextSize(stepNumberTextSize); - paint.setColor(nextTextColor); - } - } else { - paint.setTextSize(stepNumberTextSize); - paint.setColor(nextTextColor); - } - drawNumber(canvas, number, circleCenterX, paint); - - textPaint.setTextSize(textSize); - textPaint.setColor(nextTextColor); - int alpha = (int) Math.max(Color.alpha(nextTextColor), animatedFraction * 255); - textPaint.setAlpha(alpha); - } else { - if (nextStepCircleEnabled && nextStepCircleColor != 0) { - paint.setColor(nextStepCircleColor); - canvas.drawCircle(circleCenterX, circleCenterY, selectedCircleRadius, paint); - } - - paint.setColor(nextTextColor); - - paint.setTextSize(stepNumberTextSize); - drawNumber(canvas, number, circleCenterX, paint); - - textPaint.setTextSize(textSize); - textPaint.setColor(nextTextColor); - } - drawText(canvas, text, textY, step); - } - } - - private void drawNumber(Canvas canvas, String number, int circleCenterX, Paint paint) { - paint.getTextBounds(number, 0, number.length(), bounds); - float y = circlesY + bounds.height() / 2f - bounds.bottom; - canvas.drawText(number, circleCenterX, y, paint); - } - - private void drawText(Canvas canvas, String text, int y, int step) { - if (text.isEmpty()) { - return; - } - StaticLayout layout = textLayouts[step]; - canvas.save(); - canvas.translate(circlesX[step], y); - layout.draw(canvas); - canvas.restore(); - } - - private void drawCheckMark(Canvas canvas, int circleCenterX, int circleCenterY) { - paint.setColor(doneStepMarkColor); - float width = stepNumberTextSize * 0.1f; - paint.setStrokeWidth(width); - Rect bounds = new Rect( - (int) (circleCenterX - width * 4.5), - (int) (circleCenterY - width * 3.5), - (int) (circleCenterX + width * 4.5), - (int) (circleCenterY + width * 3.5)); - canvas.drawLine( - bounds.left + 0.5f * width, - bounds.bottom - 3.25f * width, - bounds.left + 3.25f * width, - bounds.bottom - 0.75f * width, paint); - canvas.drawLine( - bounds.left + 2.75f * width, - bounds.bottom - 0.75f * width, - bounds.right - 0.375f * width, - bounds.top + 0.75f * width, paint); - } - - private void drawUnCheckMark(Canvas canvas, int circleCenterX, int circleCenterY) { - paint.setColor(doneStepMarkColor); - float width = stepNumberTextSize * 0.1f; - paint.setStrokeWidth(width); - Rect bounds = new Rect( - (int) (circleCenterX - width * 0.5), - (int) (circleCenterY - width * 3.5), - (int) (circleCenterX + width * 0.5), - (int) (circleCenterY + width * 5.5)); - - canvas.drawLine( - bounds.right + 2.75f * width, - bounds.top - 0.75f * width, - bounds.left - 3.375f * width, - bounds.bottom + 0.75f * width - , paint); - canvas.drawLine( - bounds.left + 2.75f * width, - bounds.bottom - 0.75f * width, - bounds.right - 3.375f * width, - bounds.top + 0.75f * width - , paint); - } - - private void drawLine(Canvas canvas, int startX, int endX, int centerY, boolean highlight) { - if (highlight) { - paint.setColor(doneStepLineColor); - } else { - paint.setColor(nextStepLineColor); - } - paint.setStrokeWidth(stepLineWidth); - canvas.drawLine(startX, centerY, endX, centerY, paint); - } - - public interface OnStepClickListener { - void onStepClick(int step); - } - - - @Retention(RetentionPolicy.SOURCE) - @IntDef({ANIMATION_LINE, ANIMATION_CIRCLE, ANIMATION_ALL, ANIMATION_NONE}) - public @interface AnimationType { - } - - - @Retention(RetentionPolicy.SOURCE) - @IntDef({DISPLAY_MODE_WITH_TEXT, DISPLAY_MODE_NO_TEXT}) - public @interface DisplayMode { - } - - public class State { - private List steps; - private int stepsNumber; - @AnimationType - private int animationType = StepView.this.animationType; - @ColorInt - private int selectedCircleColor = StepView.this.selectedCircleColor; - @Dimension - private int selectedCircleRadius = StepView.this.selectedCircleRadius; - @ColorInt - private int selectedTextColor = StepView.this.selectedTextColor; - @ColorInt - private int doneCircleColor = StepView.this.doneCircleColor; - @Dimension - private int doneCircleRadius = StepView.this.doneCircleRadius; - @ColorInt - private int doneTextColor = StepView.this.doneTextColor; - @ColorInt - private int nextTextColor = StepView.this.nextTextColor; - @Dimension - private int stepPadding = StepView.this.stepPadding; - @ColorInt - private int nextStepLineColor = StepView.this.nextStepLineColor; - @ColorInt - private int doneStepLineColor = StepView.this.doneStepLineColor; - @Dimension - private int stepLineWidth = StepView.this.stepLineWidth; - @Dimension(unit = Dimension.SP) - private float textSize = StepView.this.textSize; - @Dimension - private int textPadding = StepView.this.textPadding; - @ColorInt - private int selectedStepNumberColor = StepView.this.selectedStepNumberColor; - @Dimension(unit = Dimension.SP) - private float stepNumberTextSize = StepView.this.stepNumberTextSize; - @ColorInt - private int doneStepMarkColor = StepView.this.doneStepMarkColor; - private int animationDuration = StepView.this.animationDuration; - private boolean nextStepCircleEnabled = StepView.this.nextStepCircleEnabled; - @ColorInt - private int nextStepCircleColor = StepView.this.nextStepCircleColor; - private Typeface typeface = paint.getTypeface(); - - public State animationType(@AnimationType int animationType) { - this.animationType = animationType; - return this; - } - - public State selectedCircleColor(@ColorInt int selectedCircleColor) { - this.selectedCircleColor = selectedCircleColor; - return this; - } - - public State selectedCircleRadius(@Dimension int selectedCircleRadius) { - this.selectedCircleRadius = selectedCircleRadius; - return this; - } - - public State selectedTextColor(@ColorInt int selectedTextColor) { - this.selectedTextColor = selectedTextColor; - return this; - } - - public State doneCircleColor(@ColorInt int doneCircleColor) { - this.doneCircleColor = doneCircleColor; - return this; - } - - public State doneCircleRadius(@Dimension int doneCircleRadius) { - this.doneCircleRadius = doneCircleRadius; - return this; - } - - public State doneTextColor(@ColorInt int doneTextColor) { - this.doneTextColor = doneTextColor; - return this; - } - - public State nextTextColor(@ColorInt int nextTextColor) { - this.nextTextColor = nextTextColor; - return this; - } - - public State stepPadding(@Dimension int stepPadding) { - this.stepPadding = stepPadding; - return this; - } - - public State nextStepLineColor(@ColorInt int nextStepLineColor) { - this.nextStepLineColor = nextStepLineColor; - return this; - } - - public State doneStepLineColor(@ColorInt int doneStepLineColor) { - this.doneStepLineColor = doneStepLineColor; - return this; - } - - public State stepLineWidth(@Dimension int stepLineWidth) { - this.stepLineWidth = stepLineWidth; - return this; - } - - public State textSize(@Dimension(unit = Dimension.SP) int textSize) { - this.textSize = textSize; - return this; - } - - public State textPadding(@Dimension int textPadding) { - this.textPadding = textPadding; - return this; - } - - public State selectedStepNumberColor(@ColorInt int selectedStepNumberColor) { - this.selectedStepNumberColor = selectedStepNumberColor; - return this; - } - - public State stepNumberTextSize(@Dimension(unit = Dimension.SP) int stepNumberTextSize) { - this.stepNumberTextSize = stepNumberTextSize; - return this; - } - - public State doneStepMarkColor(@ColorInt int doneStepMarkColor) { - this.doneStepMarkColor = doneStepMarkColor; - return this; - } - - public State animationDuration(int animationDuration) { - this.animationDuration = animationDuration; - return this; - } - - public State steps(List steps) { - this.steps = steps; - return this; - } - - public State stepsNumber(int stepsNumber) { - this.stepsNumber = stepsNumber; - return this; - } - - public State typeface(Typeface typeface) { - this.typeface = typeface; - return this; - } - - public State nextStepCircleEnabled(boolean enabled) { - this.nextStepCircleEnabled = enabled; - return this; - } - - public State nextStepCircleColor(@ColorInt int color) { - this.nextStepCircleColor = color; - return this; - } - - public void commit() { - StepView.this.animationType = animationType; - StepView.this.selectedTextColor = selectedTextColor; - StepView.this.selectedCircleRadius = selectedCircleRadius; - StepView.this.selectedCircleColor = selectedCircleColor; - StepView.this.doneCircleColor = doneCircleColor; - StepView.this.doneCircleRadius = doneCircleRadius; - StepView.this.doneTextColor = doneTextColor; - StepView.this.nextTextColor = nextTextColor; - StepView.this.stepPadding = stepPadding; - StepView.this.nextStepLineColor = nextStepLineColor; - StepView.this.doneStepLineColor = doneStepLineColor; - StepView.this.stepLineWidth = stepLineWidth; - StepView.this.textSize = textSize; - StepView.this.textPadding = textPadding; - StepView.this.selectedStepNumberColor = selectedStepNumberColor; - StepView.this.stepNumberTextSize = stepNumberTextSize; - StepView.this.doneStepMarkColor = doneStepMarkColor; - StepView.this.animationDuration = animationDuration; - setTypeface(typeface); - StepView.this.nextStepCircleEnabled = nextStepCircleEnabled; - StepView.this.nextStepCircleColor = nextStepCircleColor; - if (steps != null && !StepView.this.steps.equals(steps)) { - StepView.this.setSteps(steps); - } else if (stepsNumber != 0 && stepsNumber != StepView.this.stepsNumber) { - StepView.this.setStepsNumber(stepsNumber); - } else { - StepView.this.invalidate(); - } - } - } -} diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/SubTopic.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/SubTopic.java deleted file mode 100644 index 99b379c..0000000 --- a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/quiz/SubTopic.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; - -import android.content.Context; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.transition.Explode; -import android.util.Log; -import android.view.View; -import android.view.Window; -import android.widget.ProgressBar; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.app.AppCompatDelegate; -import androidx.recyclerview.widget.GridLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.google.firebase.database.ChildEventListener; -import com.google.firebase.database.DataSnapshot; -import com.google.firebase.database.DatabaseError; -import com.google.firebase.database.FirebaseDatabase; - -import com.quantum_guys.dncc_eco_sync.R; -import com.quantum_guys.dncc_eco_sync.adapters.SubTopicAdapter; -import com.quantum_guys.dncc_eco_sync.models.SubTopicModel; - -import java.util.ArrayList; -import java.util.List; - -public class SubTopic extends AppCompatActivity { - final List subTopics = new ArrayList<>(); - String topic, otherUid, type; - private RecyclerView recyclerView; - private RecyclerView.LayoutManager layoutManager; - private SubTopicAdapter capterAdapter; - - @Override - protected void onCreate(Bundle savedInstanceState) { - requestWindowFeature(Window.FEATURE_NO_TITLE); - getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); - getWindow().setEnterTransition(new Explode()); - getWindow().setExitTransition(new Explode()); - - super.onCreate(savedInstanceState); - SharedPreferences sharedPreferences = getSharedPreferences("Theme", Context.MODE_PRIVATE); - String themeName = sharedPreferences.getString("ThemeName", "Default"); - if (themeName.equalsIgnoreCase("TealTheme")) { - setTheme(R.style.TealTheme); - } else if (themeName.equalsIgnoreCase("VioleteTheme")) { - setTheme(R.style.VioleteTheme); - } else if (themeName.equalsIgnoreCase("PinkTheme")) { - setTheme(R.style.PinkTheme); - } else if (themeName.equalsIgnoreCase("DelRio")) { - setTheme(R.style.DelRio); - } else if (themeName.equalsIgnoreCase("DarkTheme")) { - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); - setTheme(R.style.Dark); - } else if (themeName.equalsIgnoreCase("Lynch")) { - setTheme(R.style.Lynch); - } else { - setTheme(R.style.AppTheme); - } - setContentView(R.layout.activity_all_parent_topic); - ProgressBar loading = findViewById(R.id.progressBar2); - topic = getIntent().getStringExtra("topic"); - type = getIntent().getStringExtra("type"); - otherUid = getIntent().getStringExtra("otherUid"); - recyclerView = findViewById(R.id.rcv); - - GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2); - recyclerView.setLayoutManager(gridLayoutManager); - recyclerView.setAdapter(capterAdapter); - recyclerView.setHasFixedSize(true); - Log.d("Typee-SubTopic", type); - FirebaseDatabase.getInstance().getReference().child("Topics").child(type).child(topic).child("all_totpics").addChildEventListener(new ChildEventListener() { - @Override - public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { - SubTopicModel subTopic = snapshot.getValue(SubTopicModel.class); - subTopics.add(subTopic); - capterAdapter = new SubTopicAdapter(subTopics, topic, SubTopic.this, otherUid, type); - recyclerView.setAdapter(capterAdapter); - capterAdapter.notifyDataSetChanged(); - loading.setVisibility(View.GONE); - } - - @Override - public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { - - } - - @Override - public void onChildRemoved(@NonNull DataSnapshot snapshot) { - - } - - @Override - public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { - - } - - @Override - public void onCancelled(@NonNull DatabaseError error) { - - } - }); - } - - -} diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/friends/FriendProfile.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/FriendProfile.java similarity index 100% rename from android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/friends/FriendProfile.java rename to android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/FriendProfile.java diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/Ranking.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/Ranking.java new file mode 100644 index 0000000..808f414 --- /dev/null +++ b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/Ranking.java @@ -0,0 +1 @@ +package com.quantum_guys.dncc_eco_sync.ui.activities.quiz; import static com.quantum_guys.dncc_eco_sync.ui.activities.MainActivity.userId; import android.annotation.SuppressLint; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.Fragment; import androidx.paging.PagedList; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.firebase.ui.firestore.paging.FirestorePagingAdapter; import com.firebase.ui.firestore.paging.FirestorePagingOptions; import com.firebase.ui.firestore.paging.LoadingState; import com.github.marlonlom.utilities.timeago.TimeAgo; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.quantum_guys.dncc_eco_sync.R; import com.quantum_guys.dncc_eco_sync.ui.activities.friends.FriendProfile; import java.util.Arrays; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by jhm69 */ public class Ranking extends Fragment { String institu, area, sub, typ; String ward = "All"; private FirebaseFirestore firestore; long t; private RecyclerView mRecyclerView; private SwipeRefreshLayout refreshLayout; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.ranking, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); firestore = FirebaseFirestore.getInstance(); mRecyclerView = view.findViewById(R.id.messageList); refreshLayout = view.findViewById(R.id.refreshLayout); List wards = Arrays.asList(getResources().getStringArray(R.array.wards)); Spinner spinner_wards = view.findViewById(R.id.spinner_class_level); ArrayAdapter spinnerArrayAdapter_type = new ArrayAdapter<>(requireActivity(), android.R.layout.simple_spinner_dropdown_item, wards); spinner_wards.setAdapter(spinnerArrayAdapter_type); spinner_wards.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView parent, View view, int position, long id) { ward = wards.get(position); setupAdapter(ward); } public void onNothingSelected(AdapterView parent) { ward = "All"; } }); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setLayoutManager(new LinearLayoutManager(view.getContext())); mRecyclerView.setHasFixedSize(true); mRecyclerView.addItemDecoration(new DividerItemDecoration(view.getContext(), DividerItemDecoration.VERTICAL)); refreshLayout.setOnRefreshListener(() -> setupAdapter(ward)); } private void setupAdapter(String ward) { PagedList.Config config = new PagedList.Config.Builder() .setEnablePlaceholders(false) .setPrefetchDistance(5) .setPageSize(10) .build(); Query mQuery = firestore.collection("Users") .orderBy("score", Query.Direction.DESCENDING); if (!ward.equals("All")) { mQuery = mQuery.whereEqualTo("ward", ward); } FirestorePagingOptions options = new FirestorePagingOptions.Builder() .setLifecycleOwner(this) .setQuery(mQuery, config, Player.class) .build(); FirestorePagingAdapter mAdapter = new FirestorePagingAdapter(options) { @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = getLayoutInflater().inflate(R.layout.item_quiz_profile, parent, false); return new ViewHolder(view); } @SuppressLint({"SetTextI18n", "UseCompatLoadingForColorStateLists"}) @Override protected void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull Player user) { requireView().findViewById(R.id.default_item).setVisibility(View.GONE); holder.name.setText(user.getName()); // if(user.getDept().length() > 1 && user.getInstitute().length() > 1) { // holder.institute.setText(user.getDept() + ", " + user.getInstitute()); // }else if (user.getDept().length()<2) { // holder.institute.setText(user.getInstitute()); // } else if (user.getInstitute().length()<2) { // holder.institute.setText(user.getDept()); // } // if(user.getDept().length()<1 && user.getInstitute().length() < 1){ // holder.institute.setVisibility(View.GONE); // } int score = (int) user.getScore(); holder.rank.setVisibility(View.VISIBLE); holder.level.setText(String.valueOf(score)); if (user.getId().equals(userId)) { holder.name.setText("You"); holder.back.setBackgroundColor(Color.parseColor("#DCDCFB")); }else{ holder.back.setBackgroundColor(Color.parseColor("#ffffff")); } holder.time.setText(getTimeText(user.getLastTimestamp())); holder.rank.setText(String.valueOf(position + 1)); Glide.with(requireContext()) .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) .load(user.getImage()) .into(holder.image); holder.mView.setOnClickListener(view -> FriendProfile.startActivity(getContext(), user.getId())); } @Override protected void onError(@NonNull Exception e) { super.onError(e); Log.e("MainActivity", e.getMessage()); } @Override protected void onLoadingStateChanged(@NonNull LoadingState state) { switch (state) { case LOADING_INITIAL: case LOADING_MORE: refreshLayout.setRefreshing(true); break; case LOADED: if (getItemCount() == 0) { requireView().findViewById(R.id.default_item).setVisibility(View.VISIBLE); } refreshLayout.setRefreshing(false); break; case ERROR: Toast.makeText( getActivity(), "Error Occurred!", Toast.LENGTH_SHORT ).show(); refreshLayout.setRefreshing(false); break; case FINISHED: refreshLayout.setRefreshing(false); break; } } }; mRecyclerView.setAdapter(mAdapter); } private String getTimeText(long lastTimestamp) { String time = TimeAgo.using(lastTimestamp); time = time.replaceAll("just now", "now") .replaceAll(" minutes", "m") .replaceAll(" minute", "1m") .replaceAll("about", "") .replaceAll(" hours", "h") .replaceAll(" hour", "1h") .replaceAll(" an", "") .replaceAll("a ", "1 ") .replaceAll(" ago", "") .replaceAll("yesterday", "1d") .replaceAll(" days", "d") .replaceAll(" day", "1d"); return time; } public static class ViewHolder extends RecyclerView.ViewHolder { final View mView; final CircleImageView image; final TextView name; final TextView institute; final TextView level; final TextView rank, time; final ConstraintLayout back; public ViewHolder(View itemView) { super(itemView); mView = itemView; image = mView.findViewById(R.id.image); name = mView.findViewById(R.id.name); institute = mView.findViewById(R.id.institute); level = mView.findViewById(R.id.levelCount); rank = mView.findViewById(R.id.rank); back = mView.findViewById(R.id.back); time = mView.findViewById(R.id.textView4); } } String getType(long t) { if (t == 0) return "bsc"; if (t == 1) return "hsc"; if (t == 2) return "ssc"; else return "bsc"; } } \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/friends/SearchUsersActivity.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/SearchUsersActivity.java similarity index 100% rename from android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/friends/SearchUsersActivity.java rename to android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/SearchUsersActivity.java diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/friends/quiz_history.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/quiz_history.java similarity index 100% rename from android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/friends/quiz_history.java rename to android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/volunteer/quiz_history.java diff --git a/android-app/app/src/main/res/drawable/border_background.xml b/android-app/app/src/main/res/drawable/border_background.xml new file mode 100644 index 0000000..3ef8998 --- /dev/null +++ b/android-app/app/src/main/res/drawable/border_background.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/android-app/app/src/main/res/layout/activity_issue_details.xml b/android-app/app/src/main/res/layout/activity_issue_details.xml new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/res/layout/frag_admin.xml b/android-app/app/src/main/res/layout/frag_admin.xml new file mode 100644 index 0000000..e69de29 diff --git a/android-app/app/src/main/res/xml/issue.xml b/android-app/app/src/main/res/xml/issue.xml new file mode 100644 index 0000000..e69de29 From 300fd9926c849339c205645f20aab627f5c58209 Mon Sep 17 00:00:00 2001 From: JHM69 Date: Fri, 10 May 2024 14:45:08 -0700 Subject: [PATCH 3/4] app ui updated --- .../.idea/deploymentTargetSelector.xml | 4 +- android-app/app/src/main/AndroidManifest.xml | 25 +- .../adapters/CommentsAdapter.java | 2 +- .../adapters/FriendRequestAdapter.java | 2 +- .../adapters/IssueViewHolder.java | 454 ++++++------------ .../adapters/NotificationsAdapter.java | 2 +- .../adapters/PostViewHolder.java | 11 +- .../dncc_eco_sync/adapters/TripAdapter.java | 2 +- .../searchFriends/SearchFriendAdapter.java | 2 +- .../viewFriends/ViewFriendAdapter.java | 2 +- .../messege/activity/MessageActivity.java | 2 +- .../dncc_eco_sync/models/Issue.java | 4 + .../dncc_eco_sync/models/Notification.java | 6 +- .../dncc_eco_sync/models/Post.java | 2 +- .../dncc_eco_sync/service/UploadService.java | 91 +++- .../ui/activities/MainActivity.java | 65 +-- .../ui/activities/issue/Address.java | 46 ++ .../ui/activities/issue/Example.java | 149 ++++++ .../activities/issue/GeocodingResponse.java | 23 + .../activities/issue/GoogleMapsApiClient.java | 32 ++ .../issue/GoogleMapsApiService.java | 13 + .../issue/IssuesDetailsActivity.java | 403 +++++----------- .../activities/issue/OpenMapsApiClient.java | 20 +- .../activities/issue/OpenMapsApiService.java | 11 +- .../ui/activities/issue/PostIssue.java | 83 +++- .../ui/activities/nearbysts/MapView.java | 6 +- .../ui/activities/nearbysts/NearbySts.java | 12 +- .../nearbysts/NearbyStsService.java | 13 + .../activities/nearbysts/RetrofitClient.java | 18 + .../ui/activities/post/CommentsActivity.java | 3 +- .../ui/activities/post/WhoLikedActivity.java | 2 +- .../activities/volunteer/FriendProfile.java | 2 +- .../ui/activities/volunteer/Ranking.java | 2 +- .../volunteer/SearchUsersActivity.java | 2 +- .../ui/activities/volunteer/quiz_history.java | 2 +- .../dncc_eco_sync/ui/fragment/Dashboard.java | 10 +- .../dncc_eco_sync/ui/fragment/Issue.java | 26 +- .../ui/fragment/admin/AdminFragment.java | 2 +- .../dncc_eco_sync/utils/NotificationUtil.java | 2 +- .../main/res/drawable/border_background.xml | 11 +- .../res/layout/activity_issue_details.xml | 445 +++++++++++++++++ .../main/res/layout/activity_issue_image.xml | 28 +- .../main/res/layout/activity_search_users.xml | 2 +- .../app/src/main/res/layout/frag_admin.xml | 87 ++++ .../app/src/main/res/layout/frag_issue.xml | 2 +- .../main/res/layout/fragment_quiz_history.xml | 2 +- .../main/res/layout/latex_editor_toolbar.xml | 2 +- .../app/src/main/res/layout/ranking.xml | 2 +- .../app/src/main/res/menu/menu_admin.xml | 2 +- .../app/src/main/res/values/arrays.xml | 29 +- .../app/src/main/res/values/strings.xml | 2 +- .../xml/frag_home_xml_framelayout3_scene.xml | 2 +- android-app/app/src/main/res/xml/issue.xml | 78 +++ 53 files changed, 1489 insertions(+), 763 deletions(-) diff --git a/android-app/.idea/deploymentTargetSelector.xml b/android-app/.idea/deploymentTargetSelector.xml index eda0e01..42283ba 100644 --- a/android-app/.idea/deploymentTargetSelector.xml +++ b/android-app/.idea/deploymentTargetSelector.xml @@ -4,10 +4,10 @@