Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

android - Why does my app keep crashing when i try to insert a date and time picker?

I am a novice with android and coding in general. I am trying to insert an android time and date picker into my code however it keeps crashing when I attempt to do so. Can anyone please help me out

    public class NewEvent extends Activity {    

        private static int RESULT_LOAD_IMAGE = 1;

        private EventHandler handler;

        private String picturePath = "";

        private String name;
        private String place;
        private String date;
        private String time;
        private String photograph;

        DatePicker datepicker; // object for datepicker
        int year , month , day;  // declaring variables for year, month and day
        TimePicker timepicker; // object for timepicker



        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.new_event);

            handler = new EventHandler(getApplicationContext());

            //datepicker = (DatePicker) findViewById(R.id.datePicker); // Obtain datepicker attributes from layout
               //timepicker = (TimePicker) findViewById(R.id.timePicker); //Obtain timepicker attributes from layout
                timepicker.setIs24HourView(true);    //setting timepicker to 24 hr clock view
               Button button = (Button) findViewById(R.id.button1); // button to display datepicker value
                Button button1 = (Button) findViewById(R.id.button2);  // button to display timepicker value



            ImageView iv_user_photo = (ImageView) findViewById(R.id.iv_user_photo);
            iv_user_photo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(intent, RESULT_LOAD_IMAGE);              

                }
            });


            Button btn_add = (Button) findViewById(R.id.btn_add);
            btn_add.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    EditText et_name = (EditText) findViewById(R.id.et_name);
                    name = et_name.getText().toString();

                    EditText et_place = (EditText) findViewById(R.id.et_place);
                    place = et_place.getText().toString();

                    EditText et_date = (EditText) findViewById(R.id.et_date);
                    date = et_date.getText().toString();

                    EditText et_time = (EditText) findViewById(R.id.et_time);
                    time = et_time.getText().toString();

                    ImageView iv_photograph = (ImageView) findViewById(R.id.iv_user_photo);
                    photograph = picturePath;

                    Event event = new Event();
                    event.setName(name);
                    event.setPlace(place);
                    event.setDate(date);
                    event.setTime(time);
                    event.setPhotograph(photograph);

                    Boolean added = handler.addEventDetails(event);
                    if(added){
                        Intent intent = new Intent(NewEvent.this, MainEvent.class);
                        startActivity(intent);
                    }else{
                        Toast.makeText(getApplicationContext(), "Event data not added. Please try again", Toast.LENGTH_LONG).show();
                    }


                }
            });

            button.setOnClickListener(new View.OnClickListener() { 
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
    // displaying datepicker value as pop up notification
                    Toast.makeText(getBaseContext(), "Date : "
                    + (datepicker.getMonth() + 1) +"/"+datepicker.getDayOfMonth()
                            +"/"+datepicker.getYear(), Toast.LENGTH_LONG).show();            }
            });
    // On clicking button start timepicker event
            button1.setOnClickListener(new View.OnClickListener() { 
            @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
    // displaying timepicker value as pop up notification
                Toast.makeText(getBaseContext(),"Time Selected : "+timepicker.getCurrentHour()+":"
                        +timepicker.getCurrentMinute(), Toast.LENGTH_SHORT).show();
    }
            });



            }


        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
                Uri imageUri = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(imageUri,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                cursor.close();

                ImageView imageView = (ImageView) findViewById(R.id.iv_user_photo);
                imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            }
        }

    }

Here is my xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:padding="10dp">    

    <TextView
        android:id="@+id/tv_new_event_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add New Event"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_alignParentTop="true" />


    <Button
        android:id="@+id/btn_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Event"
        android:layout_alignParentBottom="true" />

    <ScrollView        
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
        android:layout_below="@id/tv_new_event_title"
        android:layout_above="@id/btn_add">
        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <ImageView 
                android:id="@+id/iv_user_photo"
                android:src="@drawable/add_user_icon"
                android:layout_width="100dp"
                android:layout_height="100dp"/>

            <TextView               
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Event:" />

            <EditText
                android:id="@+id/et_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="text" >      
                <requestFocus />
            </EditText>


             <TextView              
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Place:" />

            <EditText
                android:id="@+id/et_place"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="text" >      
                <requestFocus />
            </EditText>

             <TextView              
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Date:" />

            <EditText
                android:id="@+id/et_date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="date" />

            <Button
                android:id="@+id/button"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button" />
            <requestFocus />

            <TextView               
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Time:" />

            <EditText
                android:id="@+id/et_time"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="time" />

            <Button
                android:id="@+id/button1"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button1" />


                <requestFocus />

        </LinearLayout>
    </ScrollView>

</RelativeLayout>

Here is my LogCat:

08-25 11:57:44.144: E/AndroidRuntime(554): FATAL EXCEPTION: main
08-25 11:57:44.144: E/AndroidRuntime(554): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.chris.hockeymanagemtapp/com.chris.hockeymanagemtapp.NewEvent}: java.lang.NullPointerException
08-25 11:57:44.144: E/AndroidRuntime(554):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-25 11:57:44.144: E/AndroidRuntime(554):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-25 11:57:44.144: E/AndroidRuntime(554):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)

08-25 11:57:44.144: E/AndroidRuntime(554):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)

08-25 11:57:44.144: E/AndroidRuntime(554):  at android.os.Handler.dispatchMessage(Handler.java:99)

08-25 11:57:44.144: E/AndroidRuntime(554):  at android.os.Looper.loop(Looper.java:123)

08-25 11:57:44.144: E/AndroidRuntime(554):  at android.app.ActivityThread.main(ActivityThread.java:3683)

08-25 11:57:44.144: E/AndroidRuntime(554):  at java.lang.reflect.Method.invokeNative(Native Method)

08-25 11:57:44.144: E/AndroidRuntime(554):  at java.lang.reflect.Method.invoke(Method.java:507)

08-25 11:57:44.144: E/AndroidRuntime(554):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)

08-25 11:57:44.144: E/AndroidRuntime(554):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)

08-25 11:57:44.144: E/AndroidRuntime(554):  at dalvik.system.NativeStart.main(Native Method)

08-25 11:57:44.144: E/AndroidRuntime(554): Caused by: java.lang.NullPointerException

08-25 11:57:44.144: E/AndroidRuntime(554):  at com.chris.hockeymanagemtapp.NewEvent.onCreate(NewEvent.java:60)

08-25 11:57:44.144: E/AndroidRuntime(554):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

08-25 11:57:44.144: E/AndroidRuntime(554):  at android.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Inside your OnCreate method do this:

DatePicker dt = (DatePicker) findViewById(R.id.yourDatePickerId);

As Anuj said, you need to initialize it before using it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...