android如何获取datepicker和; timepicker通过图像按钮单击

时间:2011-05-13 12:03:00

标签: android android-datepicker android-timepicker

ListActivity in which item contain an checkbox, textview & imagevie(alramclock). I am trying to give date n time for each task by fressing that image view.  thats shows an error like this in snapshot

主要的是为ListActivity设置listadapter我使用了不同的适配器类(TaskAdapter.java),其中我覆盖了getview()并在那里我编写了代码foe复选框,textview& ImageView的。 TextView&复选框点击活动& checkedchange工作& ImageViews点击事件也有效。但问题是我试图在点击ImageView时打开DatePicker但它在快照中显示下面的错误。

我的代码在这里, HomeActivity

package com.v3.todo;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

public class HomeActivity extends ListActivity {
    DBAdapter db;
    Cursor cr;
    CheckBox[] chk;
    static String[] valChk;
    static int Task_Id, taskId;
    static int[] idchk;
    static String Task_Nm, taskNm;
    EditText edTask;
    Button btnAdd;
    String newTask = "";
    int order;
    Calendar c = Calendar.getInstance();
    private int mYear, mMonth, mDay, mHour, mMinute;
    static final int TIME_DIALOG_ID = 1, DATE_DIALOG_ID = 0;
    String date = "", time = "", dateTime = "";
    // ArrayList al = new ArrayList();
    static ArrayList<Task> m_tasks = new ArrayList<Task>(), t_tasks = null;
    TaskAdapter m_adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.setTitle("To-Do Lists");

        btnAdd = (Button) findViewById(R.id.btnAdd);
        edTask = (EditText) findViewById(R.id.etAddTask);
        edTask.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus == true) {
                    if (edTask.getText().toString()
                            .compareTo("Add task here...") == 0) // default text
                    {
                        edTask.setText("");
                    }
                }
            }
        });

        db = new DBAdapter(HomeActivity.this);
        m_tasks = getTasks();
        if (m_tasks.size() != 0) {
            this.m_adapter = new TaskAdapter(this, R.layout.addchecktomain,
                    m_tasks);
            // lv1.setAdapter(this.m_adapter);
            System.out.println("creating");
            setListAdapter(this.m_adapter);
        } else {

            RelativeLayout rl = (RelativeLayout) findViewById(R.id.layout);
            TextView tv = new TextView(this);
            tv.setText("No To-Do Lists");
            tv.setTextSize(22);
            rl.addView(tv);
        }

        btnAdd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                newTask = edTask.getText().toString();

                String min = Integer.toString(c.get(Calendar.MINUTE));
                String hr = Integer.toString(c.get(Calendar.HOUR));
                String dd = Integer.toString(c.get(Calendar.DATE));
                String mm = Integer.toString(c.get(Calendar.MONTH));
                String yyyy = Integer.toString(c.get(Calendar.YEAR));
                if (min.length() == 1)
                    min = "0" + min;
                if (hr.length() == 1)
                    hr = "0" + hr;
                if (dd.length() == 1)
                    dd = "0" + dd;
                if (mm.length() == 1)
                    mm = "0" + mm;
                String dtCreate = mm + "-" + dd + "-" + yyyy + " " + hr + ":"
                        + min;
                if (newTask.equals("")) {
                    alertboxNeutral("Warning", "Task should not be empty!",
                            "Okay");
                }
                if (newTask.length() < 2) {
                    alertboxNeutral("Warning",
                            "Task should not be less than 2 Letters", "Okay");
                } else {
                    try {
                        db.open();
                        long id1;
                        order = db.getLastPriority();
                        if (order == 0)
                            id1 = db.insertINtask(taskNm, dtCreate, null, 0, 1);
                        else
                            id1 = db.insertINtask(taskNm, dtCreate, null, 0,
                                    order + 1);

                    } catch (Exception ex) {
                        System.out.println("Within AddTask " + ex.toString());
                    } finally {
                        db.close();
                    }
                    alertboxNeutral("Success", "Saved.", "Okay");
                }
            }
        });
    }

    // Method to fetch Uncompleted tasks from db with ID
    public ArrayList<Task> getTasks() {
        t_tasks = new ArrayList<Task>();
        try {
            db.open();
            cr = db.getUncompletedTask();
            if (cr.moveToFirst()) {
                do {
                    Task t1 = new Task();
                    String[] str = new String[2];
                    str[0] = cr.getString(0);
                    str[1] = cr.getString(1);
                    t1.setTaskID(cr.getString(0));
                    t1.setTaskName(cr.getString(1));
                    t_tasks.add(t1);
                } while (cr.moveToNext());
            }
        } catch (Exception ex) {
            System.out.println("Within Home " + ex.toString());
        } finally {
            cr.close();
            db.close();
        }

        return t_tasks;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        menu.setHeaderTitle("Task");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
        System.out.println("v.getId=" + v.getId());
        Task_Id = (Integer) v.getTag();

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                .getMenuInfo();

        switch (item.getItemId()) {
        case R.id.edit_task:
            Intent i1 = new Intent(HomeActivity.this, EditTaskActivity.class);
            i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i1);

            return true;
        case R.id.delete_task:
            // database functions
            boolean f = false;
            try {
                db.open();
                f = db.deleteTask(Task_Id);
            } catch (Exception ex) {
                System.out.println("Within Home " + ex.toString());
            } finally {
                db.close();
            }
            if (f == true)
                alertboxNeutral("Success", "Deleted.", "Okay");
            return true;
        default:
            return super.onContextItemSelected(item);
        }
    }

    public void alertboxNeutral(String title, String message, String positive) {
        AlertDialog.Builder alertbox = new AlertDialog.Builder(
                HomeActivity.this);
        if (title.equals("Warning")) {
            alertbox.setTitle(title);
            alertbox.setMessage(message);
            alertbox.setPositiveButton(positive,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Intent i = new Intent(HomeActivity.this,
                                    HomeActivity.class);
                            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(i);
                        }
                    });
            alertbox.show();
        } else if (title.equals("Success")) {
            alertbox.setTitle(title);
            alertbox.setMessage(message);
            alertbox.setPositiveButton(positive,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Intent i = new Intent(HomeActivity.this,
                                    HomeActivity.class);
                            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(i);
                        }
                    });
            alertbox.show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.add_task:
            Intent i1 = new Intent(this, AddTaskActivity.class);
            i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i1);
            break;
        case R.id.list_completed:
            Intent i2 = new Intent(this, ListCompletedActivity.class);
            i2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i2);
            break;
        case R.id.rearrange:
            Intent i3 = new Intent(this, RearrangeActivity.class);
            i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i3);
            break;
        case R.id.exit:
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            break;
        }

        return true;
    }

    /*
     * @Override protected void onPause() { // TODO Auto-generated method stub
     * super.onPause(); finish(); }
     */

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        try {
            db.open();
            m_tasks = getTasks();
        } catch (Exception ex) {
            System.out.println("Within Home " + ex.toString());
        } finally {
            db.close();
        }
        m_adapter = new TaskAdapter(this, R.layout.addchecktomain, m_tasks);

        System.out.println("notify data changed");
        // m_adapter.notifyDataSetInvalidated();
        // m_adapter.notifyDataSetChanged();
        setListAdapter(this.m_adapter);
        super.onResume();

    }

    /*
     * @Override public void onBackPressed() { // TODO Auto-generated method
     * stub db.open(); m_tasks = getTasks(); db.close();
     * System.out.println("notify data changed on back pressed");
     * m_adapter.notifyDataSetInvalidated(); m_adapter.notifyDataSetChanged();
     * super.onBackPressed(); }
     */
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            updateDisplay();
        }
    };

    private void updateDisplay() {
        // tvDt.setText(new StringBuilder().append(mMonth +
        // 1).append("-").append(mDay).append("-").append(mYear).append(" "));

    }

    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;
            updateDisplay();
        }
    };

    // updates the time we display in the TextView
    private void timeDisplay() {
        // time=(String)(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);
    }

    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 0:
            return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
                    mDay);
        }
        return null;
    }

    public static void setDate() {
        // showDialog(0);
    }
}



TaskAdapter.java
package com.v3.todo;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public final class TaskAdapter extends ArrayAdapter<Task> {
    ArrayList<Task> tasks;
    Context context1;
    CheckBox chk;
    TextView tv;
    ImageView imgAlram;
    DBAdapter db;
    static int TaskId;
    static int RId;
    Calendar c = Calendar.getInstance();
    boolean f = false;
    private int mYear, mMonth, mDay, mHour, mMinute;
    static final int TIME_DIALOG_ID = 1, DATE_DIALOG_ID = 0;
    String date = "", time = "", dateTime = "";

    public TaskAdapter(Context context, int textViewResourceId,
            ArrayList<Task> tasks) {
        super(context, textViewResourceId, tasks);
        this.tasks = tasks;
        context1 = context;
        RId = textViewResourceId;
    }

    public int getCount() {
        return tasks.size();
    }

    public Task getItem(int position) {
        return tasks.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        final int pos = position;
        final int dbid;
        View v = convertView;

        if (v == null) {
            LayoutInflater vi = (LayoutInflater) context1
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.addchecktomain, null);
        }
        Task t = tasks.get(position);
        if (t != null) {
            chk = (CheckBox) v.findViewById(R.id.cboTask);
            tv = (TextView) v.findViewById(R.id.tvTask);
            imgAlram = (ImageView) v.findViewById(R.id.imageAlram);

            if (chk != null) {
                chk.setId(Integer.parseInt(t.getTaskId()));

                chk.setText("");
                // chk.setTag(Integer.parseInt(t.getTaskId()), t.getTaskName());

                chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        int taskId = buttonView.getId();
                        if (isChecked) {
                            // /call setTaskComplete(i)
                            // / reset list view or refresh list view
                            String min = Integer.toString(c
                                    .get(Calendar.MINUTE));
                            String hr = Integer.toString(c.get(Calendar.HOUR));
                            String dd = Integer.toString(c.get(Calendar.DATE));
                            String mm = Integer.toString(c.get(Calendar.MONTH));
                            String yyyy = Integer.toString(c.get(Calendar.YEAR));
                            if (min.length() == 1)
                                min = "0" + min;
                            if (hr.length() == 1)
                                hr = "0" + hr;
                            if (dd.length() == 1)
                                dd = "0" + dd;
                            if (mm.length() == 1)
                                mm = "0" + mm;
                            String dtComplete = mm + "-" + dd + "-" + yyyy
                                    + " " + hr + ":" + min;
                            try {
                                db = new DBAdapter(context1);
                                db.open();
                                f = db.setTaskComplete(taskId, dtComplete);
                            } catch (Exception ex) {
                                System.out.println("Within Home "
                                        + ex.toString());
                            } finally {
                                db.close();
                            }
                            if (f == true) {
                                // HomeActivity.referesh = 1;
                                Intent intent = new Intent(context1,
                                        HomeActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                        | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                // HomeActivity.
                                context1.startActivity(intent);
                                Toast.makeText(context1, "Task Completed",
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                });
            }
            if (tv != null) {
                tv.setText(t.getTaskName());
                dbid = Integer.parseInt(t.getTaskId());
                tv.setTag(dbid);

                tv.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        Toast.makeText(
                                context1,
                                "You have chosen the task: " + " "
                                        + v.getTag().toString() + "  Id: "
                                        + dbid + "::" + pos, Toast.LENGTH_LONG)
                                .show();
                    }
                });
                ((Activity) context1).registerForContextMenu(tv);
            }
            if (imgAlram != null) {
                imgAlram.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // Write ur code here
                        Toast.makeText(context1, "You have chosen the Alram ",
                                Toast.LENGTH_LONG).show();
                        ((Activity) context1).showDialog(0);
                        ((Activity) context1).showDialog(TIME_DIALOG_ID);
                    }
                });
            }
        }
        return v;
    }

DatePicker对话框仅在活动中打开,但我调用((Activity)context1).showDialog(0);在ImageView onClick事件中的TaskAdapter.java类中,所有其他代码都在HomeActivity中。它会像快照一样给出错误。如何在TaskAdapter.java类中实现。请给我答案。 谢谢

3 个答案:

答案 0 :(得分:1)

从1开始,而不是从0开始。你必须有某个地方mDay = 0;

答案 1 :(得分:1)

DatePicker的日期中有 IllegalArgumentException (请阅读第2和第4条红线以了解我是如何知道的)。第9条红线告诉我问题出在你的 HomeActivity.java 文件的第363行中,这是 onCreateDialog 方法的一部分。在这种情况下,它显然是DatePickerDialog构造函数。

正如dziobas所说,有可能你有一个基本的零日,这可能是问题所在。 mDay可以设置为比该月允许的数字更高的数字。您可能希望初始化私有mDay = 1而不是保持原样。

答案 2 :(得分:1)

并且默认情况下,DatePickerDialog中的月份值始终从0开始,因此您打印月份的值,如果您得到0,则添加+1