How I stop multi booking on same time? - java

I getting booking details from firebase firestore and set into Recyclerview by bean(DTO) class there i have time and date value in integer I wanna stop multi booking in same time or near 30 mints anyone tell me how can I stop it..??
Main Recyclerview Fragement There I getting value by firestore
RecyclerView listView=(RecyclerView)view.findViewById(R.id.listview);
lbean = new ArrayList<>();
sheduleAdapter= new SheduleAdapter(getActivity(),lbean);
listView.setHasFixedSize(true);
listView.setLayoutManager(new LinearLayoutManager(getActivity()));
listView.setAdapter(sheduleAdapter);
db.collection("users").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error:" + e.getMessage());
}
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
switch (doc.getType()) {
case ADDED:
bean = doc.getDocument().toObject(bean.class);
lbean.add(bean);
sheduleAdapter.notifyDataSetChanged();
break;
case MODIFIED:
bean = doc.getDocument().toObject(bean.class);
lbean.add(bean);
sheduleAdapter.notifyDataSetChanged();
break;
case REMOVED:
lbean.remove(bean);
sheduleAdapter.notifyDataSetChanged();
break;
}
}
}
});
Recyclerview Adapter there i set value from bean class
holder.mint.setText(String.valueOf(bean.get(position).getMint()));
holder.hour.setText(String.valueOf(bean.get(position).getHour()));
holder.day.setText(String.valueOf(bean.get(position).getDay()));
holder.month.setText(String.valueOf(bean.get(position).getMonth()));
holder.year.setText(String.valueOf(bean.get(position).getYear()));
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar c=Calendar.getInstance();
iHour = c.get(Calendar.HOUR_OF_DAY);
iMin = c.get(Calendar.MINUTE );
iYear = c.get(Calendar.YEAR);
iMonth = c.get(Calendar.MONTH);
iDay = c.get(Calendar.DAY_OF_MONTH);
iMin=bean.get(position).getMint();
iHour=bean.get(position).getHour();
iDay=bean.get(position).getDay();
iMonth=bean.get(position).getMonth();
iYear=bean.get(position).getYear();
c.set(iYear,iMonth,iDay,iHour,iMin);
String mm = String.valueOf(iMin);
String h = String.valueOf(iHour);
String d = String.valueOf(iDay);
String m = String.valueOf(iMonth);
String y = String.valueOf(iYear);
Toast.makeText(context, mm + "==" + h + "==" + d + "==" + m + "==" + y, Toast.LENGTH_SHORT).show();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference ref = db.collection("users").document();
final String myId = ref.getId();
Toast.makeText(context, myId, Toast.LENGTH_SHORT).show();
}
});
}

Related

inserting value into SQL database using java language in adroid studio

i have a code that take start time and stop time by clicking on button and make the difference between two time.
i want to issert this start, stop and difference value into database. But my code didnot insert these value into database. it insert no value. my code is not giving me any error. when i run it databse rows increse but no value shows into table. all column shows empty.
please help me friends.
public class cleaning extends Fragment {
TextView tvstarttime;
Button btn_start;
Button btn_end;
TextView tvend;
TextView diffence;
boolean isStarted = false;
String starttime, endtime, timedifference;
ProgressDialog progressDialog;
Connection conn;
boolean isSucess = false;
NetworkManager networkManager = new NetworkManager();
SharedPrefManager sharedPrefManager = new SharedPrefManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_cleaning, container, false);
tvstarttime = view.findViewById(R.id.txtstarttime);
btn_start = view.findViewById(R.id.btn_start);
tvend = view.findViewById(R.id.txtendtime);
diffence=view.findViewById(R.id.txtdifference);
starttime = tvstarttime.getText().toString().trim();
endtime = tvend.getText().toString().trim();
timedifference = diffence.getText().toString().trim();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isStarted){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time = format.format(calendar.getTime());
tvend.setText(time);
try {
Date date1 = format.parse(tvend.getText().toString());
Date date2 = format.parse(tvstarttime.getText().toString());
long mills = date1.getTime() - date2.getTime();
Log.v("Data1", ""+date1.getTime());
Log.v("Data2", ""+date2.getTime());
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills % (1000*60*60));
String diff = hours + ":" + mins;
diffence.setText(diff);
}
catch (ParseException e) {
e.printStackTrace();
}
btn_start.setText("START");
}else {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time1 = format.format(calendar.getTime());
tvstarttime.setText(time1);
btn_start.setText("STOP");
}
isStarted = !isStarted;
}
});
return view;
}
private class uploadcart extends AsyncTask<Void, Void, Void> {
/* #Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(ProductDetailFragment.this);
progressDialog.setTitle("Creating account please wait!");
progressDialog.show();
super.onPreExecute();
}*/
#Override
protected Void doInBackground(Void... voids) {
try {
ConnectionHelper con = new ConnectionHelper();
conn = con.connectionclasss(Const.DBUserNameStr, Const.DBPasswordStr, Const.db, Const.ip);
String queryStmt = "Insert into CleaningTable" +
" (StartTime, StopTime, TimeTaken) values "
+ "('"
+ starttime
+ "','"
+ endtime
+ "','"
+ timedifference
+ "')";
Statement stmt = conn.createStatement();
isSucess = stmt.execute(queryStmt);
isSucess = true;
conn.close();
// return data;
} catch (Exception e) {
isSucess = false;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (isSucess) {
Toast.makeText(getActivity(), "time added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "time not added", Toast.LENGTH_SHORT).show();
}
super.onPostExecute(aVoid);
}
}
}

null value on variable passed from inside a onclick response

Is there any reason why method CreatePlan won't allow me access to variable recipe_name from the onRecipeClicked function which is retrieved from the recyclerview adapter. The Log shows that the value is retrieved from the recyclerview, but I can't seem to pass it to another method.
Any help is appreciated.
Update
Also is there a way of assigning the auto incremented id created from createPlanRecipe to the id variable in createPlan?
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
EditText editPlanName;
Integer id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
RecipeListAdapter.OnRecipeClickListener listener = new RecipeListAdapter.OnRecipeClickListener() {
public void onRecipeClicked(int position, String recipe_name) {
Log.d("Recipe selected", recipe_name);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreatePlan();
}
});
}
public void ListRecipes() {
listRecipe.clear();
SQLiteDatabase db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
public void CreatePlan(){
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
db.createPlanRecipe(d_name, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, id);
}
}

How to set string value to spinner retrieved from Firestore database in android?

I have retrieved the value of gender from the firestore database which is a string.
Now to set this value to the Spinner of the gender so that user can check and update the value on its own.
The retrieved value should show, but I am unable to convert the string value and set it to the spinner in android.
I tried searching for similar examples but no good yet.
public class EditProfile extends AppCompatActivity {
private String Fullname, Username, SpinnerC, Gender, DateOfBirth;
private CircleImageView userImage;
private Button updateProfileDetails;
private static final String TAG = "DocSnippets";
private EditText uFullname,uUsername, uDateOfBirth;
private Uri mUri;
private StorageReference storageReference;
private Spinner uSpinnerC, uGender;
private String date, tokenId;
private String mUserId;
private int REQ_CODE = 100, PERMISSION_CODE = 200;
private DocumentReference mUserRef;
private String permissions[] = {
Manifest.permission.READ_EXTERNAL_STORAGE
};
private FirebaseAuth mAuth;
private FirebaseFirestore db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
mUserId = mAuth.getCurrentUser().getUid();
mUserRef = FirebaseFirestore.getInstance().collection("users").document(mUserId);
storageReference = FirebaseStorage.getInstance().getReference().child("profile_pic");
uFullname = (EditText) findViewById(R.id.register_etName1);
uUsername = (EditText) findViewById(R.id.register_etUserName1);
userImage = (CircleImageView) findViewById(R.id.setupprofile_image1);
uDateOfBirth = (EditText) findViewById(R.id.register_etDateOfBirth);
uGender = findViewById(R.id.register_etGender1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.gender, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
uGender.setAdapter(adapter);
uSpinnerC = findViewById(R.id.register_spinnerC1);
ArrayAdapter<CharSequence> adapterC = ArrayAdapter.createFromResource(this,
R.array.numbers, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
uSpinnerC.setAdapter(adapterC);
requestFunction();
userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQ_CODE);
}
});
uDateOfBirth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDateDialog();
}
});
getUserProfileDetails();
updateProfileDetails.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
checkDataAndSave();
}
});
}
private void getUserProfileDetails(){
mUserRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
String username = (String) document.getString("username");
String gender = (String) document.getString("gender");
String dateOfBirth = (String) document.getString("dateOfBirth");
String email = (String) document.getString("email");
String fullname = (String) document.getString("fullname");
String spinnerC = (String) document.getString("spinnerC");
String profilepic = (String) document.getString("profile_pic");
uUsername.setText(username);
uGender.setText(gender);
uDateOfBirth.setText(dateOfBirth);
uSpinnerC.setText(spinnerC);
Picasso.get()
.load(profilepic)
.resize(50, 50)
.centerCrop()
.into(userImage);
} else {
Log.d(TAG, "No such document");
}
}
}
});
}
public void showDateDialog() {
Calendar cal = Calendar.getInstance();
final int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH) ;
int year = cal.get(Calendar.YEAR);
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (day < 10 && monthOfYear < 10)
date = "0" + dayOfMonth + "/0" + monthOfYear + "/" + year;
else if (day < 10 && monthOfYear > 10)
date = "0" + dayOfMonth + "/" + monthOfYear + "/" + year;
else if (day > 10 && monthOfYear < 10)
date = dayOfMonth + "/0" + monthOfYear + "/" + year;
else
date = dayOfMonth + "/" + monthOfYear + "/" + year;
uDateOfBirth.setText(date);
}
};
DatePickerDialog dpDialog = new DatePickerDialog(this, listener, year, month, day);
dpDialog.show();
}
private void checkDataAndSave() {
String fullName = uFullname.getText().toString().trim();
String username = uUsername.getText().toString().trim();
String genderselection = uGender.getSelectedItem().toString();
String dateOfBirthSelected = uDateOfBirth.getText().toString();
String spinnerC = uSpinnerC.getSelectedItem().toString();
if (mUri == null){
Toast.makeText(this, "Please Select Image", Toast.LENGTH_SHORT).show();
return;
}
if (fullName.isEmpty()){
Toast.makeText(this, "Please enter your Name", Toast.LENGTH_SHORT).show();
return;
}
if (username.isEmpty()){
Toast.makeText(this, "Please enter your User Name", Toast.LENGTH_SHORT).show();
return;
}
if (genderselection.isEmpty()){
Toast.makeText(this, "Please Select the Gender", Toast.LENGTH_SHORT).show();
return;
}
if (spinnerC.isEmpty()){
Toast.makeText(this, "Please enter the value", Toast.LENGTH_SHORT).show();
return;
}
if (dateOfBirthSelected.isEmpty()){
Toast.makeText(this, "Please Enter the Date of Birth", Toast.LENGTH_SHORT).show();
return;
}
else{
uploadImage(fullName, username, genderselection, dateOfBirthSelected, spinnerC);
}
}
private void uploadImage(final String username, final String fullName, final String genderselection, final String dateOfBirthSelected, final String spinnerC) {
UploadTask task = storageReference.child(mUserId).putFile(mUri);
task.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
task.getResult().getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String imageUrl = uri.toString();
saveData(username, fullName, imageUrl, genderselection, dateOfBirthSelected, spinnerC);
}
});
}
else{
Toast.makeText(getApplicationContext(), task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void saveData(String username, String fullName, String imageUrl, String genderselection, String dateOfBirthSelected, String spinnerC) {
Map<String, Object> map = new HashMap<>();
map.put("profile_pic", imageUrl);
map.put("fullname", fullName);
map.put("username", username);
map.put("gender",genderselection);
map.put("dateOfBirth", dateOfBirthSelected);
map.put("spinnerC", spinnerC);
map.put("tokenId", tokenId);
map.put("userId", mAuth.getCurrentUser().getUid());
//to save the current date
// map.put("date", new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date()));
mUserRef.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(EditProfile.this, "Please Verify Your Email To Login", Toast.LENGTH_SHORT).show();
Intent toHomeActivity = new Intent(EditProfile.this, SignInActivity.class);
toHomeActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(toHomeActivity);
finish();
}
else{
Toast.makeText(getApplicationContext(), task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
concern is regarding these lines in getUserProfileDetails() method
uGender.setText(gender);
uSpinnerC.setText(spinnerC);
You can do that check if your spiner text in male then setSelection 1 or 0 like below
String spinnerC = (String) document.getString("spinnerC");
if (spinnerC.equals("Male")){
uSpinnerC.setSelection(0);
}else{
uSpinnerC.setSelection(1); //female case
}

how to compare date and not display feauter week date in android

public class TestActvity extends AppCompatActivity implements View.OnClickListener {
Button next;
Button previous;
TextView textView;
int interval = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
next = (Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
next.setOnClickListener(this);
previous.setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView);
getDate(interval);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.next)
{
interval = interval + 7;
getDate(interval);
} else if (view.getId() == R.id.previous) {
interval = interval - 7;
getDate(interval);
}
}
public void getDate(int interval) {
try {
Calendar c = GregorianCalendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.add(Calendar.DAY_OF_WEEK, interval - 2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
textView.setText(startDate + " to " + endDate);
Date date = new Date();
String modifiedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
if ( endDate.compareTo(modifiedDate) > 0) {
Log.d("data", "" + "");
}
Log.d("data", "" + "");
} catch (Exception e) {
}
}
}
Using this code, i am displaying Monday to Sunday like
2017-7-3 to 2017-7-9 ,2017-7-10 to 2017-7-16 ,2017-7-17 to 2017-7-23
,2017-7-24 to 2017-7-30 ,2017-7-31 to 2017-8-5 ...
Receptively but what I want, if current week is
2017-7-24 to 2017-7-30
then when we click on next week it should display it should display only previous week please suggest me in this scenario I will compare date.
if (c.getTime().after(new Date())){
next.setVisibility(View.GONE);
}else {
next.setVisibility(View.VISIBLE);
}
apply this Condition and enjoy !!

Calendar cannot initialize null pointer exception on 5.1 API level

This time reminder class, time reminder is crashing on click and erroe goes on "custom.showDialogue" and the error is the following:
FATAL EXCEPTION: main
Process: com.appmetrik.notestakingapp, PID: 18607
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.app.notes.CustomDateTimePicker.showDialog()' on a null object reference
at com.app.notes.AddReminder.onClick(AddReminder.java:261)
public class AddReminder extends AppCompatActivity implements
android.view.View.OnClickListener`{
CustomDateTimePicker custom = null;
TextView txt_Time;
TextView txt_Date;
TextView txt_Day;
EditText et_Reminder_Title;
EditText et_Reminder_Description;
ImageButton btn_Submit_Reminder;
public static String var_Reminder_Title;
public String var_Reminder_Description;
public String var_Reminder_Time;
public String var_Reminder_Date;
public String var_Reminder_Day;
public int var_Not_Day;
public int var_Not_Month;
public int var_Not_Year;
public int var_Not_Hour;
public int var_Not_Min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_reminder);
txt_Time = (TextView) findViewById(R.id.txtEditTime);
txt_Time.setOnClickListener(this);
txt_Date = (TextView) findViewById(R.id.txtEditDate);
txt_Date.setOnClickListener(this);
txt_Day = (TextView) findViewById(R.id.txtEditDay);
txt_Day.setOnClickListener(this);
et_Reminder_Title= (EditText) findViewById(R.id.etEditReminderTitle);
et_Reminder_Description = (EditText) findViewById(R.id.etReminderDescription);
btn_Submit_Reminder = (ImageButton) findViewById(R.id.imgBtnSubmitReminder);
btn_Submit_Reminder.setOnClickListener(this);
try {
custom = new CustomDateTimePicker(AddReminder.this,
new CustomDateTimePicker.ICustomDateTimeListener() {
#Override
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName,
int hour24, int hour12, int min, int sec,
String AM_PM) {
txt_Time.setText(hour12 + ":" + min + " " + AM_PM);
txt_Date.setText(calendarSelected
.get(Calendar.DAY_OF_MONTH)
+ "/" + (monthNumber + 1) + "/" + year);
txt_Day.setText(weekDayFullName);
var_Not_Hour = hour24;
var_Not_Min = min;
var_Not_Month = monthNumber;
var_Not_Day = calendarSelected
.get(Calendar.DAY_OF_MONTH);
var_Not_Year = year;
}
#Override
public void onCancel() {
}
});
/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);
/**
* Pass Directly current data and time to show when ita pop up
*/
custom.setDate(Calendar.getInstance());
}
catch (Exception ex){
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Calendar Initialization Failed...", Toast.LENGTH_LONG).show();
}
findViewById(R.id.button_date).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
custom.showDialog();
}
});
}
public void getValues(){
var_Reminder_Title = et_Reminder_Title.getText().toString();
var_Reminder_Time = txt_Time.getText().toString();
var_Reminder_Date = txt_Date.getText().toString();
var_Reminder_Day = txt_Day.getText().toString();
var_Reminder_Description = et_Reminder_Description.getText().toString();
}
public boolean validate()
{
boolean allValid = true;
if(et_Reminder_Title.getText().toString().trim().length() == 0)
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
et_Reminder_Title.setError("Please Enter a Reminder Title here");
}
});
}
if(txt_Time.getText() == "Time")
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
et_Reminder_Title.setError("Tap Here to Select a Due Date and Time");
}
});
}
return allValid;
}
public void addReminder(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS reminders(ReminderId INTEGER PRIMARY KEY AUTOINCREMENT, ReminderTitle Text,ReminderTime Text,ReminderDate Text,ReminderDay Text, ReminderDescription Text);");
db.execSQL("INSERT INTO reminders(ReminderTitle,ReminderTime,ReminderDate,ReminderDay,ReminderDescription) VALUES('"+var_Reminder_Title+"','"+var_Reminder_Time+"','"+var_Reminder_Date+"','"+var_Reminder_Day+"','"+var_Reminder_Description+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Reminder Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Reminder Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void addNotification(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS notifications(NotificationId INTEGER PRIMARY KEY AUTOINCREMENT, NotificationTitle Text);");
db.execSQL("INSERT INTO notifications(NotificationTitle) VALUES('"+var_Reminder_Title+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Notification Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Notification Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void remind(){
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// set for 30 seconds later
alarmMgr.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + 30000, alarmIntent);
Toast.makeText(AddReminder.this, "Set Alarm", Toast.LENGTH_LONG).show();
}
public void al(){
// for Alarm 25/12/2012 at 12.00
Calendar myAlarmDate = Calendar.getInstance();
myAlarmDate.setTimeInMillis(System.currentTimeMillis());
myAlarmDate.set(var_Not_Year, var_Not_Month, var_Not_Day, var_Not_Hour, var_Not_Min, 0);
//Toast.makeText(AddReminder.this, ""+var_Not_Year+" "+ var_Not_Month+" "+ var_Not_Day+" "+var_Not_Hour+" "+var_Not_Min+" "+ 0, Toast.LENGTH_LONG).show();
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent0 = new Intent(this, AlarmReceiver.class);
//intent0.putExtra("Ringtone",getResources().getResourceName(R.raw.bbm_tone));
intent0.putExtra("Heading",var_Reminder_Title);
PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent0, 0);
//set timer you want alarm to work (here I have set it to 7.20pm)
//Intent intent0 = new Intent(this, OldEntryRemover.class);
/* Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.MONTH,12);
timeOff9.set(Calendar.DAY_OF_MONTH,1);
timeOff9.set(Calendar.YEAR,2015);
timeOff9.set(Calendar.HOUR_OF_DAY, 16);
timeOff9.set(Calendar.MINUTE, 45);
timeOff9.set(Calendar.SECOND, 0);
*/
//set that timer as a RTC Wakeup to alarm manager object
alarmMgr0.set(AlarmManager.RTC_WAKEUP, myAlarmDate.getTimeInMillis(), pendingIntent0);
// Toast.makeText(AddReminder.this, "Alarm", Toast.LENGTH_LONG).show();
}
#Override
public void onBackPressed ()
{
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.txtEditTime || v.getId() == R.id.txtEditDate || v.getId() == R.id.txtEditDay){
// custom.showDialog();
}
else if(v.getId() == R.id.imgBtnSubmitReminder) {
if (validate() == true) {
getValues();
addReminder();
// addNotification();
al();
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
}
}
}
this is custom date time picker class which is having the method showDialogue and it is using in the previous class. It is working perfectly on the version is less than 5.0 API but it is crashing on the version of 5.1 error is datetimepicker cannot be initialized.
public class CustomDateTimePicker implements android.view.View.OnClickListener {
private DatePicker datePicker;
private TimePicker timePicker;
private ViewSwitcher viewSwitcher;
private final int SET_DATE = 100, SET_TIME = 101, SET = 102, CANCEL = 103;
private Button btn_setDate, btn_setTime, btn_set, btn_cancel;
private Calendar calendar_date = null;
private Activity activity;
private ICustomDateTimeListener iCustomDateTimeListener = null;
private Dialog dialog;
private boolean is24HourView = true, isAutoDismiss = true;
private int selectedHour, selectedMinute;
public CustomDateTimePicker(Activity a,
ICustomDateTimeListener customDateTimeListener) {
activity = a;
iCustomDateTimeListener = customDateTimeListener;
dialog = new Dialog(activity);
// Context context = new ContextThemeWrapper(new MyContextWrapper, android.R.style.Theme_Holo_Light_Dialog);
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});
/*
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});*/
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View dialogView = getDateTimePickerLayout();
dialog.setContentView(dialogView);
}
public View getDateTimePickerLayout() {
LinearLayout.LayoutParams linear_match_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout.LayoutParams linear_wrap_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams frame_match_wrap = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
LinearLayout linear_main = new LinearLayout(activity);
linear_main.setLayoutParams(linear_match_wrap);
linear_main.setOrientation(LinearLayout.VERTICAL);
linear_main.setGravity(Gravity.CENTER);
LinearLayout linear_child = new LinearLayout(activity);
linear_child.setLayoutParams(linear_wrap_wrap);
linear_child.setOrientation(LinearLayout.VERTICAL);
LinearLayout linear_top = new LinearLayout(activity);
linear_top.setLayoutParams(linear_match_wrap);
btn_setDate = new Button(activity);
btn_setDate.setLayoutParams(button_params);
btn_setDate.setText("Set Date");
btn_setDate.setId(SET_DATE);
btn_setDate.setOnClickListener(this);
btn_setTime = new Button(activity);
btn_setTime.setLayoutParams(button_params);
btn_setTime.setText("Set Time");
btn_setTime.setId(SET_TIME);
btn_setTime.setOnClickListener(this);
linear_top.addView(btn_setDate);
linear_top.addView(btn_setTime);
viewSwitcher = new ViewSwitcher(activity);
viewSwitcher.setLayoutParams(frame_match_wrap);
datePicker = new DatePicker(activity);
timePicker = new TimePicker(activity);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
selectedHour = hourOfDay;
selectedMinute = minute;
}
});
viewSwitcher.addView(timePicker);
viewSwitcher.addView(datePicker);
LinearLayout linear_bottom = new LinearLayout(activity);
linear_match_wrap.topMargin = 8;
linear_bottom.setLayoutParams(linear_match_wrap);
btn_set = new Button(activity);
btn_set.setLayoutParams(button_params);
btn_set.setText("Set");
btn_set.setId(SET);
btn_set.setOnClickListener(this);
btn_cancel = new Button(activity);
btn_cancel.setLayoutParams(button_params);
btn_cancel.setText("Cancel");
btn_cancel.setId(CANCEL);
btn_cancel.setOnClickListener(this);
linear_bottom.addView(btn_set);
linear_bottom.addView(btn_cancel);
linear_child.addView(linear_top);
linear_child.addView(viewSwitcher);
linear_child.addView(linear_bottom);
linear_main.addView(linear_child);
//Invisible Calender View
datePicker.getCalendarView().setVisibility(View.GONE);
return linear_main;
}
public void showDialog() {
if (!dialog.isShowing()) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
selectedHour = calendar_date.get(Calendar.HOUR_OF_DAY);
selectedMinute = calendar_date.get(Calendar.MINUTE);
timePicker.setIs24HourView(is24HourView);
timePicker.setCurrentHour(selectedHour);
timePicker.setCurrentMinute(selectedMinute);
datePicker.updateDate(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DATE));
dialog.show();
btn_setDate.performClick();
btn_setTime.performClick();
}
}
public void setAutoDismiss(boolean isAutoDismiss) {
this.isAutoDismiss = isAutoDismiss;
}
public void dismissDialog() {
if (!dialog.isShowing())
dialog.dismiss();
}
public void setDate(Calendar calendar) {
if (calendar != null)
calendar_date = calendar;
}
public void setDate(Date date) {
if (date != null) {
calendar_date = Calendar.getInstance();
calendar_date.setTime(date);
}
}
public void setDate(int year, int month, int day) {
if (month < 12 && month >= 0 && day < 32 && day >= 0 && year > 100
&& year < 3000) {
calendar_date = Calendar.getInstance();
calendar_date.set(year, month, day);
}
}
public void setTimeIn24HourFormat(int hourIn24Format, int minute) {
if (hourIn24Format < 24 && hourIn24Format >= 0 && minute >= 0
&& minute < 60) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = true;
}
}
public void setTimeIn12HourFormat(int hourIn12Format, int minute,
boolean isAM) {
if (hourIn12Format < 13 && hourIn12Format > 0 && minute >= 0
&& minute < 60) {
if (hourIn12Format == 12)
hourIn12Format = 0;
int hourIn24Format = hourIn12Format;
if (!isAM)
hourIn24Format += 12;
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = false;
}
}
public void set24HourFormat(boolean is24HourFormat) {
is24HourView = is24HourFormat;
}
public interface ICustomDateTimeListener {
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName, int hour24,
int hour12, int min, int sec, String AM_PM);
public void onCancel();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case SET_DATE:
btn_setTime.setEnabled(true);
btn_setDate.setEnabled(false);
viewSwitcher.showNext();
break;
case SET_TIME:
btn_setTime.setEnabled(false);
btn_setDate.setEnabled(true);
viewSwitcher.showPrevious();
break;
case SET:
if (iCustomDateTimeListener != null) {
int month = datePicker.getMonth();
int year = datePicker.getYear();
int day = datePicker.getDayOfMonth();
calendar_date.set(year, month, day, selectedHour,
selectedMinute);
iCustomDateTimeListener.onSet(dialog, calendar_date,
calendar_date.getTime(), calendar_date
.get(Calendar.YEAR),
getMonthFullName(calendar_date.get(Calendar.MONTH)),
getMonthShortName(calendar_date.get(Calendar.MONTH)),
calendar_date.get(Calendar.MONTH), calendar_date
.get(Calendar.DAY_OF_MONTH),
getWeekDayFullName(calendar_date
.get(Calendar.DAY_OF_WEEK)),
getWeekDayShortName(calendar_date
.get(Calendar.DAY_OF_WEEK)), calendar_date
.get(Calendar.HOUR_OF_DAY),
getHourIn12Format(calendar_date
.get(Calendar.HOUR_OF_DAY)), calendar_date
.get(Calendar.MINUTE), calendar_date
.get(Calendar.SECOND), getAMPM(calendar_date));
}
if (dialog.isShowing() && isAutoDismiss)
dialog.dismiss();
break;
case CANCEL:
if (iCustomDateTimeListener != null)
iCustomDateTimeListener.onCancel();
if (dialog.isShowing())
dialog.dismiss();
break;
}
}
/**
* #param date
* date in String
* #param fromFormat
* format of your <b>date</b> eg: if your date is 2011-07-07
* 09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
* #param toFormat
* format to which you want to convert your <b>date</b> eg: if
* required format is 31 July 2011 then the toFormat should be
* <b>d MMMM yyyy</b>
* #return formatted date
*/
public static String convertDate(String date, String fromFormat,
String toFormat) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
Date d = simpleDateFormat.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
simpleDateFormat = new SimpleDateFormat(toFormat);
simpleDateFormat.setCalendar(calendar);
date = simpleDateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
private String getMonthFullName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getMonthShortName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getWeekDayFullName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private String getWeekDayShortName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private int getHourIn12Format(int hour24) {
int hourIn12Format = 0;
if (hour24 == 0)
hourIn12Format = 12;
else if (hour24 <= 12)
hourIn12Format = hour24;
else
hourIn12Format = hour24 - 12;
return hourIn12Format;
}
private String getAMPM(Calendar calendar) {
String ampm = (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
: "PM";
return ampm;
}
enter image description here
private void resetData() {
calendar_date = null;
is24HourView = true;
}
public static String pad(int integerToPad) {
if (integerToPad >= 10 || integerToPad < 0)
return String.valueOf(integerToPad);
else
return "0" + String.valueOf(integerToPad);
}
}

Categories