How to use DatePickerDialog in BaseAdapter
-
17-04-2021 - |
Domanda
I am working with the BaseAdapter
Class. I want to Display DatePickerDialog
in it.
When I use showDialog(DATE_DIALOG_ID);
I am getting error.
Please guide me regarding this.
package com.OrganisemeePhone.adapter;
import java.util.ArrayList;
import java.util.Vector;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class TaskFilterAdapter extends BaseAdapter {
String date, month, year,setdueDate;
//int dateFormat;
DatePickerDialog.OnDateSetListener dateListener;
int myYear, myMonth, myDay;
int dateFormat;
int starcount=0;
public TaskFilterAdapter datedialog;
viewholder holder;
LayoutInflater inflator;
ArrayList<Integer> taskId = new ArrayList<Integer>();
ArrayList<String> task = new ArrayList<String>();
ArrayList<String> dueDate = new ArrayList<String>();
ArrayList<Integer> priority = new ArrayList<Integer>();
static final int DATE_DIALOG_ID = 0;
Vector<Boolean> VectorCheckChange = new Vector<Boolean>();
Vector<Object> taskrow = new Vector<Object>();
static int pos;
Context context;
private boolean isdaymonth;
public TaskFilterAdapter(Context context,ArrayList<Integer> taskId, ArrayList<String> task, ArrayList<Integer> priority, ArrayList<String> duedate) {
super();
inflator = LayoutInflater.from(context);
this.taskId = taskId;
this.context=context;
this.task = task;
this.dueDate = duedate;
this.priority = priority;
//dateFormat=LoginActivity.db.getdateformat();
getDateFormate();
dateFormat=LoginActivity.db.getdateformat();
getDateFormate();
for(int i=0; i<task.size(); i++)
{
VectorCheckChange.add(false);
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return task.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
holder = new viewholder();
convertView = inflator.inflate(R.layout.task_row, null);
holder.task = (TextView)convertView.findViewById(R.id.task_row_text);
holder.date = (TextView)convertView.findViewById(R.id.task_row_date_text);
holder.star = (ImageView)convertView.findViewById(R.id.task_row_star);
holder.chk = (CheckBox)convertView.findViewById(R.id.task_row_check_box);
holder.task.setOnClickListener(new Clicker());
holder.chk.setOnCheckedChangeListener(new Checker());
holder.star.setOnClickListener(new Clicker());
holder.date.setOnClickListener(new Clicker());
setviewAsSettings();
setviewAsSettings();
convertView.setTag(holder);
}
else
{
holder=(viewholder)convertView.getTag();
}
pos = position;
/****************** Set Task *************************/
holder.task.setText(task.get(position));
holder.task.setTag(position);
holder.star.setTag(position);
holder.date.setTag(position);
/***************** Set Duedate ***********************/
setdueDate = dueDate.get(position);
month = setdueDate.substring(5, 7);
date = setdueDate.substring(8, 10);
if (!date.equals("00"))
{
if (isdaymonth)
if (isdaymonth)
{
holder.date.setText(date + "." + month + ".");
Log.d("taskList Adapter"," date formate day month ");
}
else
{
holder.date.setText(month + "." + date + ".");
Log.d("taskList Adapter"," date formate month day");
}
}
else
{
holder.date.setText("");
}
/***************** Set Priority ***********************/
if (priority.get(position).equals(-1) || priority.get(position).equals(0)|| priority.get(position).equals(3))
{
holder.star.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.star_low));
}
else if (priority.get(position).equals(2))
{
holder.star.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.star_med));
}
else if (priority.get(position).equals(1))
{
holder.star.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.star_high));
}
/******************* Set tag in checkBox ******************************/
holder.chk.setTag(position);
if(VectorCheckChange.get(position))
{
holder.chk.setChecked(true);
holder.task.setPaintFlags(holder.task.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.task.setTextColor(Color.parseColor("#848484"));
holder.date.setPaintFlags(holder.task.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.date.setTextColor(Color.parseColor("#848484"));
holder.task.setClickable(false);
holder.task.setEnabled(false);
}
else
{
holder.chk.setChecked(false);
holder.task.setPaintFlags(holder.task.getPaintFlags() & ~ Paint.STRIKE_THRU_TEXT_FLAG);
holder.task.setTextColor(Color.parseColor("#000000"));
holder.date.setPaintFlags(holder.task.getPaintFlags() & ~ Paint.STRIKE_THRU_TEXT_FLAG);
holder.date.setTextColor(Color.parseColor("#000000"));
holder.task.setClickable(true);
holder.task.setEnabled(true);
}
return convertView;
}
// updates by nilesh
public void setviewAsSettings(){
//check for task setting
SharedPreferences startup_pref =
PreferenceManager.getDefaultSharedPreferences(context);
Boolean viewpriority=startup_pref.getBoolean("viewpriority", true);
Boolean viewduedate=startup_pref.getBoolean("viewduedate", true);
if(!viewpriority){
holder.star.setVisibility(View.INVISIBLE);
}
if(!viewduedate){
holder.date.setVisibility(View.INVISIBLE);
}
//check for task setting completed
}
public class viewholder
{
TextView task,date;
ImageView star;
CheckBox chk;
}
public class Clicker implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position=(Integer)v.getTag();
int setPriority = 0;
if(v.getId() == holder.date.getId())
{
Log.i("Date Dialog Picker", "Click Date..................... ");
((Activity)context).showDialog(DATE_DIALOG_ID);
//.showDialog(DATE_DIALOG_ID);
//.showDialog(DATE_DIALOG_ID);
}
dateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int yr, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myYear = yr;
myMonth = monthOfYear;
myDay = dayOfMonth;
}
};
if(v.getId() == holder.task.getId())
{
Intent display_int= new Intent(context, DisplyTaskActivity.class);
display_int.putExtra(constantcode.TASK_ID,taskId.get(position));
v.getContext().startActivity(display_int);
Log.i("TaskList Adapter", "Task ....position...... "+holder.star.getTag());
}
if(v.getId() == holder.star.getId())
{
if (priority.get(position).equals(-1) || priority.get(position).equals(0) || priority.get(position).equals(3))
{
priority.set(position, 2);
setPriority = 2;
holder.star.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.star_low));
Log.d("TaskList Adapter", "----- Grey ----");
}
else if (priority.get(position).equals(2))
{
priority.set(position, 1);
setPriority = 1;
holder.star.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.star_med));
Log.d("TaskList Adapter", "----- Yellow ----");
}
else if (priority.get(position).equals(1))
{
priority.set(position, 0);
setPriority = 0;
holder.star.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.star_high));
Log.d("TaskList Adapter", "----- Orange ----");
}
String updateQuery = "update tbl_tasks set priority =" + setPriority + " where taskId="+ taskId.get(position);
LoginActivity.db.execNonQuery(updateQuery);
taskrow = LoginActivity.db.getTaskRow(taskId.get(position));
if(taskrow.get(2).toString().contains("'"))
{
taskrow.set(2, taskrow.get(2).toString().replace("'", "''"));
}
String insertQuery = "insert into tbl_update_tasks(taskId,listId,description,priority,dueDate,reminderId,senderId,receiverId,taskCategoryType,fadeDate,assignedId)values("+ taskrow.get(0) + ","+ taskrow.get(1)+ ",'"+ taskrow.get(2)+ "',"+ taskrow.get(3)+ ",'"+ taskrow.get(4)+ "',"+ taskrow.get(5)+ ","+ taskrow.get(6)+ ","+ taskrow.get(7)+ ",'"+ taskrow.get(8)+ "','"+ taskrow.get(9)+ "',"+ taskrow.get(10)+ ");";
LoginActivity.db.execNonQuery(insertQuery);
notifyDataSetChanged();
}
//Log.w("taskfilterAdapter","position....... "+v.getTag());
}
}
Dialog onCreateDialog(int id){
switch(id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this.context, dateListener, myYear, myMonth,myDay);
}
return null;
}
/* public class datedialogclicker extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
holder.date.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("New Class....", "Click OnClick.....");
showDialog(DATE_DIALOG_ID);
}
});
dateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int yr, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myYear = yr;
myMonth = monthOfYear;
myDay = dayOfMonth;
}
};
}
protected Dialog onCreateDialog(int id){
switch(id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(context, dateListener, myYear, myMonth,myDay);
}
return null;
}
}*/
public class Checker implements OnCheckedChangeListener
{
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int posi=(Integer)buttonView.getTag();
if(isChecked)
{
VectorCheckChange.set(posi, true);
}
else
{
VectorCheckChange.set(posi, false);
}
notifyDataSetChanged();
}
}
// update by nilesh
public void getDateFormate() {
// Get the app's shared preferences
SharedPreferences startup_pref = PreferenceManager
.getDefaultSharedPreferences(context);
// Get the value for the run counter
isdaymonth = startup_pref.getBoolean(constantcode.ISDAYMONTH, true);
}
}
Soluzione
(1)Define this code in BaseAdapter onClick
((Activity)AdapterName.this.context).showDialog(DATE_DIALOG_ID);
(2)below code in Activity:
DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int yr, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myYear = yr;
myMonth = monthOfYear;
myDay = dayOfMonth;
}
};
Calendar cal = Calendar.getInstance();
myYear = cal.get(Calendar.YEAR);
myMonth = cal.get(Calendar.MONTH);
myDay = cal.get(Calendar.DAY_OF_MONTH);
protected Dialog onCreateDialog(int id){
switch(id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(ActivityName.this, dateListener, myYear, myMonth, myDay);
}
return null;
}
Altri suggerimenti
The error is easy to justify: it is not exception it is compilation error - showDialog is a method of Activity class. It is so easy for the Android developers to forget that all these nice auxiliary methods should also be provided by some class right?
So the thing is that OnClickListener
is not Activity
. Make constructor of the class accepting single parameter activity, store it in local variable and then call its method showDialog:
private Activity activity;
public Clicker(Activity activity) {
this.activity = activity;
}
...
this.activity.showDialog();
...
I faced the problem of storing value of datepicker in the listview but resolved it.This is the code for it.Hope it helps.
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
public class DAteDemo extends Activity{
private ListView listViewScore = null;
private ListViewAdapter listViewAdapter = null;
static final int DATE_DIALOG_ID = 0;
private int mYear;
private int mMonth;
private int mDay;
int globalPosition; //used for storing the position of textview clicked for setting the date
ArrayList<String> mfddateList = null;
int viewlength = 30;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewScore=(ListView)findViewById(R.id.listViewScore);
mfddateList = new ArrayList<String>();
for(int i=0;i<30;i++){
mfddateList.add("");
}
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
listViewAdapter = new ListViewAdapter();
listViewScore.setAdapter(listViewAdapter);
}
class ListViewAdapter extends BaseAdapter{
@Override
public int getCount() {
return viewlength;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder viewHolder ;
View rowView=view;
if(rowView==null){
LayoutInflater layoutinflate =LayoutInflater.from(DAteDemo.this);
rowView=layoutinflate.inflate(R.layout.listviewnewtext, parent, false);
viewHolder = new ViewHolder();
viewHolder.et_Sort_Order = (TextView)rowView.findViewById(R.id.et_Sort_Order);
//Setting listen to the text box
viewHolder.et_Sort_Order.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
globalPosition = viewHolder.ref; // this is used to update the date
Log.i("Log","date:-- "+viewHolder.ref);
}
});
rowView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.ref = position;
viewHolder.et_Sort_Order.setText(mfddateList.get(position));
return rowView;
}
}//class ends
class ViewHolder{
TextView et_Sort_Order;
int ref;
}
// the callback received when the user "sets" the date in the dialog
public DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
String date = (mMonth + 1)+"/"+mYear;
mfddateList.set(globalPosition,date);
Log.i("Log", "i m in dateset "+globalPosition);
listViewAdapter.notifyDataSetChanged(); //for updating the date change
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(DAteDemo.this,mDateSetListener,mYear, mMonth,mDay );
}
return null;
}
}//ActivityEnds
**main.xml**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="match_parent"
android:id="@+id/listViewScore"
android:cacheColorHint="#00000000"
android:layout_height="match_parent"
android:layout_weight="1.00"
android:divider="#C0C0C0"
android:layout_below="@+id/layout"
android:dividerHeight="2dip"
android:background="@android:color/white" />
**listviewnewtext.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="2dip"
android:paddingBottom="0dip"
>
<TextView
android:textColor="@android:color/black"
android:layout_height="wrap_content"
android:layout_width="80dip"
android:focusable="false"
android:id="@+id/et_Sort_Order"
>
</TextView>
</LinearLayout>