how to set text of an EditText view in multiple used fragments? - android

i am creating an app that has a tabbed interface using TabHost and fragments, and the user needs to select the time using a TimePickerDialog and the selected time is populated into an EditText view, so i moved the time picker to a fragment so i can use it in multiple tabs which works but the problem is when i set the time using the dialog EditText view that is populated is the one in the last tab not the one the TimePickerDialog was opened from, how do i deal with this?
here is the layout for time picker fragment
<RelativeLayout 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"
tools:context="com.ztech.fakecallm.TimePickerFragment">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="time"
android:ems="10"
android:id="#+id/timePicker"
android:focusable="false"
android:hint="#string/time"
android:onClick="onClickTime"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
and here is the code that populates the EditText view which is stored in MainActivity.java
public void onClickTime(View view) {
final Calendar c = Calendar.getInstance();
int cHour = c.get(Calendar.HOUR_OF_DAY);
int cMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
scheduleDate = c.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a", Locale.US);
EditText timeInput = (EditText)findViewById(R.id.timePicker);
timeInput.setText(dateFormat.format(scheduleDate));
}
}, cHour, cMinute, false);
timePickerDialog.show();
}
and here is the layout of the fragment that represents the first tab
<RelativeLayout 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"
tools:context="com.ztech.fakecallm.CallsFragment">
<fragment
android:id="#+id/contact_picker_frag"
class="com.ztech.fakecallm.ContactPickerFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_contact_picker"/>
<RadioGroup android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:id="#+id/radioGroup"
android:layout_marginTop="137dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/incoming"
android:id="#+id/incomingRadioButton"
android:checked="true"
android:layout_margin="20dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/outgoing"
android:id="#+id/outgoingRadioButton"
android:checked="false"
android:layout_margin="20dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/missed"
android:id="#+id/missedRadioButton"
android:checked="false"
android:layout_margin="20dp"/>
</RadioGroup>
<fragment
android:id="#+id/time_picker_fragment_calls"
class="com.ztech.fakecallm.TimePickerFragment"
tools:layout="#layout/fragment_time_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/radioGroup"
android:layout_alignParentStart="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/schedule"
android:id="#+id/setCallScheduleButton"
android:layout_margin="20dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
and layout for the fragment that represents the second tab
<RelativeLayout 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"
tools:context="com.ztech.fakecallm.SMSFragment">
<fragment
android:id="#+id/contact_picker_frag_sms"
class="com.ztech.fakecallm.ContactPickerFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_contact_picker"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="150dp"
android:id="#+id/message_input"
android:gravity="top"
android:hint="#string/message"
android:layout_marginTop="140dp"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:id="#+id/radioGroup"
android:layout_below="#+id/message_input"
android:layout_alignParentStart="true">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/inbox"
android:id="#+id/inbox_radio_button"
android:checked="true"
android:layout_margin="20dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sent"
android:id="#+id/sent_radio_button"
android:checked="false"
android:layout_margin="20dp"/>
</RadioGroup>
<fragment
android:id="#+id/time_picker_fragment_sms"
class="com.ztech.fakecallm.TimePickerFragment"
tools:layout="#layout/fragment_time_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/radioGroup"
android:layout_alignParentStart="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/schedule"
android:id="#+id/setSMSScheduleButton"
android:layout_margin="20dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
and after all that MainActivity looks like this
package com.ztech.fakecallm;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.provider.ContactsContract.CommonDataKinds.*;
import java.text.SimpleDateFormat;
import java.util.*;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import com.ztech.fakecallm.CallsFragment;
import com.ztech.fakecallm.SMSFragment;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private static final int PICK_CONTACT = 1001;
Date scheduleDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new CallsFragment(), "Calls");
adapter.addFragment(new SMSFragment(), "SMS");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void onClickTime(View view) {
final Calendar c = Calendar.getInstance();
int cHour = c.get(Calendar.HOUR_OF_DAY);
int cMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
scheduleDate = c.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a", Locale.US);
EditText timeInput = (EditText)findViewById(R.id.timePicker);
timeInput.setText(dateFormat.format(scheduleDate));
}
}, cHour, cMinute, false);
timePickerDialog.show();
}
public void onClickSelectContact(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
}

use this
enter link description here
dependencies {
compile 'com.wdullaer:materialdatetimepicker:2.3.0'
}
and
Implement your fragment an OnTimeSetListener
and in fragment to show TimePickerDialog
Calendar now2 = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
NewActivity.this, now2.get(Calendar.HOUR_OF_DAY), now2.get(Calendar.MINUTE),
now2.get(Calendar.SECOND), false
);
tpd.show(getFragmentManager(), "Select Time");
And
#Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
String time = "You picked the following time: "+hourOfDay+"h"+minute;
timeTextView.setText(time);
}

Related

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>

Datepicker and TimePicker dialogs take two clickes of button

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

How do i Get the DatePicker to pop up when TextViewItem is Clicked

I am new to Eclipse and running Juno. I hit the wall developing a mobile app when i was trying to implement a date picker on a text item. I have read similar questions from stackoverflow and applied the answers but it doesn't seem to work for me. I keep making changes and I am totally lost. I tried adding the calender widget but its bigger than the screen so i just want to display a view with the calender for selection instead.
I need my users to be able to select a date for which they wish to travel and when search button is clicked, the entries from the form is used to display a list of available buses they can book. Please find my codes below, No help is too little.
SEARCHBUS_ACTIVITY.JAVA
package com.joel.mybusapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.FragmentActivity;
public class SearchBusActivity extends ActionBarActivity {
private Spinner fromSpinner, toSpinner;
private Button searchBusButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_bus);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addListenerOnFromSpinnerItemSelection();
addListenerOnToSpinnerItemSelection();
}
public void addListenerOnFromSpinnerItemSelection() {
fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
fromSpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnToSpinnerItemSelection() {
toSpinner = (Spinner) findViewById(R.id.toSpinner);
toSpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
TextView textViewDatePicker = (TextView) findViewById(R.id.textDateView);
textViewDatePicker.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(SearchBusActivity.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
private void updateLabel() {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
textViewDatePicker.setText(sdf.format(myCalendar.getTime()));
}
public void addListenerOnButton() {
fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
toSpinner = (Spinner) findViewById(R.id.toSpinner);
searchBusButton = (Button) findViewById(R.id.searchBusButton);
searchBusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(SearchBusActivity.this,
"OnClickListener : " +
"\nOrigin : "+ String.valueOf(fromSpinner.getSelectedItem()) +
"\nDestination : "+ String.valueOf(toSpinner.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_bus, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ACTIVITY_SEARCH_BUS.XML
<RelativeLayout 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: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.joel.mybusapp.SearchBusActivity" >
<TextView
android:id="#+id/depatureTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="24dp"
android:text="#string/departure"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#E81919"
android:textStyle="bold" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/depatureTextView"
android:layout_marginStart="20dp"
android:layout_marginTop="5dp" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fromTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#DCD9D9"
android:text="#string/from"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#E81919"
android:textStyle="bold" />
<Spinner
android:id="#+id/fromSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:entries="#array/from_arrays"
android:prompt="#string/origin_prompt" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/toTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#DCD9D9"
android:text="#string/to"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#E81919"
android:textStyle="bold" />
<Spinner
android:id="#+id/toSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/to_arrays"
android:prompt="#string/destination_prompt" />
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#DCD9D9"
android:text="#string/date"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#E81919"
android:textStyle="bold" />
<TextView
android:id="#+id/textDateView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
style="#android:style/Widget.DeviceDefault.Light.Spinner"/>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/passengersTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#DCD9D9"
android:text="#string/passengers"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#E81919"
android:textStyle="bold" />
<Spinner
android:id="#+id/passengerSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/passenger_arrays"
android:prompt="#string/passenger_prompt" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tableLayout1"
android:layout_centerInParent="true"
android:layout_marginStart="14dp"
android:orientation="vertical" >
<Button
android:id="#+id/searchBusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/searchbusbtn" />
</LinearLayout>
</RelativeLayout>
SCREENSHOT
Step 1
Create onClickListener for ur textview
Step 2
in onClickListener use my code which i have used for datepickerdialog
inOnClick method
setDate();
setDate method:
public void setDate() {
new DatePickerDialog(add_task_frag.this, d,
calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
calender.get(Calendar.DAY_OF_MONTH)).show();
}
DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
calender.set(Calendar.YEAR, year);
calender.set(Calendar.MONTH, month);
calender.set(Calendar.DAY_OF_MONTH, day);
updatedate();
}
};
updatedate() method:
public void updatedate() {
textview.setText(format.format(calender.getTime()));
}

Categories

Resources