Datepicker and TimePicker dialogs take two clickes of button - android

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);
}
});

Related

How to retrieve data from the firebase and show inside the CardView nicely

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>

button not functioning?

I created a android studio button for my app and when I click on the register button it doesn't work . I don't get any errors it just doesn't work . When the user clicks the quiz button I want to go to the quiz activity
MainActivity.java
package com.littlekidsmath.yoong.mathlearningforkids;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemSelectedListener{
Button addBtn, subBtn, multiBtn, divisionBtn,quiz;
String[] levels = {"Easy","Medium","Hard"};
SharedPreferences prefs;
Switch settings;
Spinner language;
public String[] languages = {GameActivity.ENG,GameActivity.ARABIC,"বাংলা",GameActivity.FRENCH,GameActivity.GERMAN,GameActivity.MALAY};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("MyPref",MODE_PRIVATE);
settings = (Switch) findViewById(R.id.settings);
if(prefs.getBoolean("SOUND", false)){
settings.setChecked(true);
}
settings.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
prefs.edit().putBoolean("SOUND",b).commit();
}
});
addBtn = (Button) findViewById(R.id.addtion);
subBtn = (Button) findViewById(R.id.sub);
multiBtn = (Button) findViewById(R.id.multi);
divisionBtn = (Button) findViewById(R.id.divide);
quiz = (Button) findViewById(R.id.quiz);
language = (Spinner) findViewById(R.id.language);
addBtn.setOnClickListener(this);
subBtn.setOnClickListener(this);
multiBtn.setOnClickListener(this);
divisionBtn.setOnClickListener(this);
quiz.setOnClickListener(this);
language.setOnItemSelectedListener(this);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);
language.setAdapter(adapter);
int pos = 0;
//
for(int i=0;i<languages.length;i++){
if(prefs.getString(GameActivity.LANGUAGE,"").equals(languages[i])){
pos = i;
break;
}
}
language.setSelection(pos);
if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.BANGLA)){
setBangla();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ARABIC)){
setArabic();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.FRENCH)){
setFrence();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.GERMAN)){
setGerman();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ENG)){
setEnglish();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.MALAY)){
setMalay();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addtion: {
levelChooseDialog("+");
break;
}
case R.id.sub: {
levelChooseDialog("-");
break;
}
case R.id.multi: {
levelChooseDialog("X");
break;
}
case R.id.divide: {
levelChooseDialog("/");
break;
}
case R.id.quiz: {
Intent intent = new Intent(MainActivity.this, HomeScreen.class);
startActivity(intent);
}
}
}
public void levelChooseDialog(final String operator){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = View.inflate(this,R.layout.level_dialog,null);
builder.setView(view);
ListView listView = (ListView) view.findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,levels);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int level = 0;
if (position == 0){
level = 0;
}else if(position == 1){
level = 1;
}else {
level = 2;
}
startActivity(new Intent(MainActivity.this,LessonActivity.class).putExtra("level",level)
.putExtra("operator",operator));
}
});
builder.create().show();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
prefs.edit().putString(GameActivity.LANGUAGE,languages[position]).commit();
if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.BANGLA))
{
setBangla();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ARABIC)){
setArabic();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.FRENCH)){
setFrence();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.GERMAN)){
setGerman();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ENG)){
setEnglish();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.MALAY)){
setMalay();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void setBangla(){
addBtn.setText(Languages.BANGLA[0]);
subBtn.setText(Languages.BANGLA[1]);
multiBtn.setText(Languages.BANGLA[3]);
divisionBtn.setText(Languages.BANGLA[2]);
settings.setText(Languages.BANGLA[4]);
levels[0] = Languages.BANGLA[7];
levels[1] = Languages.BANGLA[8];
levels[2] = Languages.BANGLA[9];
}
public void setArabic(){
addBtn.setText(Languages.ARABIC[0]);
subBtn.setText(Languages.ARABIC[1]);
multiBtn.setText(Languages.ARABIC[3]);
divisionBtn.setText(Languages.ARABIC[2]);
settings.setText(Languages.ARABIC[4]);
levels[0] = Languages.ARABIC[7];
levels[1] = Languages.ARABIC[8];
levels[2] = Languages.ARABIC[9];
}
public void setMalay(){
addBtn.setText(Languages.MALAY[0]);
subBtn.setText(Languages.MALAY[1]);
multiBtn.setText(Languages.MALAY[3]);
divisionBtn.setText(Languages.MALAY[2]);
settings.setText(Languages.MALAY[4]);
levels[0] = Languages.MALAY[7];
levels[1] = Languages.MALAY[8];
levels[2] = Languages.MALAY[9];
}
public void setFrence(){
addBtn.setText(Languages.FRENCH[0]);
subBtn.setText(Languages.FRENCH[1]);
multiBtn.setText(Languages.FRENCH[3]);
divisionBtn.setText(Languages.FRENCH[2]);
settings.setText(Languages.FRENCH[4]);
levels[0] = Languages.FRENCH[7];
levels[1] = Languages.FRENCH[8];
levels[2] = Languages.FRENCH[9];
}
public void setGerman(){
addBtn.setText(Languages.GERMAN[0]);
subBtn.setText(Languages.GERMAN[1]);
multiBtn.setText(Languages.GERMAN[3]);
divisionBtn.setText(Languages.GERMAN[2]);
settings.setText(Languages.GERMAN[4]);
levels[0] = Languages.GERMAN[7];
levels[1] = Languages.GERMAN[8];
levels[2] = Languages.GERMAN[9];
}
public void setEnglish(){
addBtn.setText(Languages.ENGLISH[0]);
subBtn.setText(Languages.ENGLISH[1]);
multiBtn.setText(Languages.ENGLISH[3]);
divisionBtn.setText(Languages.ENGLISH[2]);
settings.setText(Languages.ENGLISH[4]);
levels[0] = Languages.ENGLISH[7];
levels[1] = Languages.ENGLISH[8];
levels[2] = Languages.ENGLISH[9];
}
}
activity_main.xml
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.littlekidsmath.yoong.mathlearningforkids.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/addtion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/add"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Addition" />
<Button
android:id="#+id/sub"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/minus"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Subtraction" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/multi"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/cancel"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Multiplication" />
<Button
android:id="#+id/divide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/division"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Division" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/quiz"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:paddingBottom="20dp"
android:paddingTop="20dp"
android:text="Quiz" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text=""
android:textColor="#color/white"
android:textSize="18sp" />
<Switch
android:id="#+id/settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="#dimen/activity_horizontal_margin"
android:text="Sound"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:text="Language" />
<Spinner
android:id="#+id/language"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:background="#color/white"
android:padding="10dp"></Spinner>
</LinearLayout>
Can anyone help please? When click on the quiz button the application will close. I want it to go to quiz page which called HomeScreen.java
looks good to me, did u declare the second activity in the manifest file? :
<activity android:name="HomeScreen"/>
If that doesn't work, use some break points and the debugger, hope it helps.

Have to decrement one value which is stored using shared preference according to the current date

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 ,....

Changing a value according to current date

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>

The Implementation of a spinners is causing my app to crash

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>

Categories

Resources