I have two dates in string format and stored it using shared preference.the first date(current date)is set to date picker date and second one is the date after adding 41 days to the first date.In a button i have to get the difference between the two dates in days.And it is stored using shared preference.The problem is that i have to decrement the difference between these two dates according to each current date.How can do that?please help...
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import java.util.Calendar;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeUnit;
import static com.example.aiswarya.mantraapp.R.id.end;
//import static com.example.aiswarya.mantraapp.R.id.enddate;
import static com.example.aiswarya.mantraapp.R.id.imageView;
import static com.example.aiswarya.mantraapp.R.id.myImageViewText;
//import static com.example.aiswarya.mantraapp.R.id.startdate;
import static com.example.aiswarya.mantraapp.R.id.textView3;
/**
* Created by aiswarya on 3/24/2017.
*/
public class Fasting extends AppCompatActivity {
ImageButton backb;
ImageButton reset;
TextView startdate,enddate;
ImageView remaining;
TextView remainingtext;
SharedPreferences myprefs;
public String dayys;
public long from,to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitydate);
backb=(ImageButton) findViewById(R.id.back);
reset= (ImageButton) findViewById(R.id.reset);
// startdate= (TextView) findViewById(R.id.textView2);
// enddate= (TextView) findViewById(textView3);
remaining=(ImageView) findViewById(R.id.myImageView);
//remainingtext=(TextView) findViewById(R.id.myImageViewText);
backb.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(Fasting.this,
Home.class);
startActivity(intent);
}
});
reset.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startdate.setText("START DATE");
enddate.setText("END DATE");
remainingtext.setText("REMAINING DAYS");
}
});
myprefs=getPreferences(MODE_PRIVATE);
init();
}
public void selectFrom(View v) {
final Calendar today = Calendar.getInstance();
DatePickerDialog dp = new DatePickerDialog(Fasting.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Log.d("date", dayOfMonth + "/" + month + "/" + year);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
((TextView)findViewById(R.id.textView2)).setText(cal.get(Calendar.DAY_OF_MONTH) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.YEAR));
cal.add(Calendar.DAY_OF_MONTH, 41);
((TextView)findViewById(textView3)).setText(cal.get(Calendar.DAY_OF_MONTH) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.YEAR));
long from = today.getTimeInMillis();
long to = cal.getTimeInMillis();
int days = (int) TimeUnit.MILLISECONDS.toDays(Math.abs(from - to));
Toast.makeText(getApplicationContext(), "DAYS = " + days, Toast.LENGTH_LONG).show();
final String dayss=String.valueOf(days);
remaining.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
remainingtext.setText(""+dayss+" DAYS");
}
});
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
dp.show();
}
private void init(){
startdate=(TextView) findViewById(R.id.textView2);
enddate=(TextView) findViewById(R.id.textView3);
remainingtext=(TextView) findViewById(R.id.myImageViewText);
readPreferences();
}
public void onSave(View view) {
String start=startdate.getText().toString();
String end=enddate.getText().toString();
String rem=remainingtext.getText().toString();
//int ageText=Integer.parseInt(age.getText().toString());
SharedPreferences.Editor editor=myprefs.edit();
editor.putString("keyname",start);
editor.putString("keyage",end);
editor.putString("keyrem",rem);
editor.commit();
}
public void onReset(View view) {
SharedPreferences.Editor editor=myprefs.edit();
editor.clear();
editor.commit();
readPreferences();
}
public void readPreferences(){
String stl= myprefs.getString("keyname","");
startdate.setText(stl);
//int vall=myprefs.getInt("keyage",0);
String vall=myprefs.getString("keyage","");
enddate.setText(String.valueOf(vall));
String remdays=myprefs.getString("keyrem","");
remainingtext.setText(String.valueOf(remdays));
}
}
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.aiswarya.mantraapp.Fasting">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#drawable/linir_back"
>
<ImageButton
android:id="#+id/back"
android:layout_width="50dp"
android:layout_marginTop="5dp"
android:layout_height="30dp"
android:background="#drawable/linir_back"
android:src="#drawable/back_button"/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="FASTING"
android:textSize="30dp"
android:textColor="#color/colorBlue"
android:textStyle="bold"
/>
</LinearLayout>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColorHint="#color/colorAccent"
android:textStyle="bold"
android:textColor="#color/colorAccent"
android:visibility="visible"
android:onClick="selectFrom"
android:layout_marginTop="5dp"
android:text="START DATE"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_marginTop="10dp"
android:textColorHint="#color/colorAccent"
android:textStyle="bold"
android:textColor="#color/colorAccent"
android:visibility="visible"
android:text="END DATE"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/submit4resized1"
android:onClick="onSave"
android:layout_marginLeft="90dp"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/reset"
android:src="#drawable/resetbutton"
android:layout_marginTop="5dp"
android:background="#color/colorWhite"
android:layout_marginLeft="70dp"
android:onClick="onReset" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="216dp">
<ImageView
android:id="#+id/myImageView"
android:layout_width="200dp"
android:layout_height="150dp"
android:onClick="showDiff"
android:src="#drawable/new1"
android:layout_marginRight="63dp"
android:layout_marginEnd="63dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/myImageViewText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="REMAINING DAYS"
android:textColor="#color/colorWhite"
android:layout_marginRight="41dp"
android:layout_marginEnd="41dp"
android:layout_alignBottom="#+id/myImageView"
android:layout_alignRight="#+id/myImageView"
android:layout_alignEnd="#+id/myImageView"
android:layout_marginBottom="65dp" />
</RelativeLayout>
Related
I have created the CreateEvent.java module to upload the data to firebase. But how to retrieve the data and show in the Cardlist? For example show in the xml file below. And also if there was more than 1 data in firebase, how to show in with multiple cardlist that I have created in the xml file?
CreateEvent.java
package com.example.edward.eventmanagementsystem.ManageEvent;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.edward.eventmanagementsystem.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import static android.widget.Toast.LENGTH_SHORT;
public class CreateEvent extends Activity {
private static final String TAG = "activity_create_event";
private Uri filePath;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private DatabaseReference mDatabaseReference;
private Button mRegisterButton;
EditText mEventNameText, mContactNumText, mEventLocationText;
TextView mEventDate;
RadioGroup mEventType;
FirebaseStorage storage;
StorageReference storageRef,imageRef;
ProgressDialog progressDialog;
UploadTask uploadTask;
Uri uriImage = Uri.parse("com.example.edward.eventmanagementsystem.ManageEvent/"+ R.drawable.ic_launcher_background);
public static final int PICK_IMAGE = 1;
ImageView mimageToUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
FirebaseDatabase firebaseDatabase;
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("ListEventInformation").push();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
mRegisterButton = (Button)findViewById(R.id.btnRegisterEvent);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
mDisplayDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
CreateEvent.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: date: mm/dd/yyyy: " + month + "/" + day + "/" + year);
String date = month + "/" + day + "/" + year;
mDisplayDate.setText(date);
}
};
//perform action upload image
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
//insert data to database
mEventNameText = (EditText) findViewById(R.id.RegisterEventName);
mContactNumText = (EditText) findViewById(R.id.RegisterContactNumber);
mEventDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mEventType = (RadioGroup) findViewById(R.id.RegisterEventRadiogroup);
mEventLocationText = (EditText) findViewById(R.id.RegisterEventLocation);
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
mRegisterButton = (Button) findViewById(R.id.btnRegisterEvent);
mimageToUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CreateEvent.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else {
ActivityCompat.requestPermissions(CreateEvent.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = mEventType.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton)findViewById(selectedId);
final String name = mEventNameText.getText().toString().trim();
final String contact = mContactNumText.getText().toString().trim();
final String date = mEventDate.getText().toString().trim();
final String type = radioButton.getText().toString().trim();
final String location = mEventLocationText.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
mEventNameText.setError("Enter First Name!");
return;
}
if (TextUtils.isEmpty(date)) {
mEventDate.setError("Enter Date!");
return;
}
if (TextUtils.isEmpty(type)) {
radioButton.setError("Enter Phone Number!");
return;
}
if(isValidPhone(contact)){
Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
}else {
mContactNumText.setError("Phone number is not valid");
Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(location)) {
mEventLocationText.setError("Enter Location!");
return;
}
Map userInfo = new HashMap();
userInfo.put("mEventNameText", name);
userInfo.put("mContactNumText", contact);
userInfo.put("mEventDate", date);
userInfo.put("radioButton", type);
userInfo.put("mEventLocationText", location);
mDatabaseReference.updateChildren(userInfo);
final String fileName = System.currentTimeMillis()+"";
if(uriImage != null) {
StorageReference storageReference = storage.getReference();
storageReference.child("profileImageUrl").child(fileName).putFile(uriImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
mDatabaseReference.child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){ }
else{
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}else{
}
Toast.makeText(getApplicationContext(),"New event created successfully!",LENGTH_SHORT).show();
Intent ManageEventMenu = new Intent(CreateEvent.this, com.example.edward.eventmanagementsystem.ManageEvent.ManageEventMenu.class);
startActivity(ManageEventMenu);
}
});
}
public boolean isValidPhone(CharSequence phone) {
boolean check=false;
if(!Pattern.matches("[a-zA-Z]+", phone))
{
if(phone.length() < 10 || phone.length() > 11)
{
check = false;
}
else
{
check = true;
}
}
else
{
check=false;
}
return check;
}
private void selectPdf() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(intent,86);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 86 && resultCode == RESULT_OK && data != null){
final Uri imageUri = data.getData();
uriImage = imageUri;
mimageToUpload.setImageURI(uriImage);
}
else {
Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
}
}
}
I would like to show the data in this way.
The sample of xml file I would like to display the data create from Firebase in upload from CreateEvent.java
activity_list_of_event.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"
android:background="#drawable/gradientwallpaper">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:textSize="24dp"
android:textColor="#color/white"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Total Created Event"
android:layout_marginLeft="10dp"
android:textSize="16dp"
android:textColor="#color/white"
android:layout_marginTop="10dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upcoming"
android:layout_marginLeft="10dp"
android:textSize="16dp"
android:textColor="#color/white"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pass"
android:gravity="right"
android:layout_marginRight="10dp"
android:textSize="16dp"
android:textColor="#color/white"/>
</LinearLayout>
<android.support.v7.widget.CardView 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="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:padding="10dp"
android:weightSum="10">
<LinearLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:id="#+id/item_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Month" />/ android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
<TextView
android:id="#+id/item_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Date" />/ android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:id="#+id/item_eventName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event Name"
android:textStyle="bold" />/android:textScaleX="18sp"
<TextView
android:id="#+id/item_contactNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Contact Number"
android:textStyle="bold" />
<TextView
android:id="#+id/item_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Type of event"
android:textStyle="bold" />
<TextView
android:id="#+id/itemLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Location"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="#+id/item_image"
android:layout_width="75dp"
android:layout_height="75dp"
android:background="#color/white"
android:scaleType="centerCrop"
android:src="#drawable/pic1" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I have two dates in string format and stored it using shared preference. The first date (current date) is set to date picker date and second one is the date after adding 41 days to the first date. In a button I have to get the difference between the two dates in days and it is stored using shared preference. The problem is, that I have to decrement the difference between these two dates according to each current date. How can do that? Please help.
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import java.util.Calendar;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeUnit;
import static com.example.aiswarya.mantraapp.R.id.end;
//import static com.example.aiswarya.mantraapp.R.id.enddate;
import static com.example.aiswarya.mantraapp.R.id.imageView;
import static com.example.aiswarya.mantraapp.R.id.myImageViewText;
//import static com.example.aiswarya.mantraapp.R.id.startdate;
import static com.example.aiswarya.mantraapp.R.id.textView3;
/**
* Created by aiswarya on 3/24/2017.
*/
public class Fasting extends AppCompatActivity {
ImageButton backb;
ImageButton reset;
TextView startdate,enddate;
ImageView remaining;
TextView remainingtext;
SharedPreferences myprefs;
public String dayys;
public long from,to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitydate);
backb=(ImageButton) findViewById(R.id.back);
reset= (ImageButton) findViewById(R.id.reset);
// startdate= (TextView) findViewById(R.id.textView2);
// enddate= (TextView) findViewById(textView3);
remaining=(ImageView) findViewById(R.id.myImageView);
//remainingtext=(TextView) findViewById(R.id.myImageViewText);
backb.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(Fasting.this,
Home.class);
startActivity(intent);
}
});
reset.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startdate.setText("START DATE");
enddate.setText("END DATE");
remainingtext.setText("REMAINING DAYS");
}
});
myprefs=getPreferences(MODE_PRIVATE);
init();
}
public void selectFrom(View v) {
final Calendar today = Calendar.getInstance();
DatePickerDialog dp = new DatePickerDialog(Fasting.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Log.d("date", dayOfMonth + "/" + month + "/" + year);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
((TextView)findViewById(R.id.textView2)).setText(cal.get(Calendar.DAY_OF_MONTH) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.YEAR));
cal.add(Calendar.DAY_OF_MONTH, 41);
((TextView)findViewById(textView3)).setText(cal.get(Calendar.DAY_OF_MONTH) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.YEAR));
long from = today.getTimeInMillis();
long to = cal.getTimeInMillis();
int days = (int) TimeUnit.MILLISECONDS.toDays(Math.abs(from - to));
Toast.makeText(getApplicationContext(), "DAYS = " + days, Toast.LENGTH_LONG).show();
final String dayss=String.valueOf(days);
remaining.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
remainingtext.setText(""+dayss+" DAYS");
}
});
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
dp.show();
}
private void init(){
startdate=(TextView) findViewById(R.id.textView2);
enddate=(TextView) findViewById(R.id.textView3);
remainingtext=(TextView) findViewById(R.id.myImageViewText);
readPreferences();
}
public void onSave(View view) {
String start=startdate.getText().toString();
String end=enddate.getText().toString();
String rem=remainingtext.getText().toString();
//int ageText=Integer.parseInt(age.getText().toString());
SharedPreferences.Editor editor=myprefs.edit();
editor.putString("keyname",start);
editor.putString("keyage",end);
editor.putString("keyrem",rem);
editor.commit();
}
public void onReset(View view) {
SharedPreferences.Editor editor=myprefs.edit();
editor.clear();
editor.commit();
readPreferences();
}
public void readPreferences(){
String stl= myprefs.getString("keyname","");
startdate.setText(stl);
//int vall=myprefs.getInt("keyage",0);
String vall=myprefs.getString("keyage","");
enddate.setText(String.valueOf(vall));
String remdays=myprefs.getString("keyrem","");
remainingtext.setText(String.valueOf(remdays));
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.aiswarya.mantraapp.Fasting">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#drawable/linir_back"
>
<ImageButton
android:id="#+id/back"
android:layout_width="50dp"
android:layout_marginTop="5dp"
android:layout_height="30dp"
android:background="#drawable/linir_back"
android:src="#drawable/back_button"/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="FASTING"
android:textSize="30dp"
android:textColor="#color/colorBlue"
android:textStyle="bold"
/>
</LinearLayout>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColorHint="#color/colorAccent"
android:textStyle="bold"
android:textColor="#color/colorAccent"
android:visibility="visible"
android:onClick="selectFrom"
android:layout_marginTop="5dp"
android:text="START DATE"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_marginTop="10dp"
android:textColorHint="#color/colorAccent"
android:textStyle="bold"
android:textColor="#color/colorAccent"
android:visibility="visible"
android:text="END DATE"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/submit4resized1"
android:onClick="onSave"
android:layout_marginLeft="90dp"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/reset"
android:src="#drawable/resetbutton"
android:layout_marginTop="5dp"
android:background="#color/colorWhite"
android:layout_marginLeft="70dp"
android:onClick="onReset" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="216dp">
<ImageView
android:id="#+id/myImageView"
android:layout_width="200dp"
android:layout_height="150dp"
android:onClick="showDiff"
android:src="#drawable/new1"
android:layout_marginRight="63dp"
android:layout_marginEnd="63dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/myImageViewText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="REMAINING DAYS"
android:textColor="#color/colorWhite"
android:layout_marginRight="41dp"
android:layout_marginEnd="41dp"
android:layout_alignBottom="#+id/myImageView"
android:layout_alignRight="#+id/myImageView"
android:layout_alignEnd="#+id/myImageView"
android:layout_marginBottom="65dp" />
</RelativeLayout>
</LinearLayout>
your apps showing diffrence in messagebox after changing the date from todays date to later 24 , 23 , 22 ,....
This is the Java end. It has the Spinner adapters and also the setOnItemClickListener methods. When I comment the "spTitles" setadAdapter method, the program runs. However the program runs whether or not I comment the spCategories setAdapter method
import java.util.ArrayList;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import com.playmaker.BudgetOh.R;
import com.playmaker.BudgetOh.adapter.CategoriesAdapter;
import com.playmaker.BudgetOh.manager.CategoriesManager;
import com.playmaker.BudgetOh.manager.ExpenseManager;
import com.playmaker.BudgetOh.model.Expense;
public class EditExpense extends Activity implements OnClickListener,
OnItemSelectedListener, OnDateSetListener, OnTimeSetListener {
private Spinner spTitles, spCategories;
;
private String cat_item;
private ArrayList<Expense> allExpenses;
private ArrayList<String> allTitles;
private Expense expense;
private String titlePosition;
private ExpenseManager expenseManager;
private Button btnEditExpenseDate, btnEditExpenseTime, btnAddExpense; //actually modify expense;
private EditText etEditExpenseTitle, etEditExpenseAmount, etEditExpenseComments;
private int mYear, mDay, mMonth, mHour, mMinute;
static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID = 1;
private ArrayAdapter<String> catAdapter;
private String title, date, time, amount, category, comment;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_expense);
init();
allExpenses = expenseManager.getAllExpenses();
for (Expense expense : allExpenses) {
allTitles.add(expense.getTitle());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, allTitles);
//Populting the categories
String[] osArray = {"Food and Drinks", "Transportation", "Health", "Leisure", "Other"};
catAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, osArray);
spTitles.setAdapter(adapter);
spCategories.setAdapter(catAdapter);
}
private void init() {
expenseManager = new ExpenseManager(this);
expense = new Expense();
//For Spinners
spTitles = (Spinner) findViewById(R.id.spTitles);
spCategories = (Spinner) findViewById(R.id.spCategories);
//For Buttons
btnEditExpenseTime = (Button) findViewById(R.id.btnEditExpenseTime);
btnEditExpenseDate = (Button) findViewById(R.id.btnEditExpenseDate);
btnAddExpense = (Button) findViewById(R.id.btnModifyExpense);
//For EditText
etEditExpenseTitle = (EditText) findViewById(R.id.etEditExpenseTitle);
etEditExpenseAmount = (EditText) findViewById(R.id.etEditExpenseAmount);
etEditExpenseComments = (EditText) findViewById(R.id.etEditExpenseComments);
//Setting Onclick listeners for all the buttons
btnEditExpenseDate.setOnClickListener(this);
btnEditExpenseTime.setOnClickListener(this);
btnAddExpense.setOnClickListener(this);
spTitles.setOnItemSelectedListener(this);
spCategories.setOnItemSelectedListener(this);
allExpenses = new ArrayList<Expense>();
allTitles = new ArrayList<String>();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnEditExpenseTime:
showDialog(TIME_DIALOG_ID);
break;
case R.id.btnEditExpenseDate:
showDialog(DATE_DIALOG_ID);
break;
case R.id.btnModifyExpense:
time = btnEditExpenseTime.getText().toString();
date = btnEditExpenseDate.getText().toString();
title = etEditExpenseTitle.getText().toString();
category = cat_item;
amount = etEditExpenseAmount.getText().toString();
comment = etEditExpenseComments.getText().toString();
expense.setTitle(title);
expense.setDate(date);
expense.setTime(time);
expense.setAmount(amount);
expense.setCategory(category);
expense.setComment(comment);
long ret = expenseManager.updateExpense(expense);
if (ret != -1) {
clearFields();
Toast.makeText(getApplicationContext(), "Entry Added"
, Toast
.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Failed-Entry"
, Toast
.LENGTH_LONG).show();
}
expenseManager.close();
break;
}
}
private void clearFields() {
etEditExpenseComments.setText("");
etEditExpenseAmount.setText("");
etEditExpenseTitle.setText("");
btnEditExpenseDate.setText("Date");
btnEditExpenseTime.setText("Time");
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
updateTime();
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
private void updateDate() {
this.btnEditExpenseDate.setText(new StringBuilder().append(mMonth + 1).append("-")
.append(mDay).append("-").append(mYear).append(" "));
}
private void updateTime() {
this.btnEditExpenseTime.setText(new StringBuilder().append(mHour).append(":")
.append(mMinute).append(" "));
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long arg3) {
switch (arg0.getId()) {
case R.id.spTitles:
titlePosition = allTitles.get(position);
expense = expenseManager.getExpense(titlePosition);
etEditExpenseComments.setText(expense.getComment());
etEditExpenseAmount.setText(expense.getAmount());
etEditExpenseTitle.setText(expense.getTitle());
break;
case R.id.spCategories:
cat_item = arg0.getItemAtPosition(position).toString();
break;
default:
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, this, mYear, mMonth, mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this, this, mHour, mMinute, true);
default:
break;
}
return null;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
switch (arg0.getId()) {
case R.id.spTitles:
etEditExpenseTitle.setText("");
etEditExpenseAmount.setText("");
etEditExpenseComments.setText("");
break;
default:
break;
}
}
}
This is the xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.playmaker.BudgetOh.activities.EditExpense">
<Spinner
android:id="#+id/spTitles"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<EditText
android:id="#+id/etEditExpenseTitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center"
android:hint="Expense Title"
android:paddingTop="10dp"></EditText>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/btnEditExpenseDate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.86"
android:text="Date" />
<Button
android:id="#+id/btnEditExpenseTime"
android:layout_width="163dp"
android:layout_height="wrap_content"
android:text="Time" />
</LinearLayout>
<EditText
android:id="#+id/etEditExpenseAmount"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center"
android:hint="Expense Amount"
android:paddingTop="10dp"></EditText>
<TextView
android:id="#+id/tvCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:text="#string/CategoriesString"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="25sp"
/>
<Spinner
android:id="#+id/spCategories"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#E3CF57">
</Spinner>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Comments"
android:textSize="25sp" />
<EditText
android:id="#+id/etEditExpenseComments"
android:layout_width="match_parent"
android:layout_height="70dp"
android:ems="10"
android:hint="Please enter you brief comments on your expense"
android:inputType="textMultiLine">
</EditText>
<Button
android:id="#+id/btnModifyExpense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Add Expense"
android:textSize="20sp" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:orientation="horizontal">
<Button
android:id="#+id/action_bar_button_cancel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="CANCEL" />
<Button
android:id="#+id/action_bar_button_ok"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="OK" />
</LinearLayout>
</LinearLayout>
<requestFocus />
</ScrollView>
</LinearLayout>
I have problems on how to make this functional. I have tested many codes now for this layout but it wont work. This is the layout i made wherein:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout2"
android:layout_marginLeft="30dp"
android:layout_marginTop="60dp"
android:padding="10dp"
android:background="#f7a29d">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Goal Name:"
android:id="#+id/tt"
android:layout_alignBottom="#+id/linearLayout2"
android:layout_alignParentStart="true"
android:textColor="#000000"
android:paddingBottom="5dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/goal_name"
android:textColor="#000000"
android:padding="10dp"
android:background="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Start Date:"
android:id="#+id/textView24"
android:textColor="#000000"
android:paddingTop="5dp"
android:paddingBottom="5dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/sdate"
android:textColor="#000000"
android:padding="10dp"
android:background="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="End Date:"
android:id="#+id/tt2"
android:textColor="#000000"
android:paddingTop="5dp"
android:paddingBottom="5dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/edate"
android:textColor="#000000"
android:padding="10dp"
android:background="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="NOTIFICATIONS OPTIONS"
android:id="#+id/textView25"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Time:"
android:id="#+id/textView35"
android:layout_row="2"
android:layout_column="0"
android:textColor="#000000" />
<GridLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_row="19"
android:layout_column="0">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="ShowTime"
android:id="#+id/showtime"
android:layout_row="1"
android:layout_column="0"
android:textColor="#000000"
android:layout_marginLeft="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Time"
android:id="#+id/settime"
android:layout_row="1"
android:layout_column="1"
android:layout_marginLeft="5dp" />
<TimePicker
android:id="#+id/timePicker"
android:layout_width="1dp"
android:layout_height="1dp"
android:visibility="invisible"/>
</GridLayout>
<GridLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Repeat:"
android:id="#+id/textView26"
android:layout_below="#+id/linearLayout2"
android:layout_row="0"
android:layout_column="0"
android:textColor="#000000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="ShowRepeat"
android:id="#+id/showRepeat"
android:layout_row="2"
android:layout_column="0"
android:textColor="#000000"
android:background="#ffffff"
android:padding="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Repetition Option:"
android:id="#+id/textView28"
android:layout_row="3"
android:layout_column="0"
android:textColor="#000000" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="#+id/toggleButton"
android:layout_row="2"
android:layout_column="1"
android:textColor="#000000"
android:background="#9bd8ea" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="set"
android:id="#+id/setRepetition"
android:layout_row="4"
android:layout_column="0"
android:textColor="#000000"
android:background="#3a738a" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Sound Option:"
android:id="#+id/textView30"
android:layout_row="7"
android:layout_column="0"
android:textColor="#000000" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="#+id/toggleButton2"
android:layout_row="8"
android:layout_column="0"
android:textColor="#000000"
android:background="#9bd8ea" />
</GridLayout>
</LinearLayout>
It look like this:
Goal Name: (data already given)
Start Date: (data already given)
End Date: (data already given)
Notifications Options
Time:
showTime [Set] -> time picker pop up
Repeat:
showRepeat [Toggle Button] -> chose if to repeat notifications once or not
Repetition Option:
[Set] -> Alert Dialog pop with choices and choices made is print in showRepeat TextView
Sound:
[Toggle Button] -> chose to notify with sound or not
SetNotifyActivity.java
package com.citu.goalsettingorganizer;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.app.Dialog;
import android.app.Activity;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;
import java.util.Calendar;
public class SetNotifyActivity extends AppCompatActivity {
private TextView goalname,startdate,enddate,showrepeat;
private TextView showTime;
private TimePicker timePicker;
private Button setTime,setRepeat;
private int hour;
private int minute;
private String format;
static final int TIME_PICKER_DIALOG_ID = 100;
MyDBAdapter dbhandler;
public int goal_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_notify);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
goalname = (TextView)findViewById(R.id.goal_name);
startdate = (TextView)findViewById(R.id.sdate);
enddate = (TextView)findViewById(R.id.edate);
showrepeat = (TextView)findViewById(R.id.showRepeat);
showTime = (TextView) findViewById(R.id.showtime);
setTime = (Button)findViewById(R.id.settime);
timePicker = (TimePicker)findViewById(R.id.timePicker);
setRepeat = (Button)findViewById(R.id.setRepetition);
goal_id = Integer.parseInt(extras.getString("goalid"));
//Create database
dbhandler = new MyDBAdapter(this);
displayDetails();
displayTime();
changeTimeButton();
selectRepeat();
}
public void displayDetails(){
List<Goals> oneGoal = dbhandler.getLatestGoal(goal_id);
for (final Goals goals : oneGoal) {
goalname.setText(goals.getGoalName());
startdate.setText(goals.getSMonth() + "/" + goals.getSDay() + "/" + goals.getSYear());
enddate.setText(goals.getEMonth() + "/" + goals.getEDay() + "/" + goals.getEYear());
}
}
public void displayTime(){
final Calendar getTime = Calendar.getInstance();
hour = getTime.get(Calendar.HOUR_OF_DAY);
minute = getTime.get(Calendar.MINUTE);
// set current time into textview
showTime(hour,minute);
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
public void changeTimeButton(){
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_PICKER_DIALOG_ID);
}
});
}
public void showTime(int hour, int min) {
if (hour == 0) {
hour += 12;
format = "AM";
}
else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
showTime.setText(new StringBuilder().append(pad(hour)).append(" : ").append(pad(min))
.append(" ").append(format));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
// set current time into textview
showTime(hour,minute);
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
};
// On clicking repeat type button
public void selectRepeat(){
setRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(SetNotifyActivity.this);
final EditText number = new EditText(SetNotifyActivity.this);
alert.setMessage("Enter a Number:");
alert.setTitle("");
alert.setView(number);
alert.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String tempnumber = number.getText().toString();
final CharSequence[] items = {"Hours","Days", "Weeks", "Months"};
AlertDialog.Builder builder = new AlertDialog.Builder(SetNotifyActivity.this);
builder.setTitle("Select Period:");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
showrepeat.setText(tempnumber+" "+items[item]);
dialog.dismiss();
}
}).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
alert.create().show();
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_PICKER_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
public void done(){
Intent myIntent = new Intent(SetNotifyActivity.this, MainMenuActivity.class);
startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_set_notify, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_done) {
done();
return true;
}
return super.onOptionsItemSelected(item);
}
}
My problem is when the user finish setting his notifications, i cant make it work. The notifications will work based on what he/she choose. I cant seem to find any sources that i could understand easily for this.
i have deleted the codes i tested to make notifications work so that it doesnt look messy. It doesnt work anyway-
So for the life of me I can not find the reason behind needing to click twice on the start date and start time for the picker dialog to open. I have searched these forums many times and they have all been mostly related to edit text fields whereas mine is a simple button but the onClickListener takes two hits. Thanks in advance.
This is my Class:
package com.shotsevolved.app
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.List;
public class DealCreator extends FragmentActivity {
String mUsername;
String companyName;
ParseGeoPoint location;
String title;
double mOldPrice;
double mNewPrice;
boolean isFree;
boolean isUnlimited;
String mDescription;
int mUses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "Ztgl9DAaj4XPrDnS2Ro8jNHiaNnTPFCeF6V1Gm71", "26QMHWwfHmxKfwMvKemaEXH2XsFxpO5sR8Csuo9v");
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_deal_creator);
final Button create = (Button)findViewById(R.id.createButton);
final ProgressBar progress = (ProgressBar)findViewById(R.id.progressIcon);
final LinearLayout view = (LinearLayout)findViewById(R.id.linView);
final LinearLayout view1 = (LinearLayout)findViewById(R.id.linView1);
final LinearLayout main = (LinearLayout)findViewById(R.id.mainLinear);
final CheckBox freeBox = (CheckBox)findViewById(R.id.freeBox);
final EditText oldPrice = (EditText)findViewById(R.id.oldPrice);
final EditText newPrice = (EditText)findViewById(R.id.newPrice);
final CheckBox unlimited = (CheckBox)findViewById(R.id.unlimitedBox);
final EditText uses = (EditText)findViewById(R.id.uses);
final Button date = (Button)findViewById(R.id.startDate);
final Button time = (Button)findViewById(R.id.startTime);
create.setVisibility(View.INVISIBLE);
Intent intent = getIntent();
mUsername = intent.getStringExtra("key");
ParseQuery<ParseObject> query = ParseQuery.getQuery("appUsers");
query.whereEqualTo("username", mUsername);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> user, ParseException e) {
if(user.size() == 1 && e == null){
int admin = user.get(0).getInt("admin");
if(admin == 2){
ParseQuery<ParseObject> query = ParseQuery.getQuery("AdminNames");
query.whereEqualTo("username", mUsername);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> user, ParseException e) {
if(user.size() == 1 && e == null){
unlimited.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
uses.setVisibility(View.INVISIBLE);
view1.removeView(uses);
}else{
uses.setVisibility(View.VISIBLE);
view1.addView(uses);
}
}
});
freeBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
oldPrice.setVisibility(View.INVISIBLE);
newPrice.setVisibility(View.INVISIBLE);
view.removeView(oldPrice);
view.removeView(newPrice);
}else{
oldPrice.setVisibility(View.VISIBLE);
newPrice.setVisibility(View.VISIBLE);
view.addView(oldPrice);
view.addView(newPrice);
}
}
});
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog(main);
}
});
time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog(main);
}
});
progress.setVisibility(View.GONE);
view.removeView(progress);
create.setVisibility(View.VISIBLE);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(freeBox.isChecked()){
isFree = true;
mOldPrice = 0;
mNewPrice = 0;
}else{
mOldPrice = Double.parseDouble(oldPrice.getText().toString());
mNewPrice = Double.parseDouble(newPrice.getText().toString());
isFree = false;
}
if(unlimited.isChecked()){
isUnlimited = true;
mUses = 0;
}else{
mUses = Integer.parseInt(uses.getText().toString());
isUnlimited = false;
}
//Call create deal class
deal();
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! Database Hacked!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! You are not an Admin!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! Database Hacked!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
private void deal() {
ParseObject newDeal = new ParseObject("Deals");
newDeal.put("uses", mUses);
newDeal.put("unlimitedUses", isUnlimited);
newDeal.put("description", mDescription);
newDeal.put("free", isFree);
newDeal.put("title", title);
newDeal.put("oldPrice", mOldPrice);
newDeal.put("newPrice", mNewPrice);
newDeal.put("location", location);
newDeal.put("username", mUsername);
newDeal.put("companyName", companyName);
newDeal.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Context context = getApplicationContext();
CharSequence text = "Deal Saved";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
And these are my Fragments:
Date:
package com.shotsevolved.app;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
Time:
package com.shotsevolved.app;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
And finally my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#1e1c1c"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="#dimen/height"
android:layout_alignParentTop="true"
android:background="#color/purple"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageButton
android:id="#+id/btn_backFromSettings"
android:layout_width="#dimen/width"
android:layout_height="fill_parent"
android:background="#drawable/ui_button_purple"
android:contentDescription="#string/desc"
android:src="#drawable/ico_left" />
<LinearLayout
android:layout_width="#dimen/divider_size"
android:layout_height="fill_parent"
android:background="#color/dark_purple" >
</LinearLayout>
<TextView
android:id="#+id/mainLogin"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:tag="bold"
android:text="#string/dealCreator"
android:textColor="#color/white"
android:textSize="#dimen/tex_size_xxlarge" />
<LinearLayout
android:layout_width="#dimen/divider_size"
android:layout_height="fill_parent"
android:background="#color/dark_purple" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/mainLinear">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/dim_20"
android:id="#+id/linView">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressIcon"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/titleOfDeal"
style="#style/EditText_Purple"
android:hint="Title of Deal"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/dealDescription"
android:gravity="top"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Describe company and deal"
android:layout_gravity="center_horizontal" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Free"
android:layout_marginTop="#dimen/dim_10"
style="#style/CheckBox_Purple"
android:textColor="#color/offwhite"
android:id="#+id/freeBox" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/oldPrice"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Old cost of product"
android:inputType="numberDecimal"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/newPrice"
android:layout_marginTop="#dimen/dim_10"
android:inputType="numberDecimal"
style="#style/EditText_Purple"
android:hint="New cost of product"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linView1"
android:paddingRight="#dimen/dim_20"
android:paddingLeft="#dimen/dim_20">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unlimited uses"
style="#style/CheckBox_Purple"
android:textColor="#color/offwhite"
android:id="#+id/unlimitedBox" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/uses"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Number of uses per customer"
android:inputType="number"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linView2"
android:gravity="center_horizontal"
android:layout_marginTop="#dimen/dim_10"
android:paddingRight="#dimen/dim_20"
android:paddingLeft="#dimen/dim_20">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startDate"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Start Date"
android:layout_marginRight="#dimen/dim_10"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startTime"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Start Time"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/dim_10"
android:gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set expiry date"
android:layout_marginRight="#dimen/dim_10"
android:padding="#dimen/dim_10"
style="#style/Button_Purple"
android:id="#+id/dateButtonEnd"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set expiry time"
android:padding="#dimen/dim_10"
style="#style/Button_Purple"
android:id="#+id/timeButtonEnd"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Create"
android:padding="#dimen/dim_10"
android:layout_marginTop="#dimen/dim_10"
android:layout_marginLeft="#dimen/dim_20"
android:layout_marginRight="#dimen/dim_20"
style="#style/Button_Purple"
android:id="#+id/createButton"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Hmm, your code looks ok. Can you try adding android:focusable="false" to your buttons. I'm curious if the problem is that you're just requesting focus the first click and the second actually initiates the click.
Also, if this doesn't help, can you put some logs in your click listener and also in the public void showTimePickerDialog(View v) { method as well ... to see if it's triggered the first click at all.
Try to add delay on button click it will avoid multi click
date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
date.setEnabled(false);
showDatePickerDialog(main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
date.setEnabled(true);
}
}, 100);
}
});