How to create notifications based on user selected data in Android - android

I have problems on how to make this functional. I have tested many codes now for this layout but it wont work. This is the layout i made wherein:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout2"
android:layout_marginLeft="30dp"
android:layout_marginTop="60dp"
android:padding="10dp"
android:background="#f7a29d">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Goal Name:"
android:id="#+id/tt"
android:layout_alignBottom="#+id/linearLayout2"
android:layout_alignParentStart="true"
android:textColor="#000000"
android:paddingBottom="5dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/goal_name"
android:textColor="#000000"
android:padding="10dp"
android:background="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Start Date:"
android:id="#+id/textView24"
android:textColor="#000000"
android:paddingTop="5dp"
android:paddingBottom="5dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/sdate"
android:textColor="#000000"
android:padding="10dp"
android:background="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="End Date:"
android:id="#+id/tt2"
android:textColor="#000000"
android:paddingTop="5dp"
android:paddingBottom="5dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/edate"
android:textColor="#000000"
android:padding="10dp"
android:background="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="NOTIFICATIONS OPTIONS"
android:id="#+id/textView25"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Time:"
android:id="#+id/textView35"
android:layout_row="2"
android:layout_column="0"
android:textColor="#000000" />
<GridLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_row="19"
android:layout_column="0">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="ShowTime"
android:id="#+id/showtime"
android:layout_row="1"
android:layout_column="0"
android:textColor="#000000"
android:layout_marginLeft="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Time"
android:id="#+id/settime"
android:layout_row="1"
android:layout_column="1"
android:layout_marginLeft="5dp" />
<TimePicker
android:id="#+id/timePicker"
android:layout_width="1dp"
android:layout_height="1dp"
android:visibility="invisible"/>
</GridLayout>
<GridLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Repeat:"
android:id="#+id/textView26"
android:layout_below="#+id/linearLayout2"
android:layout_row="0"
android:layout_column="0"
android:textColor="#000000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="ShowRepeat"
android:id="#+id/showRepeat"
android:layout_row="2"
android:layout_column="0"
android:textColor="#000000"
android:background="#ffffff"
android:padding="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Repetition Option:"
android:id="#+id/textView28"
android:layout_row="3"
android:layout_column="0"
android:textColor="#000000" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="#+id/toggleButton"
android:layout_row="2"
android:layout_column="1"
android:textColor="#000000"
android:background="#9bd8ea" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="set"
android:id="#+id/setRepetition"
android:layout_row="4"
android:layout_column="0"
android:textColor="#000000"
android:background="#3a738a" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Sound Option:"
android:id="#+id/textView30"
android:layout_row="7"
android:layout_column="0"
android:textColor="#000000" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="#+id/toggleButton2"
android:layout_row="8"
android:layout_column="0"
android:textColor="#000000"
android:background="#9bd8ea" />
</GridLayout>
</LinearLayout>
It look like this:
Goal Name: (data already given)
Start Date: (data already given)
End Date: (data already given)
Notifications Options
Time:
showTime [Set] -> time picker pop up
Repeat:
showRepeat [Toggle Button] -> chose if to repeat notifications once or not
Repetition Option:
[Set] -> Alert Dialog pop with choices and choices made is print in showRepeat TextView
Sound:
[Toggle Button] -> chose to notify with sound or not
SetNotifyActivity.java
package com.citu.goalsettingorganizer;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.app.Dialog;
import android.app.Activity;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;
import java.util.Calendar;
public class SetNotifyActivity extends AppCompatActivity {
private TextView goalname,startdate,enddate,showrepeat;
private TextView showTime;
private TimePicker timePicker;
private Button setTime,setRepeat;
private int hour;
private int minute;
private String format;
static final int TIME_PICKER_DIALOG_ID = 100;
MyDBAdapter dbhandler;
public int goal_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_notify);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
goalname = (TextView)findViewById(R.id.goal_name);
startdate = (TextView)findViewById(R.id.sdate);
enddate = (TextView)findViewById(R.id.edate);
showrepeat = (TextView)findViewById(R.id.showRepeat);
showTime = (TextView) findViewById(R.id.showtime);
setTime = (Button)findViewById(R.id.settime);
timePicker = (TimePicker)findViewById(R.id.timePicker);
setRepeat = (Button)findViewById(R.id.setRepetition);
goal_id = Integer.parseInt(extras.getString("goalid"));
//Create database
dbhandler = new MyDBAdapter(this);
displayDetails();
displayTime();
changeTimeButton();
selectRepeat();
}
public void displayDetails(){
List<Goals> oneGoal = dbhandler.getLatestGoal(goal_id);
for (final Goals goals : oneGoal) {
goalname.setText(goals.getGoalName());
startdate.setText(goals.getSMonth() + "/" + goals.getSDay() + "/" + goals.getSYear());
enddate.setText(goals.getEMonth() + "/" + goals.getEDay() + "/" + goals.getEYear());
}
}
public void displayTime(){
final Calendar getTime = Calendar.getInstance();
hour = getTime.get(Calendar.HOUR_OF_DAY);
minute = getTime.get(Calendar.MINUTE);
// set current time into textview
showTime(hour,minute);
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
public void changeTimeButton(){
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_PICKER_DIALOG_ID);
}
});
}
public void showTime(int hour, int min) {
if (hour == 0) {
hour += 12;
format = "AM";
}
else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
showTime.setText(new StringBuilder().append(pad(hour)).append(" : ").append(pad(min))
.append(" ").append(format));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
// set current time into textview
showTime(hour,minute);
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
};
// On clicking repeat type button
public void selectRepeat(){
setRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(SetNotifyActivity.this);
final EditText number = new EditText(SetNotifyActivity.this);
alert.setMessage("Enter a Number:");
alert.setTitle("");
alert.setView(number);
alert.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String tempnumber = number.getText().toString();
final CharSequence[] items = {"Hours","Days", "Weeks", "Months"};
AlertDialog.Builder builder = new AlertDialog.Builder(SetNotifyActivity.this);
builder.setTitle("Select Period:");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
showrepeat.setText(tempnumber+" "+items[item]);
dialog.dismiss();
}
}).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
alert.create().show();
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_PICKER_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
public void done(){
Intent myIntent = new Intent(SetNotifyActivity.this, MainMenuActivity.class);
startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_set_notify, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_done) {
done();
return true;
}
return super.onOptionsItemSelected(item);
}
}
My problem is when the user finish setting his notifications, i cant make it work. The notifications will work based on what he/she choose. I cant seem to find any sources that i could understand easily for this.
i have deleted the codes i tested to make notifications work so that it doesnt look messy. It doesnt work anyway-

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>

Code to Delete row from given customized listview using alertbox displayed when checkbox is checked in android programming

This is my code below
1) This is Class with getter and setter methods + extension of base adapter
package virtual.mall;
import java.util.List;
import virtual.mall.Salt_page_ada.saltlist_holder;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
class Order1_cls {
String o1_it_name,o1_it_count;
int o1_it_cost,o1_it_qty;
Boolean o1isselect=false;
public Order1_cls(String o1_it_name,String o1_it_count,int o1_it_qty,int o1_it_cost){
super();
this.o1_it_name = o1_it_name;
this.o1_it_count=o1_it_count;
this.o1_it_qty=o1_it_qty;
this.o1_it_cost = o1_it_cost;
this.o1isselect=o1isselect;
}
public String getO1_it_name() {
return o1_it_name;
}
public void setO1_it_name(String o1_it_name) {
this.o1_it_name = o1_it_name;
}
public String getO1_it_count() {
return o1_it_count;
}
public void setO1_it_count(String o1_it_count) {
this.o1_it_count = o1_it_count;
}
public int getO1_it_cost() {
return o1_it_cost;
}
public void setO1_it_cost(int o1_it_cost) {
this.o1_it_cost = o1_it_cost;
}
public int getO1_it_qty() {
return o1_it_qty;
}
public void setO1_it_qty(int o1_it_qty) {
this.o1_it_qty = o1_it_qty;
}
public Boolean getO1isselect() {
return o1isselect;
}
public void setO1isselect(Boolean o1isselect) {
this.o1isselect = o1isselect;
}
}
public class Order1_page extends ArrayAdapter<Order1_cls> {
private List <Order1_cls> order1list;
private Context context;
public Order1_page(List<Order1_cls> order1list, Context context) {
super(context, R.layout.order1listref,order1list);
this.order1list=order1list;
this.context=context;
}
public static class Order1list_holder{
public TextView o1_name;
public TextView o1_count;
public TextView o1_qty;
public TextView o1_cost;
public CheckBox o1chkbx;
}
public View getView(int pos,View con_view,ViewGroup parent){
View v=con_view;
Order1list_holder hold=new Order1list_holder();
if(con_view==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.order1listref,null);
hold.o1_name=(TextView)v.findViewById(R.id.o1_tv_name);
hold.o1_count=(TextView)v.findViewById(R.id.o1_tv_count);
hold.o1_qty=(TextView)v.findViewById(R.id.o1_tv_qty);
hold.o1_cost=(TextView)v.findViewById(R.id.o1_tv_cost);
hold.o1chkbx=(CheckBox)v.findViewById(R.id.o1_cBox);
hold.o1chkbx.setOnCheckedChangeListener((Order1class) context);
}
else{
hold=(Order1list_holder)v.getTag();
}
Order1_cls o1= order1list.get(pos);
//hold.o1_name.setText(o1.getO1_it_name());
hold.o1_count.setText(o1.getO1_it_count());
hold.o1_qty.setText(" "+o1.getO1_it_qty());
hold.o1_cost.setText(" " + o1.getO1_it_cost());
hold.o1chkbx.setChecked(o1.o1isselect);
hold.o1chkbx.setTag(o1);
return v;
}
}
2) This is code for main class extending the activity with handlers
i have written the code for deletion below but it shows an exceptio
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
public class Order1class extends Activity implements android.widget.CompoundButton.OnCheckedChangeListener {
ListView lv;
ArrayList<Order1_cls> order1list; //class name in ref java file
Order1_page o1adapter; // ref xml name
ArrayList<Integer> positionslist;
ImageButton addc,delbtn;
protected Object posi;
final Context context = this;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order1pageclass);
positionslist=new ArrayList<Integer>();
lv=(ListView)findViewById(R.id.order1class_listv); //listview id in main layout
disp_ord1list();
}
private void disp_ord1list() {
// TODO Auto-generated method stub
order1list =new ArrayList<Order1_cls>();
order1list.add(new Order1_cls("Rice(basmati)","1kg packet",3,450));
order1list.add(new Order1_cls("Lentils(finegrade)","2kg packet",2,500));
order1list.add(new Order1_cls("Colgate","5kg packet",3,60));
order1list.add(new Order1_cls("cereal","1kg packet",3,60));
order1list.add(new Order1_cls("surfexcel","2kg packet",2,40));
order1list.add(new Order1_cls("vim","200gms Bar",1,25));
order1list.add(new Order1_cls("Flour","5kg packet",1,300));
o1adapter=new Order1_page(order1list,this);
lv.setAdapter(o1adapter);
}
#Override
public void onCheckedChanged(CompoundButton but_view, boolean o1isselected) {
// TODO Auto-generated method stub
int posi=lv.getPositionForView(but_view);
if(posi !=ListView.INVALID_POSITION){
Order1_cls o1=order1list.get(posi);
o1.setO1isselect(o1isselected);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("remove item ??");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to delete")
.setCancelable(false)
.setPositiveButton("Delete",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
for(int position : positionslist){
order1list.remove(position);
} o1adapter.notifyDataSetChanged();
}
})
.setNegativeButton("add",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// Toast.makeText(this,"CLICKED ON " + o1.getO1_it_name()+"of count "+ o1.getO1_it_count()+"cost is "+o1.getO1_it_cost(),Toast.LENGTH_SHORT).show();
}
}
3) order1pageclass.xml file for actual page layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#58ACFA"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order-1 27/3/15"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25dp" />
</LinearLayout>
<ListView
android:id="#+id/order1class_listv"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_above="#+id/lay1"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1"
android:background="#FAFAFA" >
</ListView>
<LinearLayout
android:id="#+id/lay1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:background="#58ACFA"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/menu_btn"
android:background="#58ACFA" />
<ImageButton
android:id="#+id/imageButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.65"
android:src="#drawable/home_btn"
android:background="#58ACFA"
/>
<ImageButton
android:id="#+id/imageButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/cart_btn"
android:background="#58ACFA" />
</LinearLayout>
</RelativeLayout>
4) reference page layout (how each row should look or what it must have )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/o1_tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:text="Rice(Basmati)"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/o1_cBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:layout_marginRight="36dp"
android:text="+ Cart" />
<TextView
android:id="#+id/o1_tv_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/o1_tv_name"
android:layout_below="#+id/o1_tv_name"
android:layout_margin="5dp"
android:text="5kg Pack"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
<TextView
android:id="#+id/o1_tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/o1_tv_count"
android:layout_alignBottom="#+id/o1_tv_count"
android:layout_margin="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="28dp"
android:layout_toLeftOf="#+id/o1_cBox"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
<TextView
android:id="#+id/tvqty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/o1_tv_qty"
android:layout_alignBottom="#+id/o1_tv_qty"
android:layout_margin="5dp"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/o1_tv_name"
android:text="Qty :"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
<TextView
android:id="#+id/o1_tv_cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/o1_tv_qty"
android:layout_alignBottom="#+id/o1_tv_qty"
android:layout_alignRight="#+id/o1_cBox"
android:layout_margin="5dp"
android:text="450 "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
</RelativeLayout>
In your onCheckedChanged() method save the positions in a list. and when button is clicked iterate through the list and delete them from the adapter list.

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