how to show current date in edit text view - android

THIS MY CODE
package com.clip.android;
/**
*
* #author abhishek
*
*/
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
public class ClaimRegister extends ClaimActivity implements OnClickListener{
EditText polid;
/*DatePicker claimDate;*/
String userValue;
String getClaimDate;
Spinner Spinner;
String clmType;
ImageButton calIcon;
EditText claimDate;
/*TextView b1;*/
double a = 4.32;
double b = Math.pow(10.0,8.0);
int year,day,month;
List<String> claimTypes=new ArrayList<String>();
/* List<Customer> customers = new ArrayList<Customer>();*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_claim_register);
setHeader("Register Your Claim", true, true);
claimDate = (EditText)findViewById(R.id.editText1);
polid = (EditText)findViewById(R.id.polid);
/*claimDate = (DatePicker)findViewById(R.id.dp);*/
Spinner=(Spinner) findViewById(R.id.spin);
userValue = polid.getText().toString();
calIcon = (ImageButton)findViewById(R.id.imageButton1);
calIcon.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
/*claimDate.setMinDate((long)(c.getTimeInMillis()-(a*b)));
claimDate.init(year, month, day, null);*/
claimDate.setText(String.valueOf(c.getTimeInMillis()-(a*b)));
DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth)
{
Calendar cl = Calendar.getInstance();
cl.set(year, monthOfYear, dayOfMonth-1);
if(cl.before(Calendar.getInstance())){
claimDate.setText(dayOfMonth+"-"+(monthOfYear)+"-"+year);
}else {
claimDate.setText("");
Toast.makeText(ClaimRegister.this, "Date Shold Be Within Current Date.", Toast.LENGTH_SHORT).show();
return;
}
year = year;
month = monthOfYear;
day = dayOfMonth;
}
}, year, month, day;
((Dialog) datePickerListener).show();
}
});
AsyncCall drop = new AsyncCall();
drop.execute();
}
private class AsyncCall extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
Log.d("doBack", "0000");
claimTypes = com.clip.webservice.GetAQuote.GetLineofBusiness("CLMTYPE", "getClmType");
return null;
}
protected void onPostExecute(Void result)
{
Log.d("onPost", "lol");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ClaimRegister.this, android.R.layout.simple_spinner_dropdown_item,claimTypes);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("onPost", "123");
Spinner.setAdapter(adapter);
Log.d("onPost", "hiiii");
Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), "type = "+ item, Toast.LENGTH_LONG).show();
clmType= Spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
String item=parent.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), "type = "+ item, Toast.LENGTH_LONG).show();
clmType= Spinner.getSelectedItem().toString();
}
});
}
}
public void submit(View view)
{
userValue = polid.getText().toString();
if(userValue.trim().equals("")&& userValue != null){
Toast.makeText(this, "Policy Id is required", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(this,ClaimRegisterPage.class);
intent.putExtra("getclmType", clmType);
intent.putExtra("userValue", userValue);
Log.d("In submit", "userValue = "+userValue);
startActivity(intent);
}
}
}
ERROR:-
04-26 11:45:04.450: E/AndroidRuntime(2813): FATAL EXCEPTION: main
04-26 11:45:04.450: E/AndroidRuntime(2813): Process: com.clip.android, PID: 2813
04-26 11:45:04.450: E/AndroidRuntime(2813): java.lang.ClassCastException: com.clip.android.ClaimRegister$1$1 cannot be cast to android.app.Dialog
04-26 11:45:04.450: E/AndroidRuntime(2813): at com.clip.android.ClaimRegister$1.onClick(ClaimRegister.java:96)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.view.View.performClick(View.java:5198)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.view.View$PerformClick.run(View.java:21147)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.os.Handler.handleCallback(Handler.java:739)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.os.Handler.dispatchMessage(Handler.java:95)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.os.Looper.loop(Looper.java:148)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.app.ActivityThread.main(ActivityThread.java:5417)
04-26 11:45:04.450: E/AndroidRuntime(2813): at java.lang.reflect.Method.invoke(Native Method)
04-26 11:45:04.450: E/AndroidRuntime(2813): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-26 11:45:04.450: E/AndroidRuntime(2813): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
What Set current date as default date and i want to allow user 15 days behind from current date not below than that date.Please help to resolve this.

DatePickerDialog is a Dialog But DatePickerDialog.OnDateSetListener is not a Dailog that can be cast. So show DatePickerDialog instead of showing datePickerListener. It's the line of error
((Dialog) datePickerListener).show();
See the example how DatePickerDialog is created and used.

//Current date
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
// editText is the EditText that should display it
editText.setText(currentDateTimeString);
For 15 days limit, you can use if else condition before setting the date to edit text.So if user Selects date before 15 days the edit text remains empty

There are couple of errors that I've noticed in the code,
1) Replace
calIcon.setOnClickListener(new Button.OnClickListener()
with
calIcon.setOnClickListener(new View.OnClickListener()
2) Below type-casting is causing the crash
((Dialog) datePickerListener).show();
You should create an instance of Dialog, build it with require attributes and set the listener. Then call the show() method on it. Refer, Datepicker: How to popup datepicker when click on button and store value in variable

Resolved Code
package com.clip.android;
/**
*
* #author abhishek
*
*/
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
public class ClaimRegister extends ClaimActivity implements OnClickListener{
EditText polid;
String userValue;
String getClaimDate;
Spinner Spinner;
String clmType;
ImageButton calIcon;
EditText claimDate;
double a = 1.296;
double b = Math.pow(10.0,9.0);
static final int DATE_PICKER_ID = 0;
int year,day,month;
List<String> claimTypes=new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_claim_register);
setHeader("Register Your Claim", true, true);
claimDate = (EditText)findViewById(R.id.editText1);
polid = (EditText)findViewById(R.id.polid);
Spinner=(Spinner) findViewById(R.id.spin);
userValue = polid.getText().toString();
calIcon = (ImageButton)findViewById(R.id.imageButton1);
claimDate.setEnabled(false);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
claimDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(day).append("-").append(month + 1).append("-")
.append(year).append(" "));
calIcon.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
AsyncCall drop = new AsyncCall();
drop.execute();
}
private class AsyncCall extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
Log.d("doBack", "0000");
claimTypes = com.clip.webservice.GetAQuote.GetLineofBusiness("CLMTYPE", "getClmType");
return null;
}
protected void onPostExecute(Void result)
{
Log.d("onPost", "lol");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ClaimRegister.this, android.R.layout.simple_spinner_dropdown_item,claimTypes);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("onPost", "123");
Spinner.setAdapter(adapter);
Log.d("onPost", "hiiii");
Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), "type = "+ item, Toast.LENGTH_LONG).show();
clmType= Spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
String item=parent.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), "type = "+ item, Toast.LENGTH_LONG).show();
clmType= Spinner.getSelectedItem().toString();
}
});
}
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
//disabled the dates lesser than 15 days from current date onload of date picker dialog
DatePickerDialog dp = new DatePickerDialog(this, pickerListener, year, month,day);
Calendar c = Calendar.getInstance();
dp.getDatePicker().setMinDate(((long)(c.getTimeInMillis()-(a*b))));
return dp;
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
claimDate.setText(new StringBuilder().append(day)
.append("-").append(month + 1).append("-").append(year)
.append(" "));
}
};
public void submit(View view)
{
userValue = polid.getText().toString();
//Validation for Policy Id since it's mandatory
if(userValue.trim().equals("")&& userValue != null){
Toast.makeText(this, "Policy Id is required", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(this,ClaimRegisterPage.class);
intent.putExtra("getclmType", clmType);
intent.putExtra("userValue", userValue);
Log.d("In submit", "userValue = "+userValue);
startActivity(intent);
}
}
}

Related

NullPoint when start Activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have 1 problem and Who can help me?.
I have 1 Activity run when start App
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.Serializable;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
Button btnLogin, btnRegister, btnFindPassword;
EditText editUsername, editPassword;
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
btnLogin = (Button) findViewById(R.id.button_login);
btnRegister = (Button) findViewById(R.id.button_register);
btnFindPassword = (Button) findViewById(R.id.button_findPassword);
editUsername = (EditText) findViewById(R.id.editText_username);
editPassword = (EditText) findViewById(R.id.editText_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarActivity);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Đăng nhập");
Login();
Register();
FindPassword();
}
public void Login(){
btnLogin.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = db.getDataTableUser();
int temp = 1;
if (res.getCount() == 0) {
showMessage("Error", "Tài khoản không tồn tại");
return;
}
while (res.moveToNext()) {
String username, password, idUser;
idUser = res.getString(0);
username = res.getString(1);
password = res.getString(2);
if (editUsername.getText().toString().equals(username) == true&&editPassword.getText().toString().equals(password) == true) {
doOpenManagePage(idUser);
temp = 0;
break;
}
}
if (temp==1){
showMessage("Error", "Account does not exist");
}
}
}
);
}
public void Register(){
btnRegister.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenRegister();
}
}
);
}
public void FindPassword(){
btnFindPassword.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenFindPasswordStep1();
}
}
);
}
public void doOpenRegister(){
Intent newIntent = new Intent(this, Register.class);
startActivity(newIntent);
}
public void doOpenFindPasswordStep1(){
Intent newIntent = new Intent(this, FindPasswordStep1.class);
startActivity(newIntent);
}
public void doOpenManagePage(String idUser){
Intent newIntent = new Intent(this, ManagePage.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.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.menu_manage_page, 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_logout) {
return true;
}
else if (id==R.id.action_search){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then it send IdUser to this Activity
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class ManagePage extends AppCompatActivity{
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_page);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_note);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doOpenInsertNote(idUser);
}
});
}
public String getIdUser(){
Bundle extras = getIntent().getExtras();
String idUser = extras.getString("IdUser");
return idUser;
}
public void doOpenInsertNote(String idUser){
Intent newIntent = new Intent(this, InsertNote.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
}
When i run it 1st time, this app is ok, it can go to next Activity
package com.example.khuatduytan.doantotnghiep;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
public class InsertNote extends AppCompatActivity implements View.OnClickListener {
private ImageButton insertDate;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et, content_InsertNote, money_InsertNote;
private Button btnSubmitNote, btnCancelNote;
private Spinner SelectTypeNote;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
insertDate = (ImageButton) findViewById(R.id.dateInsert);
cal = Calendar.getInstance();
et = (EditText) findViewById(R.id.dateInsert_editText);
btnSubmitNote = (Button) findViewById(R.id.insertNote);
btnCancelNote = (Button) findViewById(R.id.cancelNote);
content_InsertNote = (EditText) findViewById(R.id.noiDung);
money_InsertNote = (EditText) findViewById(R.id.soTien);
SelectTypeNote = (Spinner) findViewById(R.id.loai);
db = new DatabaseHelper(this);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
insertDate.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
setBtnSubmitNote(idUser);
setBtnCancelNote();
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / " + selectedYear);
}
};
private void setBtnSubmitNote(final String idUser){
btnSubmitNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmDialog(idUser);
}
});
}
private void setBtnCancelNote(){
Intent newIntent = new Intent(this, ManagePage.class);
startActivity(newIntent);
}
private void confirmDialog(final String idUser) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String date = null, content = null, money = null, TypeNote_Selected;
int Type_Note = 0, id_User;
id_User = Integer.parseInt(idUser);
date = et.getText().toString();
content = content_InsertNote.getText().toString();
money = money_InsertNote.getText().toString();
TypeNote_Selected = SelectTypeNote.getSelectedItem().toString();
if(TypeNote_Selected.equals("Thu")){
Type_Note = 0;
} else{
Type_Note = 1;
}
if(date.equals("")||content.equals("")||money.equals("")){
Toast.makeText(InsertNote.this, "Bạn chưa nhập đủ dữ liệu", Toast.LENGTH_LONG).show();
}
else {
long isInserted = db.insertNoteTable(date, content, Type_Note, money, id_User);
if (isInserted == -1) {
Toast.makeText(InsertNote.this, "Thêm ghi chú không thành công", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(InsertNote.this, "Thêm ghi chú thành công", Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.show();
}
}
`
But when i run it second time, When i click button to open Activity
InsertNote, I receive a error
03-26 16:12:32.161 2614-2614/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khuatduytan.doantotnghiep/com.example.khuatduytan.doantotnghiep.ManagePage}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.khuatduytan.doantotnghiep.ManagePage.onCreate(ManagePage.java:21)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
at android.app.ActivityThread.access$600(ActivityThread.java:141) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5041) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
at dalvik.system.NativeStart.main(Native Method) 
I tried to print what i send from Activity Main to Activity ManagePage by Toast, it display exactly what i want to send.
But i dont know why this error display.
Can you help me?
Sorry about my English
You call setBtnCancelNote() method in the onCreate() method of your InsertNote activity. so as soon as InsertNote starts it tries to launch the ManagePage activity.
The problem is your ManagePage activity expects the value IdUser in the bundle received from the intent. But you do not pass this value to ManagePage activity when you start it from InsertNote activity.
You probably want to add this line to your setBtncancelNote() method in InsertPage activity -
newIntent.putExtra("IdUser", //The Values here);
If you pass this value then ManageNote will not crash.
please add more info like line numbers, otherwise its difficult to debug it remotely ..
Anyway, my guess is you have to check for null pointers when you do stuff like getIntent().getExtras()
just put some breakpoints there, and step by step and you'll figure it out

Getting data from a DatePickerDialog to a fragment

As above I am trying to work out how to pass back the date selected by the user. I have worked out how to get the date selected by using the onDateSet method but I do not know how to feed this back to the parent fragment, and then set the EditText text to the date selected.
package com.example.androidvehicle;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class fragmentServicing extends Fragment {
callBack mCallBack;
Button mot;
Button servicing;
Button tax;
EditText txtService;
final int Date_Dialog_ID=0;
int cDay,cMonth,cYear; // this is the instances of the current date
Calendar cDate;
int sDay,sMonth,sYear; // this is the instances of the entered date
int id_dialog = 1;
int yr, day, month = 0;
// interfacing back to activity
public interface callBack
{
public void onItemSelected(String id);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_servicing, container, false);
txtService = (EditText) view.findViewById(R.id.txtServiceDate);
mot = (Button) view.findViewById(R.id.buttonMOT);
servicing = (Button) view.findViewById(R.id.buttonService);
servicing.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// this will then pass back to the activity the string hello
mCallBack.onItemSelected("hello");
getActivity().showDialog(1);
}
});
mot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().showDialog(1);
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallBack = (callBack) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
// this is an override for when the dialog is created
protected Dialog onCreateDialog(int id)
{
switch(id)
{
// this will return a date picker dialog if 1 is passed
// could use another number for another dialog
case 1:
// passes it the current date
return new DatePickerDialog(getActivity(), mDateSetListener, yr, month, day);
}
return null;
}
// this returns the date back that has been selected by the user
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
yr = year;
month = monthOfYear;
day = dayOfMonth;
Log.d("date selected", "year "+ yr+ " month " +month+" day "+day);
}
};
}
You can set DateListner on Edittext onClicklistner..
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
public class DateListener implements OnClickListener, OnDateSetListener {
private Activity activity;
private int year;
private int monthOfYear;
private int dayOfMonth;
private View touchedView;
public DateListener(Activity activity) {
this.activity = activity;
final Calendar c = Calendar.getInstance();
this.year = c.get(Calendar.YEAR);
this.monthOfYear = c.get(Calendar.MONTH);
this.dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
}
public int getYear() {
return year;
}
public int getMonth() {
return monthOfYear;
}
public int getDay() {
return dayOfMonth;
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
this.year = year;
this.monthOfYear = monthOfYear + 1;
this.dayOfMonth = dayOfMonth;
updateDisplay();
updateEditText();
}
#Override
public void onClick(View v) {
touchedView = v;
new DatePickerDialog(activity,
this, this.getYear(), this.getMonth(), this.getDay()).show();
}
private void updateDisplay() {
((TextView) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(monthOfYear)).append(".")
.append(pad(year)));
}
private void updateEditText() {
((EditText) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(monthOfYear)).append(".")
.append(pad(year)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}
In Your Fragment
DateListener dateListener = new DateListener(getActivity());
edittext.setOnClickListener(dateListener);

on tab change in same page, 2nd time OnCreate() doesn't work

All the functions are running properly, but only one problem exists that if i record details for a day, and if I switch tab to the history tab to see the new record, the viewlist in the history class should display that record. However the viewlist doesnot display the lastest record, and i check the database, the lastest record has been written into database. The only way to see the new record is to close the emulator and restart it.
I found the problem that on startup, the recorder and history tab would both be initialised in OnCreate() method. But after that when I switch between these two tabs, it would not be initialised. Therefore, in the history.class, it would not open the database and read the data. That's the problem. Could somebody please help me, thanks
tab Prototype class
package com.example.tabpro;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class TabBar extends TabActivity{
static TabHost tabHost=null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost = getTabHost();
Intent recorderIntent = new Intent(TabBar.this, Recorder.class);
TabSpec recorderTabSpec = tabHost.newTabSpec("tab1");
recorderTabSpec.setIndicator("Recorder");
recorderTabSpec.setContent(recorderIntent);
tabHost.addTab(recorderTabSpec);
Intent historyIntent = new Intent(TabBar.this,History.class);
TabSpec historyTabSpec = tabHost.newTabSpec("tab2");
historyTabSpec.setIndicator("History");
historyTabSpec.setContent(historyIntent);
tabHost.addTab(historyTabSpec);
tabHost.setCurrentTab(0);
}
public void switchTab(int tab)
{
tabHost.setCurrentTab(tab);
}
}
Recorder.class
package com.example.tabpro;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class Recorder extends Activity implements OnSeekBarChangeListener {
int mYear;
int mMonth;
int mDay;
TextView dateDisplay;
Button pickDateButton;
TextView sbHourValue;
TextView sbMinValue;
int hours;
int mins;
static final int DATE_DIALOG_ID = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recorder);
initialDatePicker();
initialSeekBar();
initialSaveButton();
}
public void initialDatePicker()
{
dateDisplay = (TextView)findViewById(R.id.dateDisplay);
pickDateButton = (Button)findViewById(R.id.pickDate);
pickDateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar currentDate = Calendar.getInstance();
mYear = currentDate.get(Calendar.YEAR);
mMonth = currentDate.get(Calendar.MONTH);
mDay = currentDate.get(Calendar.DAY_OF_MONTH);
dateDisplay.setText(new StringBuilder()
.append(mYear).append("-")
.append(mMonth + 1).append("-")
.append(mDay));
}
public DatePickerDialog.OnDateSetListener mDateSetListener = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
dateDisplay.setText(new StringBuilder()
.append(mYear).append("-")
.append(mMonth + 1).append("-")//start from 0
.append(mDay));
}
};
protected Dialog onCreateDialog(int id){
switch(id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
}
return null;
}
public void initialSeekBar()
{
SeekBar sbHour = (SeekBar)findViewById(R.id.seekBar_hour);
sbHour.setMax(23);
sbHour.setProgress(0);
sbHour.setOnSeekBarChangeListener(this);
sbHourValue = (TextView)findViewById(R.id.textView_hour);
sbHourValue.setText("0"+ " hour(s)");
SeekBar sbMin = (SeekBar)findViewById(R.id.seekBar_min);
sbMin.setMax(59);
sbMin.setProgress(0);
sbMin.setOnSeekBarChangeListener(this);
sbMinValue = (TextView)findViewById(R.id.TextView_min);
sbMinValue.setText("0" + " minute(s)");
}
public void initialSaveButton()
{
Button saveButton = (Button)findViewById(R.id.button_save);
saveButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String time;
String date;
date = dateDisplay.getText().toString();
time = hours + " hour(s) " + mins + " minute(s)";
TabProDB db;
db = new TabProDB(Recorder.this);
db.open();
boolean findSameDay = false;
Cursor c = db.GetAllRecords();
if(c!=null)
{
if (c.moveToFirst())
{
do {
String dateToCompare = c.getString(c.getColumnIndex(TabProDB.KEY_DATE));
if(dateToCompare.equalsIgnoreCase(date))
{
findSameDay = true;
}
} while (c.moveToNext());
}
}
if(findSameDay!=true)
{
long id = db.insertRecord(date, time);
db.close();
Toast.makeText(Recorder.this, "Record Saved" , Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Recorder.this, "You have already recorded the today: " + date, Toast.LENGTH_SHORT).show();
db.close();
}
switchTabInActivity(1);
}
});
}
public void switchTabInActivity(int index)
{
TabBar parentActivity;
parentActivity = (TabBar)this.getParent();
parentActivity.switchTab(index);
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
if(arg0.getId() == R.id.seekBar_hour){
// update hour value
hours = arg1;
sbHourValue.setText(Integer.toString(arg1)+" hour(s)");
}
else{
// update minute value
mins = arg1;
sbMinValue.setText(Integer.toString(arg1)+" minute(s)");
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
History.class
package com.example.tabpro;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class History extends Activity implements OnItemClickListener {
int getdbID;
String Date;
String Time;
ListView date_time_ListView;
ArrayList<String> listItems = null;
ArrayAdapter arrayAdapter = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
date_time_ListView = (ListView) findViewById(R.id.listView1);
TabProDB db = new TabProDB(this);
try{
listItems = new ArrayList<String>();
db.open();
Cursor c = db.GetAllRecords();
if(c!=null)
{
if (c.moveToFirst())
{
do{
String date1 = c.getString(c.getColumnIndex(TabProDB.KEY_DATE) );
String time1 = c.getString(c.getColumnIndex(TabProDB.KEY_TIME) );
String date_time1 = date1 + "\n" +time1;
listItems.add(date_time1);
}while (c.moveToNext());
}
}
db.close();
}catch (Exception e) {}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems );
date_time_ListView.setAdapter(arrayAdapter);
date_time_ListView.setOnItemClickListener(this);
date_time_ListView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder ad = new AlertDialog.Builder(History.this);
ad.setTitle("Delete?");
ad.setMessage("Are you sure you want to delete this record?");
final int positionToRemove = position;
String selectedFromList = (date_time_ListView.getItemAtPosition(position).toString());
String[] splitDateTime = selectedFromList.split("\n");
final String splitDate = splitDateTime[0];
Toast.makeText(History.this, splitDate, Toast.LENGTH_SHORT).show();
String splitTime = splitDateTime[1];
ad.setNegativeButton("Cancel", null);
ad.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
TabProDB db = new TabProDB(History.this);
try
{
db.open();
Cursor c = db.GetAllRecords();
if(c!=null)
{
if(c.moveToFirst())
{
do
{
//search database to find a date that equals the date on the listview
String findDate = c.getString(c.getColumnIndex(TabProDB.KEY_DATE));
if(splitDate.equalsIgnoreCase(findDate))
{
getdbID =c.getInt(c.getColumnIndex(TabProDB.KEY_ROWID));
db.deleteRow(getdbID);
break;
}
else
{
}
}while(c.moveToNext());
}
}
}
catch(Exception e){}
db.close();
listItems.remove(positionToRemove);
arrayAdapter.notifyDataSetChanged();
}
});
ad.show();
return false;
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(History.this, Update.class);
String str1[] = ((TextView) view).getText().toString().split("\n");
String str2 = str1[0];
String str3 = str1[1];
i.putExtra("date", str2);
i.putExtra("time", str3);
i.putExtra("position", position);
startActivity(i);
}
}
final Intent i = new Intent().setClass(TabBar.this,
Recorder.class);
TabSpec spec1 = tabHost.newTabSpec("Recoder");
spec1.setContent(i);
spec1.setIndicator(getResources().getString(R.string.title_card_post1),
getResources().getDrawable(R.drawable.tab1));
final Intent i = new Intent().setClass(TabBar.this,
History.class);
TabSpec spec1 = tabHost.newTabSpec("History");
spec1.setContent(i);
spec1.setIndicator(getResources().getString(R.string.title_card_post1),
getResources().getDrawable(R.drawable.tab1));
tabHost.addTab(spec1);
tabHost.addTab(spec2);
Try this code and let me know whether this works for you because this solution is working for me and one of my application does have it.

app ends while clicking datepicker button

My program contains a button named date to show calendar view. but app ends while clicking it. pls give me a solution.My program contains a button named date to show calendar view. but app ends while clicking it. pls give me a solution.
FirstActivity.java
package example.showevent1;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.os.Bundle;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.*;
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.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
public class FirstActivity extends FragmentActivity implements OnItemSelectedListener, OnDateSetListener {
/** Called when the activity is first created. */
private static final String DATE_FORMAT = "yyyy-MM-dd";
classdbOpenHelper eventsData;
TextView userSelection;
Button okButton;
Button date1;
public EditText date;
private Calendar mCalendar;
private static final String[] items = { "Yalahanka", "Rajai nagar", "Sivaji Nagar", "Koramangala", "RT Nagar", "Banashankari", "Yashwanthpura", "Hebbal" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
okButton = (Button) findViewById(R.id.button2);
date1 = (Button) findViewById(R.id.button1);
userSelection = (TextView) findViewById(R.id.textView1);
Spinner my_spin = (Spinner) findViewById(R.id.spinner1);// data1
my_spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
my_spin.setAdapter(aa);
okButton.setOnClickListener(new clicker());
eventsData = new classdbOpenHelper(this);
date1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePicker();
}
});
}
static final String YEAR = "year";
static final String MONTH = "month";
static final String DAY = "day";
static final String HOUR = "hour";
static final String MINS = "mins";
static final String CALENDAR = "calendar";
private void showDatePicker() {
Object ft = getFragmentManager().beginTransaction();
DatePickerDialogFragment newFragment = new DatePickerDialogFragment();
Bundle args = new Bundle();
args.putInt(YEAR, mCalendar.get(Calendar.YEAR));
args.putInt(MONTH, mCalendar.get(Calendar.MONTH));
args.putInt(DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
newFragment.setArguments(args);
newFragment.show((FragmentManager) ft, "datePicker");
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
userSelection.setText(items[pos]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
userSelection.setText("");
}
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String datevalue = date1.getText().toString();
String Userselectvalue = userSelection.getText().toString();
SQLiteDatabase db = eventsData.getWritableDatabase();
ContentValues cv = new ContentValues();
// cv.put(classdbOpenHelper.KEY_COUNTED,
// metersave.getText().toString());
cv.put(classdbOpenHelper.KEY_DESC, Userselectvalue);
cv.put(classdbOpenHelper.KEY_DATE, datevalue);
db.insert(classdbOpenHelper.DATABASE_TABLE, null, cv);
}
public void onDestroy() {
eventsData.close();
}
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateButtons();
}
private void updateButtons() {
// Set the date button text
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
date1.setText(dateForButton);
}
}
DatePickerDialogFragment.java
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.*;
public class DatePickerDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
Fragment editFragment = getFragmentManager().findFragmentByTag(FirstActivity.ACCESSIBILITY_SERVICE);
OnDateSetListener listener = (OnDateSetListener) editFragment;
return new DatePickerDialog(getActivity(), listener,
args.getInt(FirstActivity.YEAR),
args.getInt(FirstActivity.MONTH),
args.getInt(FirstActivity.DAY));
}
}
You are getting a Nullpointer because you never actually initialize the Calendar object:
mCalendar

android-Intent and OnClickListener

Brand new to android and facing a weird problem.Check out the code below
FirstActivity.java:
package experiment.on.it;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FirstActivity extends Activity implements Button.OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button timeDatePicker = (Button) findViewById(R.id.timeDatePickerBtn);
Button customSpinner = (Button) findViewById(R.id.spinnerBtn);
timeDatePicker.setOnClickListener(this);
customSpinner.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.timeDatePickerBtn:
startActivity(new Intent(this, TimeDatePicker.class));
case R.id.spinnerBtn:
startActivity(new Intent(this, CustomSpinner.class));
}
}
}
As I/you expected that by clicking on the two buttons i.e.
timeDatePicker
customSpinner
a new Activity will starts (TimeDatePicker and CustomSpinner respectively).
Our expectation is correct. But the problem i'm facing that when i click on the timeDatePicker the second activity (CustomSpinner) starts. But if i press the emulator's back button (i.e. the device back button) the first activity(TimeDatePicker) appears. I cant find any keyword to describe this kind of problem. So writing this boring question. Any help will be greatly appreciated from a beginner.(...And i think the answer will be pretty easy and small, which i couldnt get. :-P) The Activities code are given below.
TimeDatePicker.java:
package experiment.on.it;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimeDatePicker extends Activity {
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
private TextView mTimeDisplay;
private Button mPickTime;
private int mhour;
private int mminute;
static final int TIME_DIALOG_ID = 3;
static final int DATE_DIALOG_ID = 2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timedatepicker);
mDateDisplay = (TextView) findViewById(R.id.date);
mPickDate = (Button) findViewById(R.id.datepicker);
mTimeDisplay = (TextView) findViewById(R.id.time);
mPickTime = (Button) findViewById(R.id.timepicker);
// Pick time's click event listener
mPickTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(TIME_DIALOG_ID);
}
});
// PickDate's click event listener
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mhour = c.get(Calendar.HOUR_OF_DAY);
mminute = c.get(Calendar.MINUTE);
}
// -------------------------------------------update
// date----------------------------------------//
private void updateDate() {
mDateDisplay.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("/").append(mMonth + 1).append("/")
.append(mYear).append(" "));
showDialog(TIME_DIALOG_ID);
}
// -------------------------------------------update
// time----------------------------------------//
public void updatetime() {
mTimeDisplay.setText(new StringBuilder().append(pad(mhour)).append(":")
.append(pad(mminute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
// Datepicker dialog generation
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
// Timepicker dialog generation
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mhour = hourOfDay;
mminute = minute;
updatetime();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this, mTimeSetListener, mhour, mminute,
true);
}
return null;
}
}
CustomSpinner.java:
package experiment.on.it;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class CustomSpinner extends Activity {
String[] items = { "this", "is", "a", "really", "really2", "really3",
"really4", "really5", "silly", "list" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.spinnerlayout);
Spinner spin =(Spinner)findViewById(R.id.sPinner);
ArrayAdapter adapter = new ArrayAdapter(this,R.layout.radio,R.id.txt,items);
spin.setAdapter(adapter);
}
}
The problem can be solved putting break in every case of the switch
public void onClick(View v) {
switch (v.getId()) {
case R.id.timeDatePickerBtn:
startActivity(new Intent(this, TimeDatePicker.class));
break;
case R.id.spinnerBtn:
startActivity(new Intent(this, CustomSpinner.class));
break;
}
}
try this.
You are missing break; statement in your switch case block.
So, thought the first activity starts and is in your backstack, it is immediately pushed down by the second one due to the missing break and the back button behaves as it should and return you to the the first one.
I think, you missed 'break' in switch~case.
You're missing break in your switch case, along with default. Since your switch case is taking the value of the spinner class, when you end the spinner class by pressing back button, the time-date picker class pops up.

Categories

Resources