The Implementation of a spinners is causing my app to crash - android

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>

Related

button not functioning?

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

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>

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

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

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

prevent result from shown unless click the button

hi i want to show the result in edittext 2 only after click the convert button
also
the second button (clear) not shown when i run the program how to show it as the screen size is small
here is the code
package converter.com;
import android.app.Activity;
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.EditText;
import android.widget.Spinner;
public class now extends Activity {
/** defining variables */
String[] currencys1,currencys2;
String e,l,f,u,d;
double EURO=5,dollar=6,franc=7,LE=1,UAE=8,txtvalue;
EditText txt1,txt2;
Button convert,clear;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt1 =(EditText)findViewById(R.id.txt1);
txt2 =(EditText)findViewById(R.id.txt2);
convert=(Button)findViewById(R.id.btn1);
clear=(Button)findViewById(R.id.clear_btn);
currencys1=getResources().getStringArray(R.array.currency);
final Spinner s1=(Spinner)findViewById(R.id.sp1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, currencys1);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
{
switch(arg2)
{
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
currencys2=getResources().getStringArray(R.array.currency1);
final Spinner s2=(Spinner)findViewById(R.id.sp2);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, currencys2);
s2.setAdapter(adapter1);
s2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
{
txtvalue = Double.parseDouble(txt1.getText().toString());
switch(arg2)
{
case 0:
final String fromCurrencyCode = s1.getSelectedItem().toString();
final String toCurrencyCode = s2.getSelectedItem().toString();
if (fromCurrencyCode.equals(toCurrencyCode)) {
txt2.setText(txt1.getText());
}
else
{
double EURO1=txtvalue*EURO;
txt2.setText(String.valueOf(EURO1));
}
break;
case 1:
final String fromCurrencyCode1 = s1.getSelectedItem().toString();
final String toCurrencyCode1 = s2.getSelectedItem().toString();
if (fromCurrencyCode1.equals(toCurrencyCode1)) {
txt2.setText(txt1.getText());
}
else
{
double LE1=txtvalue*LE;
txt2.setText(String.valueOf(LE1));
}
break;
case 2:
final String fromCurrencyCode2 = s1.getSelectedItem().toString();
final String toCurrencyCode2 = s2.getSelectedItem().toString();
if (fromCurrencyCode2.equals(toCurrencyCode2)) {
txt2.setText(txt1.getText());
}
else
{
double franc1=txtvalue*franc;
txt2.setText(String.valueOf(franc1));
}
break;
case 3:
final String fromCurrencyCode3 = s1.getSelectedItem().toString();
final String toCurrencyCode3 = s2.getSelectedItem().toString();
if (fromCurrencyCode3.equals(toCurrencyCode3)) {
txt2.setText(txt1.getText());
}
else
{
double UAE1=txtvalue*UAE;
txt2.setText(String.valueOf(UAE1));
}
break;
case 4:
final String fromCurrencyCode4 = s1.getSelectedItem().toString();
final String toCurrencyCode4 = s2.getSelectedItem().toString();
if (fromCurrencyCode4.equals(toCurrencyCode4)) {
txt2.setText(txt1.getText());
}
else
{
double dollar1=txtvalue*dollar;
txt2.setText(String.valueOf(dollar1));
}
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
convert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//i want to put the code here which show result only after click that button
}
});
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
txt2.setText(" ");
}
});
}
}
here is the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#cad1d9"
>
<TableLayout android:layout_width="match_parent" android:id="#+id/tableLayout1" android:layout_height="wrap_content">
<TextView android:id="#+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="from" android:textColor="#5c6471"></TextView>
</TableLayout>
<Spinner android:id="#+id/sp1" android:layout_height="50dip" android:layout_width="match_parent"></Spinner>
<TextView android:id="#+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Amount" android:textColor="#5c6471"></TextView>
<EditText android:text="1" android:id="#+id/txt1" android:layout_width="match_parent" android:layout_height="wrap_content" android:numeric="decimal"></EditText>
<TextView android:id="#+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="To" android:textColor="#5c6471"></TextView>
<Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/sp2"></Spinner>
<TextView android:id="#+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="value" android:textColor="#5c6471"></TextView>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/txt2" android:text="1" android:editable="false"></EditText>
<Button android:editable="false" android:width="100px" android:gravity="center" android:id="#+id/btn1" android:text="Convert" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="#string/clear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:minWidth="400px" android:id="#+id/clear_btn"></Button>
</LinearLayout>
You can do the following to hide txt2 when you first create the activity:
txt2.setVisibility(View.GONE);
Then in the click handler for the convert button:
txt2.setVisibility(View.VISIBLE);
In the click handler for the clear button, presumably you would want to make it GONE again.
Regarding the problem of the clear button being off the screen: wrap your LinearLayout in a ScrollView (making the ScrollView the top view of the hierarchy with a single LinearLayout child). That way the user can scroll down to see all the content of your layout. You need to change the height of the LinearLayout to wrap_content:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#cad1d9"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
. . .
</LinearLayout
</ScrollView>

Categories

Resources