Reading Selected Date without DatePickeView in android studio - java

I am Parvanshu Sharma and I am a beginner to programming, I am making an application in which
I have done that on button click a date Picker dialog will appear and the button text will be set to the selected by the user, Currently there are 3 buttons for this and I even have a realtime database for uploading this date on Firebase, but now I am having problems in getting the every unique date and uploading it, I am not able to get the selected date.
And as my every stackoverflow question has-
MainActivity.java (Its too big so I haven't shown imports)
public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;
Integer OrderQuantity = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString()+"/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
if (Quantity1.getSelectedItem().toString() != "0") {
//I want some solution HERE
}
}
});
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}```
and here goes my activity_main.xml
```<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/NameTextView"
android:layout_width="93dp"
android:layout_height="wrap_content"
android:layout_marginStart="20sp"
android:layout_marginLeft="20sp"
android:layout_marginTop="10sp"
android:text="Name"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonName"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:layout_marginStart="20sp"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Name"
android:inputType="textPersonName" />
<TextView
android:id="#+id/PhoneTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="Mobile Number"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonPhone"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Mobile number"
android:inputType="phone" />
<TextView
android:id="#+id/AddressTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="Address"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonAddress"
android:layout_width="328dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Delivery Address"
android:inputType="textPostalAddress" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:text=" Order Details"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold" />
<TableLayout
android:id="#+id/MainTable"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:stretchColumns="0,1,2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="0"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text=" Date "
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_column="1"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text="Item"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_column="2"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text="Quantity"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem1"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center"
android:text="Select Item" />
<Spinner
android:id="#+id/SelectQuantity1"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem2"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center"
android:text="Select Item" />
<Spinner
android:id="#+id/SelectQuantity2"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem3"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center" />
<Spinner
android:id="#+id/SelectQuantity3"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
</TableLayout>
<Button
android:id="#+id/DoneButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Done" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
and I have one more class for creating DatePickerDialog,
the source from where I learnt and implemented that how to make DatePickerDialog is Here
which goes here- (DatePickerFragment.java)
public class DatePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
}
}

Tried using an interface. You will have all 3 dates in your main activity, now you can do whatever with them
public class DatePickerFragment extends DialogFragment {
private static applyDate mInterface;
private static int buttonNumberHere;
public interface applyDate {
void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber);
}
public static DatePickerFragment newInstance(int buttonNumber, applyDate context)
{
DatePickerFragment fragment = new DatePickerFragment();
mInterface = ((applyDate) context);
buttonNumberHere = buttonNumber;
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getContext(), datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
mInterface.setDate(selectedYear, selectedMonth, selectedDay, buttonNumberHere);
}
};
In MainActivity
public class MainActivity extends AppCompatActivity implements applyDate, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;// Idk what is this
Integer OrderQuantity = 3;
String itemOneDate;
String itemTwoDate;
String itemThreeDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(1, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(2, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(3, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Idk how to set date but now you have all three dates
DatabaseReference dateOne = database.getReference(itemOneDate + "/DateOne");
dateOne.setValue(itemOneDate);
DatabaseReference dateTwo = database.getReference(itemOneDate + "/DateTwo");
dateTwo.setValue(itemTwoDate);
DatabaseReference dateThree = database.getReference(itemThreeDate + "/DateThree");
dateThree.setValue(itemThreeDate);
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString()+"/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
if (Quantity1.getSelectedItem().toString() != "0") {
//I want some solution HERE
}
}
});
}
#Override
public void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber){
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, selectedYear);
c.set(Calendar.MONTH, selectedMonth);
c.set(Calendar.DAY_OF_MONTH, selectedDay);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
if (buttonNumber == 1){
itemOneDate = CurrentDateString;
}
else if (buttonNumber == 2){
itemTwoDate = CurrentDateString;
}
else if (buttonNumber == 3){
itemThreeDate = CurrentDateString;
}
}
}

Related

how to save selected radio button and spinner data by value using rest API?

I am using rest API and facing some issue when embedding an API. How do I save spinner and radio button data by value and using retrofit2.This API is for calculating BMR and BMR Please help!
Here is BMIquestions.java
public class BMIquestions extends AppCompatActivity implements View.OnClickListener{
Button nextbtn;
ImageButton date;
DatePickerDialog datePickerDialog;
EditText age, height, weight;
// Let's assume 1 = male and 0 = female
// Declare a RadioGroup object reference
RadioGroup rgGender;
// Declare RadioButton object references for Male and Female
RadioButton rbMale, rbFemale;
private String gender=null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentHeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if(rbMale.isSelected()){
rbMale.setTag("1");
rbMale.getTag().toString();
if(rbFemale.isSelected()){
rbFemale.setTag("0");
rbFemale.getTag().toString();
}
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
String[] level = new String[]{"Not Very Activ", "Lightly Active", "Active", "Very Active"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this,
R.layout.drop_down_items,
level
);
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.type);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(BMIquestions.this, autoCompleteTextView.getText().toString(), Toast.LENGTH_SHORT).show();
if(autoCompleteTextView.getText().toString().equals("Lightly Active")){
autoCompleteTextView.setTag("1.55");
}
}
});
date.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View view) {
// Calender class 's instance and get current,date ,month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);//current year
int mMonth = c.get(Calendar.MONTH);//current month
int mDay = c.get(Calendar.DAY_OF_MONTH);//current date
final int noofyears = (int) (mYear - c.get(Calendar.YEAR)); //calculate age
//date picker dialog
datePickerDialog = new DatePickerDialog(BMIquestions.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
age.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
DatePicker dp = datePickerDialog.getDatePicker();
WindowManager.LayoutParams params = datePickerDialog.getWindow().getAttributes();
//params.gravity = Gravity.CENTER_HORIZONTAL;
params.width = 50; // dialogWidth;
params.height = 100; // dialogHeight;
datePickerDialog.show();
}
});
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
case R.id.male:
gender="0";
break;
case R.id.female:
rbFemale.setTag("0");
gender=rbFemale.getTag().toString();
break;
}
}
public void openHomePage() {
String userHeight = height.getText().toString();
String userWeight = weight.getText().toString();
String userAge = age.getText().toString();
HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("height", userHeight);
meMap.put("age", userAge);
meMap.put("gender", gender);
//meMap.put("activity_level",act);
meMap.put("current_weight",userWeight);
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(meMap);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(BMIquestions.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(BMIquestions.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Intent i=new Intent(BMIquestions.this,HomePage.class);
startActivity(i);
}
}
Here is activity_bmiquestions.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.questions.BMIquestions">
<TextView
android:id="#+id/targetWeight"
android:layout_width="386dp"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_regular"
android:gravity="center"
android:paddingStart="12dp"
android:paddingTop="60dp"
android:text="Tell us About Youself"
android:textColor="#color/black"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="122dp"
android:fontFamily="#font/roboto_regular"
android:text="Gender:"
android:textColor="#color/black"
android:textSize="14dp" />
<RadioGroup
android:id="#+id/gender_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="142dp"
android:paddingStart="24dp"
android:orientation="horizontal"
>
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
/>
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
</RadioGroup>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/age"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="DD/MM/YYYY" />
<ImageButton
android:id="#+id/calender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/ic_baseline_calendar_today_24" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Height in centimeter"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentHeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your height"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="cm"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="When were you born ?"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Weight in kilogram"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentWeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your weight" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:textColor="#color/black" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="440dp"
android:layout_marginStart="10dp">
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="330dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="80dp"
android:hint="Activity Level" >
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/type"
android:inputType="none">
</AutoCompleteTextView>
</com.google.android.material.textfield.TextInputLayout>
</RelativeLayout>
<android.widget.Button
android:id="#+id/Next"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="21dp"
android:background="#color/dark_grey"
android:text="Next"
android:textColor="#color/white"
android:textSize="15sp"
android:textStyle="bold"></android.widget.Button>
</RelativeLayout>
Here is Api Interface
public interface Api{
//GetCalculations
#POST("calculation")
Call<QuestionResponse> calculation(
#Body HashMap<String, String> body
);
}
Here is RetrofitClient.java
package com.example.signup.ui.api;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
//singeleton class defining retrofit client
//define base url
//initialize retrofit object
private static final String BASE_URL = "http://xxx.xxx.xxx.xxx:xxxx/api/";
private static RetrofitClient retrofitClient;
private static Retrofit retrofit;
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
private RetrofitClient() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//return instances when above method call
public static synchronized RetrofitClient getInstance() {
if (retrofitClient==null) {
retrofitClient = new RetrofitClient();
}
return retrofitClient;
}
public Api getApi() {
return retrofit.create(Api.class);
}
}
How can I fix this problem?

inputData to send data to mainActivity error using Realm Database instant crash

I have a problem that when I press the Fab button the app instant close and I don't know how to fix it, my goal was when pressing the fab button and inserting the data it will send the data to the MainActivity.xml and make a list of item
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Income"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expenses"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Balance"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
<ListView
android:id="#+id/listView"
app:layout_anchor="#id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp">
</ListView>
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:fabCradleMargin="10dp"
app:fabCradleVerticalOffset="10dp"
app:fabCradleRoundedCornerRadius="20dp"
android:layout_gravity="bottom">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottomNavigationView"
app:menu="#menu/bottom_nav_menu"
android:layout_marginEnd="10dp"/>
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fab"
android:src="#drawable/add_button"
app:layout_anchor="#id/bottomAppBar"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
activity_input_data.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".InputDataActivity">
<LinearLayout
android:layout_marginTop="200dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="200dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textAlignment="center"
android:textSize="50dp"
android:textStyle="bold"
android:text="Input Data"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtTitle"
android:hint="Title..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtAmount"
android:hint="Amount..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtDate"
android:hint="Date..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/addButton"
android:text="Add"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20dp">
<ImageView
android:src="#drawable/profile_button"
android:layout_width="50dp"
android:layout_height="50dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:layout_gravity="end"
android:textSize="16dp"
android:textStyle="bold"
android:text="Main Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/amount"
android:layout_gravity="end"
android:textSize="14dp"
android:textStyle="bold"
android:text="Rp. 20.000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/date"
android:layout_gravity="end"
android:textSize="12dp"
android:textStyle="bold"
android:text="23-06-2021"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/spinner"
android:layout_gravity="end"
android:textSize="14dp"
android:textStyle="bold"
android:text="Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
MyHelper myHelper;
BottomNavigationView bottomNavigationView;
FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
floatingActionButton = findViewById(R.id.fab);
//ListView Adapter
ListViewAdapter adapter = new ListViewAdapter(this, myHelper.justRefresh());
listView.setAdapter(adapter);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, InputDataActivity.class);
startActivity(intent);
}
});
//Bottom Nav
bottomNavigationView.setBackground(null);
bottomNavigationView.getMenu().getItem(2).setEnabled(false);
}
}
InputDataActivity.java
public class InputDataActivity extends AppCompatActivity {
EditText txtTitle, txtAmount,txtDate;
Button button;
Realm realm;
ListView listView;
MyHelper myHelper;
RealmChangeListener realmChangeListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_data);
realm = Realm.getDefaultInstance();
txtTitle = findViewById(R.id.txtTitle);
txtAmount = findViewById(R.id.txtAmount);
txtDate = findViewById(R.id.txtDate);
button = findViewById(R.id.addButton);
listView = findViewById(R.id.listView);
//MyHelper
myHelper = new MyHelper(realm);
myHelper.selectFromDB();
//ListView Adapter
ListViewAdapter adapter = new ListViewAdapter(this, myHelper.justRefresh());
listView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
Refresh();
}
private void saveData(){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Number maxId = realm.where(User.class).max("title_id");
int newKey = (maxId == null) ? 1 : maxId.intValue()+1;
User user = realm.createObject(User.class, newKey);
user.setTitle_name(txtTitle.getText().toString());
user.setAmount(txtAmount.getText().toString());
user.setDate(txtDate.getText().toString());
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(InputDataActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Toast.makeText(InputDataActivity.this, "Fail", Toast.LENGTH_SHORT).show();
}
});
}
private void Refresh(){
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange(Object o) {
ListViewAdapter adapter = new ListViewAdapter(InputDataActivity.this, myHelper.justRefresh());
listView.setAdapter(adapter);
}
};
realm.addChangeListener(realmChangeListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
MyHelper.java
public class MyHelper {
Realm realm;
RealmResults<User> users;
public MyHelper(Realm realm) {
this.realm = realm;
}
public void selectFromDB(){
users = realm.where(User.class).findAll();
}
public ArrayList<User> justRefresh(){
ArrayList<User> listItem = new ArrayList<>();
for(User user: users){
listItem.add(user);
}
return listItem;
}
}
User.java
public class User extends RealmObject {
#PrimaryKey
private int title_id;
private String title_name;
private String amount;
private String date;
private String spinner;
public int getTitle_id() {
return title_id;
}
public void setTitle_id(int title_id) {
this.title_id = title_id;
}
public String getTitle_name() {
return title_name;
}
public void setTitle_name(String title_name) {
this.title_name = title_name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSpinner() {
return spinner;
}
public void setSpinner(String spinner) {
this.spinner = spinner;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
Context context;
ArrayList<User> users;
public ListViewAdapter(Context context, ArrayList<User> users) {
this.context = context;
this.users = users;
}
#Override
public int getCount() {
return users.size();
}
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater =(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view =inflater.inflate(R.layout.list_item, parent,false);
TextView title,amount,date,spinner;
title =view.findViewById(R.id.title);
amount = view.findViewById(R.id.amount);
date = view.findViewById(R.id.date);
spinner = view.findViewById(R.id.spinner);
User u = (User)this.getItem(position);
title.setText(u.getTitle_name());
amount.setText(u.getAmount());
date.setText(u.getDate());
spinner.setText(u.getSpinner());
int numPosition = u.getTitle_id();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// for update
}
});
return view;
}
}
if someone can help, Thank you because I'm stuck here. my goal is to make Money Management

Recyclerview is Scrolling when media Player is playing. How can i fix it?

I'm developing a ChatApp with the function of Audio Messages. The Recording and playing of this Audio Messages are working very well, but if i click on Play Button the Recyclerview is scrolling up. Anyone have an idea?
Sorry for my bad english, i'm from Germany ;)
AdapterChat.Java
private static final int MSG_TYPE_LEFT = 0;
private static final int MSG_TYPE_RIGHT = 1;
Context context;
List<ModelChat> chatList;
String imageUrl;
FirebaseUser fUser;
public AdapterChat(Context context, List<ModelChat> chatList, String imageUrl) {
this.context = context;
this.chatList = chatList;
this.imageUrl = imageUrl;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
//inflate layouts: row_chat_left.xml for receiver, row_chat_right.xml for sender
if (i == MSG_TYPE_RIGHT) {
View view = LayoutInflater.from(context).inflate(R.layout.row_chat_right, viewGroup, false);
return new MyHolder(view);
}
else {
View view = LayoutInflater.from(context).inflate(R.layout.row_chat_left, viewGroup, false);
return new MyHolder(view);
}
}
public void add(ModelChat object) {
chatList.add(object);
add(object);
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onBindViewHolder(#NonNull final MyHolder myHolder, final int i) {
final String message = chatList.get(i).getMessage();
String timeStamp = chatList.get(i).getTimestamp();
String type = chatList.get(i).getType();
if (type.equals("text") || message.equals(R.string.message_was_deleted)) {
//text message
myHolder.messageTv.setVisibility(View.VISIBLE);
myHolder.messageIv.setVisibility(View.GONE);
myHolder.playAudioBtn.setVisibility(View.GONE);
myHolder.messageVoiceSb.setVisibility(View.GONE);
myHolder.sbCurrentTime.setVisibility(View.GONE);
myHolder.sbTotalDuration.setVisibility(View.GONE);
myHolder.messageTv.setText(message);
}
else if (type.equals("audio")) {
//audio message
myHolder.messageTv.setVisibility(View.GONE);
myHolder.messageIv.setVisibility(View.GONE);
myHolder.playAudioBtn.setVisibility(View.VISIBLE);
myHolder.messageVoiceSb.setVisibility(View.VISIBLE);
myHolder.sbCurrentTime.setVisibility(View.VISIBLE);
myHolder.sbTotalDuration.setVisibility(View.VISIBLE);
myHolder.voiceMessageUrl = message;
myHolder.getAdapterPosition();
myHolder.playAudioBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (myHolder.mediaPlayer.isPlaying()) {
myHolder.handler.removeCallbacks(myHolder.updater);
myHolder.mediaPlayer.pause();
myHolder.playAudioBtn.setImageResource(R.drawable.ic_play_btn);
}
else {
myHolder.mediaPlayer.start();
myHolder.playAudioBtn.setImageResource(R.drawable.ic_pause_btn);
myHolder.updateSeekbar();
}
}
});
myHolder.prepareMediaPlayer();
myHolder.messageVoiceSb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
SeekBar seekBar = (SeekBar) view;
int playPosition = (myHolder.mediaPlayer.getDuration() / 100) * seekBar.getProgress();
myHolder.mediaPlayer.seekTo(playPosition);
myHolder.sbCurrentTime.setText(myHolder.milliSecondsToTimer(myHolder.mediaPlayer.getCurrentPosition()));
return false;
}
});
myHolder.mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
myHolder.messageVoiceSb.setSecondaryProgress(i);
}
});
myHolder.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
myHolder.messageVoiceSb.setProgress(0);
myHolder.playAudioBtn.setImageResource(R.drawable.ic_play_btn);
myHolder.mediaPlayer.reset();
myHolder.prepareMediaPlayer();
}
});
}
else {
//image message
myHolder.messageIv.setVisibility(View.VISIBLE);
myHolder.messageTv.setVisibility(View.GONE);
myHolder.playAudioBtn.setVisibility(View.GONE);
myHolder.messageVoiceSb.setVisibility(View.GONE);
myHolder.sbCurrentTime.setVisibility(View.GONE);
myHolder.sbTotalDuration.setVisibility(View.GONE);
Picasso.get().load(message).placeholder(R.drawable.ic_image_black).into(myHolder.messageIv);
}
//set data
myHolder.messageTv.setText(message);
myHolder.timeTv.setText(timeStamp);
try {
Picasso.get().load(imageUrl).into(myHolder.profileIv);
}
catch (Exception e) {
}
myHolder.messageLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//show delete message confirm dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.delete);
builder.setMessage("Are you sure to delete this message?");
//delete button
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteMessage(i);
}
});
//cancel delete button
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//dismiss dialog
dialog.dismiss();
}
});
//create and show dialog
builder.create().show();
return false;
}
});
//set seen/delivered status of message
if (i==chatList.size()-1) {
if (chatList.get(i).isSeen()) {
myHolder.isSeenTv.setText("Seen");
}
else {
myHolder.isSeenTv.setText("Delivered");
}
}
else {
myHolder.isSeenTv.setVisibility(View.GONE);
}
}
private void deleteMessage(int position) {
final String myUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
/*Logic:
* Get timeStamp of clicked message
* Compare the timeStamp of the clicked message with all messages in CHats
* Where both values matches, delete that message
* This will allow sender to delete his and receiver's message*/
String msgTimeStamp = chatList.get(position).getTimestamp();
final String type = chatList.get(position).getType();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
Query query = dbRef.orderByChild("timestamp").equalTo(msgTimeStamp);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
/*if you want to allow sender to delete only his message then
* compare sender value with current user's uid
* if they match means its the message of sender that is trying to delete*/
if (ds.child("sender").getValue().equals(myUID)) {
if (type.equals("audio")) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("type", "text");
ds.getRef().updateChildren(hashMap);
} else if (type.equals("image")) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("type", "text");
ds.getRef().updateChildren(hashMap);
}
/*We can do one of two things here
* 1) Remove the message from chats
* 2) Set the value of message "This messages was deleted..." */
//1) Remove the message from Chats
//ds.getRef().removeValue();
//2) Set the value of message "This message was deleted..."
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("message", "This message was deleted...");
ds.getRef().updateChildren(hashMap);
Toast.makeText(context, "message deleted...", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "You can delete only your messages...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return chatList.size();
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getItemViewType(int position) {
//get currently signed in user
fUser = FirebaseAuth.getInstance().getCurrentUser();
if (chatList.get(position).getSender().equals(fUser.getUid())) {
return MSG_TYPE_RIGHT;
}
else {
return MSG_TYPE_LEFT;
}
}
//view holder class
class MyHolder extends RecyclerView.ViewHolder {
//views
ImageView profileIv, messageIv;
ImageButton playAudioBtn;
SeekBar messageVoiceSb;
TextView messageTv, timeTv, isSeenTv, sbCurrentTime, sbTotalDuration;
LinearLayout messageLayout; //for click listener to show delete option
MediaPlayer mediaPlayer;
Handler handler = new Handler();
String voiceMessageUrl = null;
#SuppressLint("ClickableViewAccessibility")
public MyHolder(#NonNull View itemView) {
super(itemView);
//init views
profileIv = itemView.findViewById(R.id.profileIv);
messageIv = itemView.findViewById(R.id.messageIV);
messageTv = itemView.findViewById(R.id.messageTv);
messageVoiceSb = itemView.findViewById(R.id.messageVoiceSb);
playAudioBtn = itemView.findViewById(R.id.playAudioBtn);
sbCurrentTime = itemView.findViewById(R.id.sbCurrentTime);
sbTotalDuration = itemView.findViewById(R.id.sbTotalDuration);
timeTv = itemView.findViewById(R.id.timeTv);
isSeenTv = itemView.findViewById(R.id.isSeenTv);
messageLayout = itemView.findViewById(R.id.messageLayout);
mediaPlayer = new MediaPlayer();
messageVoiceSb.setMax(100);
}
private void prepareMediaPlayer() {
try {
mediaPlayer.setDataSource(voiceMessageUrl); //url of audio file to play
mediaPlayer.prepare();
sbTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
} catch (Exception e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekbar();
long currentDuration = mediaPlayer.getCurrentPosition();
sbCurrentTime.setText(milliSecondsToTimer(currentDuration));
}
};
private void updateSeekbar() {
if (mediaPlayer.isPlaying()) {
messageVoiceSb.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration()) * 100));
handler.postDelayed(updater, 1000);
}
}
private String milliSecondsToTimer(long milliSeconds) {
String timerString = "";
String secondsString;
int hours = (int) (milliSeconds / (1000 * 60 * 60));
int minutes = (int) (milliSeconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliSeconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
if (hours > 0) {
timerString = hours + ":";
}
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
timerString = timerString + minutes + ":" + secondsString;
return timerString;
}
}
chatActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/chatBackground"
tools:context=".ChatActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#color/colorPrimaryDark"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profileIv"
android:layout_width="35dp"
android:layout_height="35dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_default"
app:civ_circle_background_color="#color/colorPrimaryDark"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:layout_marginStart="20dp">
<!-- Receiver Name-->
<TextView
android:id="#+id/nameTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="His Name"
android:textColor="#color/colorWhite"
android:textSize="18sp"
android:textStyle="bold" />
<!-- Receiver Status i.e online or offline-->
<TextView
android:id="#+id/userStatusTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="online"
android:textColor="#color/colorWhite"
android:textSize="12sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="#+id/blockIv"
android:layout_gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:src="#drawable/ic_unblocked_green"
android:visibility="invisible"/>
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
<!-- RecyclerView-->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/chat_recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar"
android:layout_above="#id/chatLayout" />
<!-- send message edit text and button in layout-->
<LinearLayout
android:id="#+id/chatLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:background="#color/textInputBackground"
android:orientation="horizontal">
<!-- ImageButton: to send Image-->
<ImageButton
android:id="#+id/attachBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#null"
android:src="#drawable/ic_attach_black" />
<!-- EditText: input message-->
<EditText
android:id="#+id/messageEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#null"
android:inputType="textCapSentences|textMultiLine"
android:padding="15dp"
android:hint="Start typing" />
<Chronometer
android:id="#+id/record_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:textSize="14sp"
android:textColor="#color/colorPrimary" />
<!-- Button: voice message-->
<ImageButton
android:id="#+id/recordBtn"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#null"
android:src="#drawable/ic_record_btn_stopped" />
<!-- Button: send message-->
<ImageButton
android:id="#+id/sendBtn"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#null"
android:src="#drawable/ic_send" />
</LinearLayout>
row_chat_right.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="#+id/messageLayout"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="end">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/profileIv"
app:civ_border_color="#null"
android:visibility="gone"
android:src="#drawable/ic_default_img" />
<TextView
android:id="#+id/messageTv"
android:layout_weight="1"
android:textSize="16sp"
android:textColor="#color/textColor"
android:background="#drawable/bg_sender"
android:padding="15dp"
android:text="His Message"
android:visibility="gone"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/messageIV"
android:layout_width="200dp"
android:layout_height="200dp"
android:adjustViewBounds="true"
android:padding="15dp"
android:src="#drawable/ic_image_black"
android:scaleType="fitCenter"
android:background="#drawable/bg_sender" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/bg_sender"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/playAudioBtn"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="20dp"
android:background="#null"
android:src="#drawable/ic_play_btn" />
<SeekBar
android:id="#+id/messageVoiceSb"
android:visibility="gone"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/playAudioBtn"
android:padding="10dp"
android:layout_marginTop="10dp"
android:max="100"
android:progress="0" />
<TextView
android:id="#+id/sbCurrentTime"
android:visibility="gone"
android:text="0:00"
android:textStyle="bold"
android:textSize="12sp"
android:layout_marginStart="2dp"
android:layout_below="#id/messageVoiceSb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sbTotalDuration"
android:visibility="gone"
android:textStyle="bold"
android:text="0:10"
android:textSize="12sp"
android:layout_below="#id/messageVoiceSb"
android:layout_toEndOf="#id/messageVoiceSb"
android:layout_marginEnd="12dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
<TextView
android:id="#+id/timeTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:textAlignment="textEnd"
android:text="07/08/2020 23:00PM"
android:textColor="#color/textColor"
android:textSize="12sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/isSeenTv"
android:gravity="end"
android:textAlignment="textEnd"
android:text="delivered" />
Here is the Fix!!
<TextView
android:layout_width="match_parent" <-- This is what I changed
android:layout_height="wrap_content"/>
<SeekBar
android:layout_width="match_parent" <-- Check this as well
android:layout_height="wrap_content"/>

send sms automatically using firebase database given phone number and date

Firebase database screenshot
I'm a beginner at android and firebase and am developing a driving school app.
I am to successfully add customer details to a firebase database ('name', 'phone', 'fromdate' and 'todate'). I want to send an sms alert to the customer e.g. ("your licence is expiry soon.") using 'phone' and 'date' from the firebase database. The sms should be sent 7 days before the expiry date (I mean 'todate' in the firebase database). Here I've attached my firebase database screenshot. Please give me an example of how to do this.
Update customer details
public class Updatecustomer extends AppCompatActivity {
private EditText edtname, edtpho;
private Button btnsubmit;
private EditText datepickerto, datepickerfr;
private Calendar mcurrentDate, mlateDate;
int day, month, year;
private DatabaseReference childref;
private DatabaseReference listref;
private DatabaseReference noderef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_updatecustomer);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Update your Customer Details");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
datepickerto = (EditText)findViewById(R.id.datepickerto);
datepickerfr = (EditText)findViewById(R.id.datepickerfr);
edtname = (EditText)findViewById(R.id.edtname);
edtpho = (EditText)findViewById(R.id.edtpho);
btnsubmit = (Button)findViewById(R.id.btnsubmit);
mcurrentDate = Calendar.getInstance();
day = mcurrentDate.get(Calendar.DAY_OF_MONTH);
month = mcurrentDate.get(Calendar.MONTH);
year = mcurrentDate.get(Calendar.YEAR);
day = day+1;
datepickerto.setText(day+"-"+month+"-"+year);
datepickerto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new
DatePickerDialog(Updateproduction.this, new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int
monthOfYear, int dayOfMonth) {
monthOfYear =monthOfYear+1;
datepickerto.setText(dayOfMonth+"-"+monthOfYear+"-
"+year);
}
}, year, month, day);
datePickerDialog.show();
}
});
mlateDate = Calendar.getInstance();
day = mlateDate.get(Calendar.DAY_OF_MONTH);
month = mlateDate.get(Calendar.MONTH);
year = mlateDate.get(Calendar.YEAR);
month = month+1;
datepickerfr.setText(day+"-"+month+"-"+year);
datepickerfr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new
DatePickerDialog(Updatecustomer.this, new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int
monthOfYear, int dayOfMonth) {
monthOfYear =monthOfYear+1;
datepickerfr.setText(dayOfMonth+"-"+monthOfYear+"-
"+year);
}
}, year, month, day);
datePickerDialog.show();
}
});
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference table_user = database.getReference();
childref = table_user.child("Rajadriving");
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDiaglog = new
ProgressDialog(Updateproduction.this);
mDiaglog.setMessage("Please Waiting...");
mDiaglog.show();
table_user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//if(dataSnapshot.child(spinnershift.getSelectedItem()
.toString()).exists())
// {
// mDiaglog.dismiss();
// Toast.makeText(Updatecustomer.this, "Data
already Stored", Toast.LENGTH_SHORT).show();
// }
// else
{
mDiaglog.dismiss();
Datastore user = new
Datastore(datepickerfr.getText().toString(),datepickerto.getText()
.toString(),
edtpho.getText().toString().trim(),
edtname.getText().toString().trim());
listref =
childref.child(datepickerfr.getText().toString());
noderef =
listref.child(edtname.getText().toString());
noderef.setValue(user);
//Intent addintent = new
Intent(MainActivity.this,Paid.class);
// startActivity(addintent);
Toast.makeText(Updatecustomer.this, "Data saved
successfully !", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
activity_update_customer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.udayaj.rajadriving.Updatecustomer">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Raja Driving School"
android:textStyle="bold"
android:textColor="#f05"
android:textSize="25dp"
android:fontFamily="sans-serif"
android:gravity="center"
android:id="#+id/textView" />
<EditText
android:id="#+id/edtname"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/datepickerfr"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:hint="Enter Customer Name"
android:inputType="textPersonName"
android:textSize="16dp" />
<EditText
android:id="#+id/edtpho"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/edtname"
android:layout_below="#+id/edtname"
android:layout_marginTop="19dp"
android:hint="Enter Phone No."
android:inputType="number"
android:minLines="10"/>
<Button
android:id="#+id/btnsubmit"
android:layout_width="150dp"
android:layout_height="55dp"
android:layout_below="#+id/edtpho"
android:layout_centerHorizontal="true"
android:layout_marginTop="96dp"
android:background="#drawable/sty_submit"
android:text="Submit"
android:textColor="#android:color/white" />
<EditText
android:id="#+id/datepickerfr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView5"
android:layout_marginEnd="19dp"
android:layout_toStartOf="#+id/datepickerto"
android:hint="Enter From Date"
android:inputType="date" />
<EditText
android:id="#+id/datepickerto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/textView5"
android:layout_marginEnd="42dp"
android:hint="Enter Expire Date"
android:inputType="date" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:text="Date use this format eg:6-6-2018."
android:id="#+id/textView5" />
</RelativeLayout>

Integer value not being saved to Preference XML not displaying the value

I'm currently developing a calorie app for my class project. I am having issues saving the value from the profile function calculateTDEE to the shared preference xml. The page i'm currently working on gets information from the user and depending what the user selects determines their calories. That value is then saved in shared preference where it is displayed in the main activity.
I'm still learning android studio and this is my first app I'm developing.
Thank you in advance.
profile java file
`public class Profile extends Fragment implements View.OnClickListener {
//adaptors spinners
ArrayAdapter<String> HeightFeetAdapter;
ArrayAdapter<String> WeightLBSAdapter;
//references UI elements
Button SaveButton;
Spinner weightSpinner;
Spinner heightSpinner;
Spinner goal;
Spinner gender;
Spinner activityLevel;
EditText age;
private Animation anim;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_profile, container,
false);
String username =
getActivity().getIntent().getStringExtra("Username");
TextView userMain = (TextView) myView.findViewById(R.id.User);
userMain.setText(username);
age =(EditText)myView.findViewById(R.id.editText3);
age.setInputType(InputType.TYPE_CLASS_NUMBER);
heightSpinner = (Spinner) myView.findViewById(R.id.HeightSpin);
weightSpinner = (Spinner) myView.findViewById(R.id.WeightSpin);
activityLevel = (Spinner) myView.findViewById(R.id.activity_level);
ArrayAdapter<CharSequence> adapter_activity =
ArrayAdapter.createFromResource(getActivity(),
R.array.activity_level, android.R.layout.simple_spinner_item);
adapter_activity.setDropDownViewResource
(android.R.layout.simple_spinner_dropdow
n_item);
activityLevel.setAdapter(adapter_activity);
goal = (Spinner) myView.findViewById(R.id.goal);
ArrayAdapter<CharSequence> adapter_goal =
ArrayAdapter.createFromResource(getActivity(),
R.array.goal, android.R.layout.simple_spinner_item);
adapter_goal.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
goal.setAdapter(adapter_goal);
gender = (Spinner) myView.findViewById(R.id.gender);
ArrayAdapter<CharSequence> adapter_gender =
ArrayAdapter.createFromResource(getActivity(),
R.array.gender, android.R.layout.simple_spinner_item);
adapter_gender.setDropDownViewResource
(android.R.layout.simple_list_item_activated_1);
gender.setAdapter(adapter_gender);
SaveButton = (Button) myView.findViewById(R.id.savebutton);
SaveButton.setOnClickListener(this);
initializeSpinnerAdapters();
loadLBVal();
loadFTVal();
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
heightSpinner.startAnimation(anim);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
weightSpinner.startAnimation(anim);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
SaveButton.startAnimation(anim);
SharedPreferences userInfo =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
return myView;
}
public void loadLBVal() {
weightSpinner.setAdapter(WeightLBSAdapter);
// set the default lib value
weightSpinner.setSelection(WeightLBSAdapter.getPosition("170"));
}
// load the feets value range to the height spinner
public void loadFTVal() {
heightSpinner.setAdapter(HeightFeetAdapter);
// set the default value to feets
heightSpinner.setSelection(HeightFeetAdapter.getPosition("5\"05'"));
}
public void initializeSpinnerAdapters() {
String[] weightLibs = new String[300];
// loading spinner values for weight
int k = 299;
for (int i = 1; i <= 300; i++) {
weightLibs[k--] = String.format("%3d", i);
}
// initialize the weightLibsAdapter with the weightLibs values
WeightLBSAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, weightLibs);
WeightLBSAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
String[] heightFeets = new String[60];
// loading values 3"0' to 7"11' to the height in feet/inch
k = 59;
for (int i = 3; i < 8; i++) {
for (int j = 0; j < 12; j++) {
heightFeets[k--] = i + "\"" + String.format("%02d", j) + "'";
}
}
// initialize the heightFeetAdapter with the heightFeets values
HeightFeetAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, heightFeets);
HeightFeetAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.savebutton:
int activityLevel, goal, gender, age;
// Get preferences
float height = getSelectedHeight();
float weight = getSelectedWeight();
activityLevel =
((Spinner)getActivity().findViewById
(R.id.activity_level)).getSelectedItemPosition();
goal = ((Spinner)getActivity().
findViewById(R.id.goal)).getSelectedItemPosition();
gender= ((Spinner)getActivity().
findViewById(R.id.gender)).getSelectedItemPosition();
age = Integer.parseInt(((EditText).
getActivity().findViewById(R.id.editText3)));
int tdee = calculateTDEE(height,weight,activityLevel,age,gender,
goal);
// Save preferences in XML
SharedPreferences userInfo = getSharedPreferences("userInfo",
0);
SharedPreferences.Editor editor = userInfo.edit();
editor.putInt("tdee", tdee);
editor.commit();
break;
}
}
public float getSelectedWeight() {
String selectedWeightValue = (String)weightSpinner.getSelectedItem();
return (float) (Float.parseFloat(selectedWeightValue) * 0.45359237);
}
public float getSelectedHeight() {
String selectedHeightValue = (String)heightSpinner.getSelectedItem();
// the position is feets and inches, so convert to meters and return
String feets = selectedHeightValue.substring(0, 1);
String inches = selectedHeightValue.substring(2, 4);
return (float) (Float.parseFloat(feets) * 0.3048) +
(float) (Float.parseFloat(inches) * 0.0254);
}
public int calculateTDEE(float height, float weight, int activityLevel,
int
age, int gender, int goal) {
double bmr = (10 * weight) + (6.25 * height) - (5 * age) + 5;
if(gender == 1) {
bmr = (10* weight) + (6.25 * height) - (5*age) - 161;
}
double activity = 1.25;
switch(activityLevel) {
case 1:
activity = 1.375;
break;
case 2:
activity = 1.55;
break;
case 3:
activity = 1.725;
break;
case 4:
activity = 1.9;
break;
}
double tdee = bmr * activity;
switch(goal) {
case 0:
tdee -=500;
break;
case 2:
tdee +=500;
break;
}
tdee += .5;
return (int) tdee;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
`
fragment_profile xml
`
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/imgbackground2"
android:weightSum="1">
<TextView
android:layout_width="180dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptyString"
android:id="#+id/User"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/tv_main_title" />
<TextView
android:layout_width="294dp"
android:layout_height="65dp"
android:text="Please Complete Information"
android:textColor="#color/colorBackground"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:textSize="20dp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Age"
android:id="#+id/textView12"
android:layout_above="#+id/gender"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<EditText
android:layout_width="50dp"
android:layout_height="50dp"
android:inputType="number"
android:ems="10"
android:id="#+id/editText3"
android:imeOptions="actionDone"
android:layout_alignTop="#+id/gender"
android:layout_alignLeft="#+id/editText"
android:layout_marginLeft="0dp"
android:layout_column="1" />
</TableRow>
</TableLayout>
<RelativeLayout
android:layout_width="194dp"
android:layout_height="26dp"></RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Gender"
android:id="#+id/textView11"
/>
<Spinner
android:layout_width="113dp"
android:layout_height="40dp"
android:id="#+id/gender"
android:layout_above="#+id/textView5"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_alignStart="#+id/textView4"
android:layout_alignEnd="#+id/textView3"
android:spinnerMode="dropdown"
android:popupBackground="#color/colorBackground" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="329dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/weightLabel"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/colorBackground"
android:textSize="25dp"
android:paddingRight="0dp"
android:paddingLeft="-2dp" />
<Spinner
android:id="#+id/WeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="#string/weightLabel"
android:spinnerMode="dropdown"
android:layout_weight="2"
android:textAlignment="center"
android:popupBackground="#drawable/graybackground2"
android:layout_span="2"
android:layout_column="1" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/heightLabel"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/colorBackground"
android:textSize="25dp"
android:layout_column="0"
android:layout_marginLeft="5dp" />
<Spinner
android:id="#+id/HeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="#string/heightLabel"
android:layout_weight="2"
android:popupBackground="#drawable/graybackground2"
android:spinnerMode="dropdown"
android:layout_marginTop="0dp"
android:layout_margin="0dp"
android:layout_marginBottom="0dp"
android:layout_column="1"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:textAlignment="center"
android:paddingStart="5dp"
android:layout_marginLeft="0dp"
android:layout_span="0"
android:layout_marginRight="0dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Activity Level"
android:id="#+id/textView7"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/activity_level"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Goal"
android:id="#+id/textView8"
android:layout_below="#+id/activity_level"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/goal"
android:layout_below="#+id/textView8"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:spinnerMode="dropdown" />
</TableRow>
</TableLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/savebutton"
android:radius="10dp"
android:textColor="#color/colorBackground"
android:onClick="saveAction"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/editText3"
android:layout_gravity="right" />
</LinearLayout>
`
Fragmenthome.java
import java.util.ArrayList;
public class FragmentHome extends Fragment implements
View.OnClickListener {
private TextView caloriesTotal;
private TextView caloriesRemain;
private ListView listView;
private LinearLayout mLayout;
private Animation anim;
ImageButton AddEntrybtn;
ImageButton ResetEntry;
Context context;
int goalCalories;
int totalCalorie;
Button mButton;
//Database
private DatabaseHandler dba;
private ArrayList<Food> dbFoods = new ArrayList<>();
private CustomListViewAdapter foodAdapter;
private Food myFood ;
//fragment
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
caloriesTotal = (TextView) myView.findViewById(R.id.tv_calorie_amount);
caloriesRemain = (TextView) myView.findViewById(R.id.calorieRemain);
listView = (ListView) myView.findViewById(R.id.ListId);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain) getActivity()).loadSelection(4);
}
});
ResetEntry = (ImageButton) myView.findViewById(R.id.ResetEntry);
ResetEntry.setOnClickListener(this);
refreshData();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
return myView;
}
public void reset () {
//
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList<Food> foodsFromDB = dba.getFoods();
//Loop
for (int i = 0; i < foodsFromDB.size(); i ++){
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood= new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.clear();
dbFoods.remove(myFood);
foodsFromDB.remove(myFood);
dba.deleteFood(foodId);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item,dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
}
public void refreshData (){
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList<Food> foodsFromDB = dba.getFoods();
totalCalorie = dba.totalCalories();
String formattedCalories = Utils.formatNumber(totalCalorie);
String formattedRemain = Utils.formatNumber(goalCalories -
totalCalorie);
//setting the editTexts:
caloriesTotal.setText("Total Calories: " + formattedCalories);
caloriesRemain.setText(formattedRemain);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
//Loop
for (int i = 0; i < foodsFromDB.size(); i ++){
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood= new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.add(myFood);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item,dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
}
//save prefs
public void savePrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
//get prefs
public int loadPrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
return sharedPreferences.getInt(key, value);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
case R.id.action_settings:
Intent preferenceScreenIntent = new Intent(getContext(),
PreferenceScreenActivity.class);
startActivity(preferenceScreenIntent);
break;
case R.id.ResetEntry:
reset();
anim= AnimationUtils.loadAnimation(getActivity(),
R.anim.fading);
listView.startAnimation(anim);
break;
}
}
}
preference.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="User Settings">
<EditTextPreference
android:title="Daily Calorie Amount"
android:inputType="number"
android:defaultValue="2000"
android:key="#string/prefs_key_daily_calorie_amount"
android:summary="#string/prefs_description_daily_calorie_amount" />
</PreferenceCategory>
</PreferenceScreen>
ok, so you have lines
SharedPreferences userInfo = getSharedPreferences("userInfo", 0);
SharedPreferences.Editor editor = userInfo.edit();
editor.putInt("tdee", tdee);
editor.commit();
which are storing your value in SharedPreferences. where do you have fetching this value? (smth like below)
int tdee = getSharedPreferences("userInfo", 0).getInt("tdee");
why do you say that int isn't stored? in my opinion is stored perfectly and you are not trying to restore it in e.g. onCreate at all (basing on posted code)
also: try to clear your code before posting question/answer, strip code from unnecesary and not related to problem lines

Categories