2011-05-13 63 views
0

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機器人如何得到一個日期選擇器及時間選擇器throgh圖像按鈕點擊

主要的是設置爲listadapter我ListActivity使用可依使用適配器類(TaskAdapter.java),我重寫getview(),並在那裏我寫代碼仇敵複選框,textview & imageview。 TextView &複選框單擊事件& checkedchange工作& ImageViews click event also working。但問題是,我試圖打開DatePicker單擊ImageView,但它顯示下面的快照中的錯誤。

我的代碼是在這裏,, 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的對話框只有一個活動中開放的,但我所說的((活動)CONTEXT1).showDialog(0);在ImageView onClick事件的TaskAdapter.java類中,而其他所有代碼都在HomeActivity中。並且它提供了像快照一樣的錯誤。如何在TaskAdapter.java類中實現。請給我答案。 謝謝

+0

你能不能請你張貼聽到logcat中,因爲它不是在圖像中可見。 – Sujit

+0

http://i.stack.imgur.com/tooth.png(提示:右鍵點擊查看圖片) –

+0

請(1)發佈logcat文本而不是snapshop。閱讀它是不可能的,(2)你的代碼很長。請刪除所有非相關部分,以便更容易遵循。你會有更好的機會得到這樣的答案:) – Aleadam

回答

1

你必須在的DatePicker的天的拋出:IllegalArgumentException(讀第二和第四紅線知道我是怎麼知道的)。第9條紅線告訴我問題出在您的HomeActivity.java文件的行363,它是onCreateDialog方法的一部分。在這種情況下,它顯然是DatePickerDialog構造函數。

正如dziobas所說,有可能你的基數爲零,這可能是問題所在。可以將mDay設置爲該月允許的數字。您可能需要初始化私有mDay = 1,而不是保持原樣。

1

從一天開始,而不是從0開始。你必須有某個地方mDay = 0;

1

,並默認在DatePickerDialog當月值將始終從0開始,所以你打印一個月的價值,如果你得到0添加+1

相關問題