android 如何获取日期选择器 &通过单击图像按钮选择时间

发布于 2024-11-07 01:11:21 字数 20143 浏览 5 评论 0原文

主要是为 ListActivity 设置 listadapter 我使用了不同的适配器类(TaskAdapter.java),其中我重写了 getview() 并在那里编写了代码敌人复选框,文本视图和图像视图。 文本视图&复选框点击事件&检查更改工作& 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);在TaskAdapter.java类中的ImageView onClick事件中,所有其他代码都在HomeActivity中。它会给出类似快照的错误。如何在TaskAdapter.java类内实现。请给我答案。 谢谢

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

Main thing is to set listadapter for ListActivity I used differnent adapter class(TaskAdapter.java) where I override the getview() and in there i write the code foe checkbox, textview & imageview.
TextView & checkbox click events & checkedchange working & ImageViews click event also working. But problm is that i am trying to open DatePicker on click of ImageView but it shows an error below in snapshot.

my code is here,,
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 dialog only open within an activity but I am call the ((Activity) context1).showDialog(0); in TaskAdapter.java class in ImageView onClick event, and all other code is in HomeActivity. ANd it give s error like snapshot. How to achieve within TaskAdapter.java class. please give me the answer.
Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

池予 2024-11-14 01:11:21

您在 DatePicker's day 中有一个 IllegalArgumentException (阅读第二条和第四条红线以了解我是如何知道的)。第 9 条红线告诉我问题出在您的 HomeActivity.java 文件中的 第 363 行 中,它是 onCreateDialog 方法的一部分。在本例中,它显然是 DatePickerDialog 构造函数。

正如 dziobas 所说,您可能有一个基础零日漏洞,这可能就是问题所在。 mDay 也可以设置为高于该月允许的数字。您可能想要初始化 private mDay = 1 而不是保持原样。

You have an IllegalArgumentException in the DatePicker's day (read the 2nd and fourth red lines to know how I know that). The 9th red line tells me that the problem is in your HomeActivity.java file, in the line 363, which is part of the onCreateDialog method. In this case, it is clearly the DatePickerDialog constructor.

As dziobas said, it is possible that you have a base zero day, and that could be the problem. mDay could be set to a number higher that the allowed for that month also. You may want to initialize private mDay = 1 instead of leaving it as is.

小嗷兮 2024-11-14 01:11:21

月份中的某天从 1 开始,而不是从 0 开始。您必须在某个地方 mDay = 0;

Day of month starts from 1 not from 0. You must have somewhere mDay = 0;

风铃鹿 2024-11-14 01:11:21

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

and also by default the month value in the DatePickerDialog will always start from 0 so you print the value of the Month and if you get 0 you add +1

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文