Commit 1ad4e397 authored by Chamod Ishankha's avatar Chamod Ishankha

add baby api connect

parent 644d4077
......@@ -3,7 +3,20 @@
<component name="deploymentTargetDropDown">
<value>
<entry key="app">
<State />
<State>
<runningDeviceTargetSelectedWithDropDown>
<Target>
<type value="RUNNING_DEVICE_TARGET" />
<deviceKey>
<Key>
<type value="SERIAL_NUMBER" />
<value value="adb-AYAV6R3925006878-kh1m4J._adb-tls-connect._tcp" />
</Key>
</deviceKey>
</Target>
</runningDeviceTargetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2024-05-21T16:09:48.003353300Z" />
</State>
</entry>
</value>
</component>
......
......@@ -45,6 +45,8 @@ dependencies {
implementation(libs.jackson.databind)
implementation(libs.ucrop)
implementation(libs.swiperefreshlayout)
implementation(libs.converter.jackson)
implementation(libs.jackson.datatype.jsr310)
testImplementation(libs.junit)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)
......
......@@ -31,6 +31,7 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.kaluwa.enterprises.babycare.MainActivity;
import com.kaluwa.enterprises.babycare.R;
import com.kaluwa.enterprises.babycare.adapter.BabyDashboardAdapter;
......@@ -38,6 +39,7 @@ import com.kaluwa.enterprises.babycare.config.ApiConfig;
import com.kaluwa.enterprises.babycare.dialogs.AddBabyDialog;
import com.kaluwa.enterprises.babycare.dto.BabyDto;
import com.kaluwa.enterprises.babycare.dto.responseDto.AuthenticationDto;
import com.kaluwa.enterprises.babycare.error.ErrorDto;
import com.kaluwa.enterprises.babycare.service.BabyApiService;
import java.time.LocalDate;
......@@ -45,6 +47,10 @@ import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class BabyDashboardActivity extends AppCompatActivity implements AddBabyDialog.BabyDialogInterface {
private final static String TAG = "BabyDashboardActivity";
......@@ -56,6 +62,8 @@ public class BabyDashboardActivity extends AppCompatActivity implements AddBabyD
private View overlay;
private SpinKitView progressbar;
private BabyApiService babyApiService;
private BabyDashboardAdapter adapter;
private List<BabyDto> babyDtoList = new ArrayList<>();
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
......@@ -81,28 +89,10 @@ public class BabyDashboardActivity extends AppCompatActivity implements AddBabyD
overlay = findViewById(R.id.overlay);
progressbar = findViewById(R.id.progress_bar);
List<BabyDto> babyDtoList = new ArrayList<>();
BabyDto baby1 = new BabyDto();
baby1.setFirstName("Chamod");
baby1.setLastName("Ishankha");
baby1.setDob(LocalDate.parse("2000/07/23", DateTimeFormatter.ofPattern("yyyy/MM/dd")));
baby1.setSex("Male");
baby1.setActive(true);
BabyDto baby2 = new BabyDto();
baby2.setFirstName("Yohani");
baby2.setLastName("Madusha");
baby2.setDob(LocalDate.parse("2000/11/01", DateTimeFormatter.ofPattern("yyyy/MM/dd")));
baby2.setSex("Female");
baby2.setActive(false);
baby2.setNotes("My little cute daughter, Love you my darling.");
babyDtoList.add(baby1);
babyDtoList.add(baby2);
if (babyDtoList.isEmpty()) {
tvNoContent.setVisibility(View.VISIBLE);
}
BabyDashboardAdapter adapter = new BabyDashboardAdapter(this, babyDtoList);
// load data
loadData();
adapter = new BabyDashboardAdapter(this, babyDtoList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
......@@ -112,6 +102,68 @@ public class BabyDashboardActivity extends AppCompatActivity implements AddBabyD
});
}
private void loadData() {
Call<List<BabyDto>> call = babyApiService.getAllBabies();
loader(overlay, progressbar, true);
noContentCall();
call.enqueue(new Callback<List<BabyDto>>() {
@Override
public void onResponse(Call<List<BabyDto>> call, Response<List<BabyDto>> response) {
if (response.isSuccessful()) {
List<BabyDto> newBabyDtoList = new ArrayList<>();
if (response.body() != null) {
newBabyDtoList = response.body();
}
// Assuming babyDtoList is a class member
// Check for changes and update the list accordingly
if (babyDtoList == null) {
babyDtoList = newBabyDtoList;
adapter.notifyItemRangeInserted(0, newBabyDtoList.size());
} else {
// Here, you might want to implement a diffing algorithm
// For simplicity, let's assume you replace the entire list
babyDtoList.clear();
babyDtoList.addAll(newBabyDtoList);
adapter.notifyDataSetChanged();
}
noContentCall();
loader(overlay, progressbar, false);
} else {
try {
Gson gson = new Gson();
assert response.errorBody() != null;
String errorBodyString = response.errorBody().string();
// Check if the error body is in JSON format
if (errorBodyString.startsWith("{")) {
ErrorDto errorDto = gson.fromJson(errorBodyString, ErrorDto.class);
Toast.makeText(BabyDashboardActivity.this, errorDto.getMessage(), Toast.LENGTH_LONG).show();
} else {
// If the error body is not in JSON format, display a generic error message
Log.e(TAG, errorBodyString);
Toast.makeText(BabyDashboardActivity.this, "An unexpected error occurred", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(TAG, "else-error: " + e.getMessage());
Toast.makeText(BabyDashboardActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
noContentCall();
loader(overlay, progressbar, false);
}
}
@Override
public void onFailure(Call<List<BabyDto>> call, Throwable throwable) {
noContentCall();
Log.e(TAG, throwable.getMessage());
Toast.makeText(BabyDashboardActivity.this, "Error to Failure", Toast.LENGTH_LONG).show();
loader(overlay, progressbar, false);
}
});
}
private void openAddBabyDialog() {
AddBabyDialog addbabyDialog = new AddBabyDialog();
addbabyDialog.show(getSupportFragmentManager(), "ADD_BABY_DIALOG");
......@@ -191,17 +243,67 @@ public class BabyDashboardActivity extends AppCompatActivity implements AddBabyD
}
@Override
public void parseValues(BabyDto dto, AlertDialog dialog, View overlay, SpinKitView progressbar) {
dto.setUserId(authDto.getUserId());
public void parseValues(BabyDto baby, AlertDialog dialog, View overlay, SpinKitView progressbar) {
baby.setUserId(authDto.getUserId());
Button positiveBtn = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
Button negativeBtn = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
loader(overlay, progressbar, true);
positiveBtn.setEnabled(false);
negativeBtn.setEnabled(false);
Call<BabyDto> call = babyApiService.addBaby(baby);
call.enqueue(new Callback<BabyDto>() {
@Override
public void onResponse(Call<BabyDto> call, Response<BabyDto> response) {
if (response.isSuccessful()) {
loadData();
Toast.makeText(BabyDashboardActivity.this, "New baby added to your list.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
loader(overlay, progressbar, false);
} else {
try {
Gson gson = new Gson();
assert response.errorBody() != null;
String errorBodyString = response.errorBody().string();
// Check if the error body is in JSON format
if (errorBodyString.startsWith("{")) {
ErrorDto errorDto = gson.fromJson(errorBodyString, ErrorDto.class);
Toast.makeText(BabyDashboardActivity.this, errorDto.getMessage(), Toast.LENGTH_LONG).show();
} else {
// If the error body is not in JSON format, display a generic error message
Log.e(TAG, errorBodyString);
Toast.makeText(BabyDashboardActivity.this, "An unexpected error occurred", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(TAG, "else-error: " + e.getMessage());
Toast.makeText(BabyDashboardActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
positiveBtn.setEnabled(true);
negativeBtn.setEnabled(true);
loader(overlay, progressbar, false);
}
}
@Override
public void onFailure(Call<BabyDto> call, Throwable throwable) {
Toast.makeText(BabyDashboardActivity.this, "Error to Failure", Toast.LENGTH_LONG).show();
positiveBtn.setEnabled(true);
negativeBtn.setEnabled(true);
loader(overlay, progressbar, false);
}
});
// TODO
// make api caller
// make photo selector
// make dropdowns
}
void noContentCall() {
if (babyDtoList.isEmpty()) {
tvNoContent.setVisibility(View.VISIBLE);
} else {
tvNoContent.setVisibility(View.GONE);
}
}
}
\ No newline at end of file
......@@ -385,7 +385,7 @@ public class UserProfileActivity extends AppCompatActivity {
userDto.setPhone(mobileNumber);
if (!TextUtils.isEmpty(etDob.getText().toString())) {
LocalDate dob = LocalDate.parse(etDob.getText().toString(), getDateTimeFormatter());
userDto.setDob(dob.toString());
userDto.setDob(dob);
}
}
......
package com.kaluwa.enterprises.babycare.adapter;
import static com.kaluwa.enterprises.babycare.utils.Utils.babyAgeCalculate;
import static com.kaluwa.enterprises.babycare.utils.Utils.calculateAge;
import static com.kaluwa.enterprises.babycare.utils.Utils.convertByteArrayToBitmap;
......@@ -25,6 +26,7 @@ import com.kaluwa.enterprises.babycare.activities.UserProfileActivity;
import com.kaluwa.enterprises.babycare.dto.BabyDto;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.List;
public class BabyDashboardAdapter extends RecyclerView.Adapter<BabyDashboardAdapter.BabyDashboardItemHolder> {
......@@ -49,21 +51,32 @@ public class BabyDashboardAdapter extends RecyclerView.Adapter<BabyDashboardAdap
@Override
public void onBindViewHolder(@NonNull BabyDashboardAdapter.BabyDashboardItemHolder holder, int position) {
BabyDto babyDto = babyList.get(position);
holder.tvBabyName.setText(babyDto.getFirstName() + " " + babyDto.getLastName());
Double age = calculateAge(babyDto.getDob(), "byMonths");
holder.tvBabyAge.setText(age != null ? age + " months" : "Not Available");
holder.tvBabySex.setText(babyDto.getSex());
if (!TextUtils.isEmpty(babyDto.getNotes())) {
holder.tvBabyDDespContent.setText(babyDto.getNotes());
String firstname = babyDto.getFirstName();
String lastname = babyDto.getLastName();
LocalDate dob = babyDto.getDob();
String sex = babyDto.getSex();
String notes = babyDto.getNotes();
Boolean isActive = babyDto.getIsActive();
InputStream imageData = babyDto.getImageData();
if (lastname != null) {
holder.tvBabyName.setText(firstname + " " + lastname);
} else {
holder.tvBabyName.setText(firstname);
}
String age = babyAgeCalculate(dob);
holder.tvBabyAge.setText(age != null ? age : "Not Available");
holder.tvBabySex.setText(sex);
if (!TextUtils.isEmpty(notes)) {
holder.tvBabyDDespContent.setText(notes);
} else {
holder.tvBabyDDespTitle.setText("Status >");
holder.tvBabyDDespContent.setTextColor(babyDto.isActive() ? context.getResources().getColor(R.color.success_green) : context.getResources().getColor(R.color.cancel_red));
holder.tvBabyDDespContent.setText(babyDto.isActive() ? "Active" : "Inactive");
holder.tvBabyDDespContent.setTextColor(isActive ? context.getResources().getColor(R.color.success_green) : context.getResources().getColor(R.color.cancel_red));
holder.tvBabyDDespContent.setText(isActive ? "Active" : "Inactive");
}
if (babyDto.getImageData() != null) {
if (imageData != null) {
try {
InputStream inputStream = babyDto.getImageData();
Bitmap bitmap = convertByteArrayToBitmap(inputStream);
Bitmap bitmap = convertByteArrayToBitmap(imageData);
holder.ivBabyImage.setImageBitmap(bitmap);
} catch (Exception e) {
Log.e(TAG, "Error occurred: " + e.getMessage());
......
......@@ -2,6 +2,9 @@ package com.kaluwa.enterprises.babycare.config;
import static com.kaluwa.enterprises.babycare.config.TokenSaver.getToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.kaluwa.enterprises.babycare.service.AuthApiService;
import com.kaluwa.enterprises.babycare.service.BabyApiService;
import com.kaluwa.enterprises.babycare.service.UserApiService;
......@@ -10,6 +13,7 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
public class ApiConfig {
private static final String BASE_URL = "http://192.168.1.2:8080/api/v1/baby-care/";
......@@ -20,9 +24,14 @@ public class ApiConfig {
private ApiConfig() {
OkHttpClient authHttpClient = new OkHttpClient.Builder().build();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
retrofitAuth = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(JacksonConverterFactory.create(mapper))
.client(authHttpClient)
.build();
......@@ -37,7 +46,7 @@ public class ApiConfig {
.build();
retrofitOther = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(JacksonConverterFactory.create(mapper))
.client(otherHttpClient)
.build();
}
......
......@@ -88,7 +88,7 @@ public class AddBabyDialog extends AppCompatDialogFragment {
int screenHeight = displayMetrics.heightPixels;
// Convert 30dp to pixels
int margin = dpToPx(getContext(), 100);
int margin = dpToPx(getContext(), 65);
// Calculate the available height
int availableHeight = screenHeight - (2 * margin);
......@@ -159,8 +159,7 @@ public class AddBabyDialog extends AppCompatDialogFragment {
baby.setLastName(lastname);
baby.setDob(LocalDate.parse(dob, getDateTimeFormatter()));
baby.setSex(sex);
baby.setPhotoData(null);
baby.setActive(switchStatus.isChecked());
baby.setIsActive(switchStatus.isChecked());
if (!TextUtils.isEmpty(weight)) {
baby.setWeight(Float.parseFloat(weight));
}
......
package com.kaluwa.enterprises.babycare.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.InputStream;
import java.time.LocalDate;
import lombok.AllArgsConstructor;
import lombok.Data;
......@@ -10,15 +13,15 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
public class BabyDto {
private Long babyId;
private String firstName;
private String lastName;
private Object dob;
private LocalDate dob;
private String sex;
private String status;
private boolean isActive;
private byte[] photoData;
private float weight;
private float height;
private Boolean isActive;
private Float weight;
private Float height;
private String bloodType;
private String eyeColor;
private String hairColor;
......@@ -29,10 +32,10 @@ public class BabyDto {
private String docName;
private String docContactNumber;
private String healthInsuranceInfo;
private Object firstSmileDate;
private Object firstToothDate;
private Object firstWordDate;
private Object firstStepDate;
private LocalDate firstSmileDate;
private LocalDate firstToothDate;
private LocalDate firstWordDate;
private LocalDate firstStepDate;
private String favFoods;
private String foodsDislikes;
private String primaryEmergencyContactName;
......@@ -44,8 +47,11 @@ public class BabyDto {
private String notes;
private UserDto user;
private Long userId;
private Long documentId;
@JsonIgnore
private InputStream imageData;
@JsonIgnore
private boolean sys_validated;
}
......@@ -17,5 +17,5 @@ public class UserDto {
private String phone;
private String role;
private String status;
private Object dob;
private LocalDate dob;
}
\ No newline at end of file
package com.kaluwa.enterprises.babycare.service;
import com.kaluwa.enterprises.babycare.dto.BabyDto;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface BabyApiService {
@GET("baby")
Call<List<BabyDto>> getAllBabies();
@POST("baby")
Call<BabyDto> addBaby(@Body BabyDto baby);
}
......@@ -189,6 +189,31 @@ public class Utils {
return age;
}
@SuppressLint("NewApi")
public static String babyAgeCalculate(LocalDate dob) {
if (dob == null) {
Log.e(TAG, "Invalid date of birth");
return null;
}
LocalDate currentDate = LocalDate.now();
Period period = Period.between(dob, currentDate);
int totalMonths = period.getYears() * 12 + period.getMonths();
int totalDays = period.getDays();
if (totalMonths <= 12) {
return totalMonths + " months " + totalDays + " days";
} else {
int years = totalMonths / 12;
int remainingMonths = totalMonths % 12;
return years + " years " + remainingMonths + " months " + totalDays + " days";
}
}
public static Bitmap convertByteArrayToBitmap(InputStream stream) {
try {
return BitmapFactory.decodeStream(stream);
......@@ -207,10 +232,10 @@ public class Utils {
public static DateTimeFormatter getDateTimeFormatter() {
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
.parseCaseInsensitive().parseLenient()
.appendPattern("[d/M/yyyy]")
.appendPattern("[dd MMM yyyy]")
.appendPattern("[dd/MM/yyyy]")
.appendPattern("[dd/M/yyyy]");
// .appendPattern("[d/M/yyyy]")
// .appendPattern("[dd MMM yyyy]")
.appendPattern("[dd/MM/yyyy]");
// .appendPattern("[dd/M/yyyy]");
return builder.toFormatter(Locale.ENGLISH);
}
......
......@@ -5,13 +5,9 @@
<item name="cornerSize">50%</item>
</style>
<!-- Custom AlertDialog theme -->
<style name="CustomAlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="buttonBarStyle">@style/CustomButtonBar</item>
</style>
<!-- Custom button bar style -->
<style name="CustomButtonBar" parent="Widget.AppCompat.ButtonBar.AlertDialog">
<item name="android:background">?attr/colorPrimary</item> <!-- Change this to your desired color -->
<style name="CustomDialogAnimation">
<!-- Define your custom enter animation here -->
<item name="android:windowEnterAnimation">@anim/fade_in</item>
<!-- You can add more animations like scale, translate, etc. -->
</style>
</resources>
\ No newline at end of file
......@@ -5,13 +5,10 @@
<item name="cornerSize">50%</item>
</style>
<!-- Custom AlertDialog theme -->
<style name="CustomAlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="buttonBarStyle">@style/CustomButtonBar</item>
<style name="CustomDialogAnimation">
<!-- Define your custom enter animation here -->
<item name="android:windowEnterAnimation">@anim/fade_in</item>
<!-- You can add more animations like scale, translate, etc. -->
</style>
<!-- Custom button bar style -->
<style name="CustomButtonBar" parent="Widget.AppCompat.ButtonBar.AlertDialog">
<item name="android:background">?attr/colorPrimary</item> <!-- Change this to your desired color -->
</style>
</resources>
\ No newline at end of file
......@@ -14,6 +14,8 @@ retrofit2 = "2.11.0"
jacksonDatabind = "2.17.1"
materialVersion = "1.13.0-alpha02"
swiperefreshlayout = "1.2.0-alpha01"
converterJackson = "2.11.0"
jacksonDatatypeJsr310 = "2.17.1"
[libraries]
junit = { group = "junit", name = "junit", version.ref = "junit" }
......@@ -32,6 +34,8 @@ convertor-gson = { group = "com.squareup.retrofit2", name = "converter-gson", ve
jackson-databind = { group = "com.fasterxml.jackson.core", name = "jackson-databind", version.ref = "jacksonDatabind" }
ucrop = { group = "com.github.yalantis", name = "ucrop", version = "2.2.9" }
swiperefreshlayout = { group = "androidx.swiperefreshlayout", name = "swiperefreshlayout", version.ref = "swiperefreshlayout" }
converter-jackson = { group = "com.squareup.retrofit2", name = "converter-jackson", version.ref = "converterJackson" }
jackson-datatype-jsr310 = { group = "com.fasterxml.jackson.datatype", name = "jackson-datatype-jsr310", version.ref = "jacksonDatatypeJsr310" }
[plugins]
androidApplication = { id = "com.android.application", version.ref = "agp" }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment