Search code examples
androidandroid-imageviewpopupwindowlayout-inflaterandroid-datepicker

How to show date picker in popup window that popped from an imagebutton


I am building application in which I need this complex mechanism. Please help me out. When I click on the imagebutton it should show a popup window. In this popup window I've kept two editTexts. I've set both editTexts to OnclickListener. Now when i click on edittext, it should show DatePicker and finally when I set the date on datepicker, it should be set on those editTexts.

I don't have any idea how to do this. Reading some tutorials I've made my java code look like:

package com.addictioncounterapp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;

public class AddictionDetails extends Activity 
{
TextView tv_addiction_name, tv_today, tv_yesterday, tv_this_week, tv_this_month, tv_total;
ImageView iv_back, iv_filter;
int year, month, day;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addiction_details);

    tv_addiction_name = (TextView) findViewById(R.id.textViewAddictionDetails);
    tv_total = (TextView) findViewById(R.id.textview_total);
    tv_today = (TextView) findViewById(R.id.textview_today);
    tv_yesterday = (TextView) findViewById(R.id.textview_yesterday);
    tv_this_week = (TextView) findViewById(R.id.textview_this_week);
    tv_this_month = (TextView) findViewById(R.id.textview_this_month);

    iv_back = (ImageView) findViewById(R.id.imageViewAddictionDetailsBack);
    iv_back.setClickable(true);
    iv_back.setOnClickListener(new OnClickListener()
                                    {
                                        @Override
                                        public void onClick(View v)
                                        {
                                            Intent intent = new Intent(AddictionDetails.this, StartActivity.class);
                                            startActivity(intent);
                                        }
                                    }
                                );
    iv_filter = (ImageView) findViewById(R.id.imageViewAddictionDetailsFilter);
    iv_filter.setClickable(true);
    iv_filter.setOnClickListener(new OnClickListener()
                                    {
                                        @Override
                                        public void onClick(View v)
                                        {
                                            LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                                            View popupView = layoutInflater.inflate(R.layout.activity_filter_addiction_form, null);
                                            final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                                            final EditText etStartDate = (EditText)popupView.findViewById(R.id.editTextFilterStartDate);
                                            etStartDate.setOnClickListener(new OnClickListener()
                                                                                {   
                                                                                    @Override
                                                                                    public void onClick(View v)
                                                                                    {
                                                                                        final int DATE_DIALOG_ID = 1;
                                                                                        showDialog(DATE_DIALOG_ID);
                                                                                        protected Dialog onCreateDialog(int id)
                                                                                        {
                                                                                                switch(id)
                                                                                                {
                                                                                                    case DATE_DIALOG_ID:
                                                                                                        return new DatePickerDialog(this, dateListener, year, month, day);
                                                                                                }
                                                                                                return null;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            );

                                            final Calendar cal = Calendar.getInstance();
                                            year = cal.get(Calendar.YEAR);
                                            month = cal.get(Calendar.MONTH);
                                            day = cal.get(Calendar.DAY_OF_MONTH);

                                            etStartDate.setText(new StringBuilder().append(day).append('/').append(month + 1).append('/').append(year));

                                            DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener()
                                                                                                    {
                                                                                                        @Override
                                                                                                        public void onDateSet(DatePicker view, int yr, int monthOfYear, int dayOfMonth)
                                                                                                        {
                                                                                                            year = yr;
                                                                                                            month = monthOfYear;
                                                                                                            day = dayOfMonth;
                                                                                                            etStartDate.setText(new StringBuilder().append(day).append('/').append(month + 1).append('/').append(year));
                                                                                                        }
                                                                                                };



                                            EditText etEndDate = (EditText)popupView.findViewById(R.id.editTextFilterEndDate);
                                            etEndDate.setOnClickListener(new OnClickListener()
                                                                                {   
                                                                                    @Override
                                                                                    public void onClick(View v)
                                                                                    {

                                                                                    }
                                                                                }
                                                                        );


                                            ImageView iv_ok = (ImageView) popupView.findViewById(R.id.imageViewOk);
                                            iv_ok.setClickable(true);
                                            iv_ok.setOnClickListener(new ImageView.OnClickListener()
                                                                        {
                                                                             @Override
                                                                             public void onClick(View v)
                                                                             {

                                                                             }
                                                                         }
                                                                    );

                                            ImageView iv_cancel = (ImageView) popupView.findViewById(R.id.imageViewCancel);
                                            iv_cancel.setClickable(true);
                                            iv_cancel.setOnClickListener(new ImageView.OnClickListener()
                                                                            {
                                                                                 @Override
                                                                                 public void onClick(View v)
                                                                                 {
                                                                                     popupWindow.dismiss();
                                                                                 }
                                                                             }
                                                                        );

                                        }
                                    }
                                );

    Intent intent = getIntent();
    String cat_name = intent.getStringExtra("cat_name");

    tv_addiction_name.setText(cat_name);

    SQLiteDatabase db = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.OPEN_READWRITE, null);

    Cursor cursor = db.query("category", new String[]{"cat_id"}, "cat_name=?", new String[]{cat_name}, null, null, null);

    //----------------------fetching id-------------------

    int cat_id = 0;
    if(cursor.getCount() > 0)
        while(cursor.moveToNext())
            cat_id = cursor.getInt(0);
    cursor.close();

    //----------------------fetching total-------------------

    int total;
    cursor = db.query("counter", new String[]{"cat_id"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
    total = cursor.getCount();
    tv_total.setText(total+"");

    //----------------------fetching today's count---------------

    cursor = db.query("counter", new String[]{"counter_entry_date"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);

    Calendar cal1 = Calendar.getInstance();
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");

    String todays_date = dateFormat1.format(cal1.getTime());
    String cursor_date;
    int counter = 0;
    if(cursor.getCount() > 0)
    {
        while(cursor.moveToNext())
        {
            cursor_date = cursor.getString(0)+"";
            if(cursor_date.equals(todays_date))
                counter++;
        }
    }
    tv_today.setText(counter+"");

    //----------------------fetching yesterdays count------------------

    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy");
    cal2.add(Calendar.DATE, -1);

    String yesterdays_date = dateFormat2.format(cal2.getTime());

    counter = 0;
    cursor.moveToFirst();
    if(cursor.getCount() > 0)
    {
        while(cursor.moveToNext())
        {
            cursor_date = cursor.getString(0)+"";
            if(cursor_date.equals(yesterdays_date))
                counter++;
        }
    }
    tv_yesterday.setText(counter+"");

    //-------------------------fetching current week count--------------------

    ArrayList<String> current_week_dates = new ArrayList<String>();

    Calendar c = Calendar.getInstance();
    c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    for (int i = 0; i < 7; i++)
    {
        current_week_dates.add(df.format(c.getTime()));
        c.add(Calendar.DATE, 1);
    }

    counter=0;
    cursor.moveToFirst();
    while(cursor.moveToNext())
    {
        if(current_week_dates.contains(cursor.getString(0)))
        {
            counter++;
        }
    }
    tv_this_week.setText(counter+"");

    //----------------------fetching current month count--------------------

    cursor.moveToFirst();
    counter=0;

    Date date = new Date();
    SimpleDateFormat sdf;

    sdf = new SimpleDateFormat("MM/yyyy");
    String current_month= sdf.format(date);

//      Toast.makeText(getBaseContext(), current_month, Toast.LENGTH_SHORT).show();

    while(cursor.moveToNext())
    {
        if((cursor.getString(0)).matches("(.*)"+current_month))
        {
            counter++;
        }
    }
//      Toast.makeText(getBaseContext(), counter+"", Toast.LENGTH_SHORT).show();

    tv_this_month.setText(counter+"");
    cursor.close();
}
}

This is my main xml file which contains imageview, from where popup is to be shown :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/black_red_texture" >

<ImageView
    android:id="@+id/imageViewAddictionDetailsBack"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/arrow_left"
    android:clickable="true" />

<TextView
    android:id="@+id/textViewAddictionDetails"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/imageView1"
    android:layout_centerHorizontal="true"
    android:text="Addiction Details"
    android:textSize="20sp" />

<TableLayout
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="false"
    android:layout_below="@id/textViewAddictionDetails"
    android:layout_centerHorizontal="true"
    android:background="#20ffffff"
    android:shrinkColumns="1" >

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:textColor="#ffffff"
            android:text="Today:" />

        <TextView
            android:textColor="#ffffff"
            android:id="@+id/textview_today"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:text="today" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp" >

        <TextView
            android:textColor="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="Yesterday:" />

        <TextView
            android:textColor="#ffffff"
            android:id="@+id/textview_yesterday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:text="yesterday" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp" >

        <TextView
            android:textColor="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="This Week:" />

        <TextView
            android:textColor="#ffffff"
            android:id="@+id/textview_this_week"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:text="this week" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp" >

        <TextView
            android:textColor="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="This Month:" />

        <TextView
            android:textColor="#ffffff"
            android:id="@+id/textview_this_month"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:text="this month" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingTop="10dp" >

        <TextView
            android:textColor="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="Total:" />

        <TextView
            android:textColor="#ffffff"
            android:id="@+id/textview_total"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:text="total" />
    </TableRow>

</TableLayout>

<ImageView
    android:id="@+id/imageViewAddictionDetailsFilter"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/filter" />

</RelativeLayout>

This is my popup layout xml code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#20000000"
    android:orientation="vertical" >

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="right"
                android:text="Start Date : "
                android:textColor="#ffffff" />

            <EditText
                android:id="@+id/editTextFilterStartDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_weight="1"
                android:hint="Select start date"
                android:clickable="true"
                android:focusableInTouchMode="false" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="right"
                android:text="End Date : "
                android:textColor="#ffffff" />

            <EditText
                android:id="@+id/editTextFilterEndDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_weight="1"
                android:hint="select end date"
                android:clickable="true"
                android:focusableInTouchMode="false" />

        </TableRow>

    </TableLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/imageViewCancel"
            android:layout_width="50dp"
            android:layout_height="60dp"
            android:layout_weight="1"
            android:src="@drawable/buttons_cancel"
            android:clickable="true" />

        <ImageView
            android:id="@+id/imageViewOk"
            android:layout_width="50dp"
            android:layout_height="60dp"
            android:layout_weight="1"
            android:src="@drawable/buttons_ok"
            android:clickable="true" />

    </LinearLayout>

</LinearLayout>

And this is my datepicker layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
<DatePicker 
    android:id="@+id/DatePicker01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"></DatePicker>
</LinearLayout>

I have not run the code as it show errors on some or the other lines in java code and I, myself got trapped by making this even more n more complex.


Solution

  • This is how i achieved that i wanted:

    public class AddictionDetails extends Activity 
    {
        TextView tv_addiction_name, tv_today, tv_yesterday, tv_this_week, tv_this_month, tv_total;
        ImageView iv_filter;
        int year, month, day;
        int placeData;
        Boolean state = false;
        DatePickerDialog.OnDateSetListener dateListener;
        SQLiteDatabase database;
        LinearLayout layout;
        int cat_id = 0;
        String startDateToCalculate = "";
        String endDateToCalculate = "";
    
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {   
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_addiction_details);
    
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    
            LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
            final View popupView = layoutInflater.inflate(R.layout.activity_filter_addiction_form, null);
            popupView.setVisibility(View.INVISIBLE);
    
            Intent intent = getIntent();
            final String cat_name = intent.getStringExtra("cat_name");
            tv_addiction_name = (TextView) findViewById(R.id.textViewAddictionDetails);
            tv_addiction_name.setText(cat_name);
    
            tv_total = (TextView) findViewById(R.id.textview_total);
            tv_today = (TextView) findViewById(R.id.textview_today);
            tv_yesterday = (TextView) findViewById(R.id.textview_yesterday);
            tv_this_week = (TextView) findViewById(R.id.textview_this_week);
            tv_this_month = (TextView) findViewById(R.id.textview_this_month);
    
            iv_filter = (ImageView) findViewById(R.id.imageViewAddictionDetailsFilter);
            iv_filter.setClickable(true);
            iv_filter.setOnClickListener(new OnClickListener()
                                            {
                                                @Override
                                                public void onClick(View v)
                                                {
                                                    if(state == false)
                                                    {
                                                        state = true;
                                                        popupView.setVisibility(View.VISIBLE);
                                                        final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                                                        final EditText etStartDate = (EditText)popupView.findViewById(R.id.editTextFilterStartDate);
                                                        popupWindow.showAtLocation(findViewById(R.id.relativeLayoutAddictionDetails), 0, 0, 100);
    //                                                  popupWindow.showAtLocation(popupView.findViewById(R.id.editTextFilterStartDate), 48, 0, 70);
    
                                                        final Calendar cal = Calendar.getInstance();
                                                        year = cal.get(Calendar.YEAR);
                                                        month = cal.get(Calendar.MONTH);
                                                        day = cal.get(Calendar.DAY_OF_MONTH);
    
                                                        etStartDate.setOnClickListener(new OnClickListener()
                                                                                            {   
                                                                                                @Override
                                                                                                public void onClick(View v)
                                                                                                {
                                                                                                    showDialog(1);
                                                                                                    placeData = 1;
                                                                                                }
                                                                                            }
                                                                                        );
    
                                                        final EditText etEndDate = (EditText)popupView.findViewById(R.id.editTextFilterEndDate);
                                                        etEndDate.setOnClickListener(new OnClickListener()
                                                                                            {   
                                                                                                @Override
                                                                                                public void onClick(View v)
                                                                                                {
                                                                                                    showDialog(1);
                                                                                                    placeData = 2;
                                                                                                }
                                                                                            }
                                                                                    );
    
                                                        Button btn_done = (Button) popupView.findViewById(R.id.buttonDone);
                                                        btn_done.setOnClickListener(new OnClickListener()
                                                                                    {
                                                                                         @Override
                                                                                         public void onClick(View v)
                                                                                         {
                                                                                             if(etStartDate.getText()+""=="" || etEndDate.getText()+""=="")
                                                                                             {
                                                                                                 AlertDialog.Builder adb = new Builder(AddictionDetails.this);
                                                                                                 adb.setTitle("Error");
                                                                                                 adb.setMessage("Fields can't be blank.");
                                                                                                 adb.setIcon(R.drawable.ic_launcher);
                                                                                                 adb.setPositiveButton("Ok",new DialogInterface.OnClickListener()
                                                                                                                                 {
                                                                                                                                     public void onClick(DialogInterface dialog, int which)
                                                                                                                                     {
                                                                                                                                         dialog.dismiss();
                                                                                                                                     }
                                                                                                                                 }
                                                                                                                        );
                                                                                                 AlertDialog ad = adb.create();
                                                                                                 ad.show();
                                                                                             }
                                                                                             else
                                                                                             {
                                                                                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                                                                                                SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
    
                                                                                                Date date1 = null, date2 = null;
                                                                                                try
                                                                                                {
                                                                                                    date1 = sdf.parse(startDateToCalculate);
                                                                                                    date2 = sdf.parse(endDateToCalculate);
                                                                                                }
                                                                                                catch (ParseException e)
                                                                                                {
                                                                                                    e.printStackTrace();
                                                                                                }
    
                                                                                                if(date1.compareTo(date2)>0)
                                                                                                {
                                                                                                    AlertDialog.Builder adb = new Builder(AddictionDetails.this);
                                                                                                    adb.setTitle("Error");
                                                                                                    adb.setMessage("Start date cannot be greater than End date.");
                                                                                                    adb.setIcon(R.drawable.ic_launcher);
                                                                                                    adb.setPositiveButton("Ok",new DialogInterface.OnClickListener()
                                                                                                                                 {
                                                                                                                                         public void onClick(DialogInterface dialog, int which)
                                                                                                                                         {
                                                                                                                                             dialog.dismiss();
                                                                                                                                         }
                                                                                                                                     }
                                                                                                                            );
                                                                                                     AlertDialog ad = adb.create();
                                                                                                     ad.show();
                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                    Intent intent = new Intent(AddictionDetails.this, FilteredData.class);
                                                                                                    intent.putExtra("start_date", startDateToCalculate);
                                                                                                    intent.putExtra("end_date", endDateToCalculate);
                                                                                                    intent.putExtra("start_date_to_display", etStartDate.getText()+"");
                                                                                                    intent.putExtra("end_date_to_display", etEndDate.getText()+"");
                                                                                                    intent.putExtra("cat_id", cat_id);
                                                                                                    intent.putExtra("cat_name", cat_name);
                                                                                                    startActivity(intent);
                                                                                                    popupWindow.dismiss();
                                                                                                    finish();
                                                                                                }
                                                                                             } 
                                                                                         }
                                                                                     }
                                                                                );
    
                                                        Button btn_cancel = (Button) popupView.findViewById(R.id.buttonCancel);
                                                        btn_cancel.setOnClickListener(new OnClickListener()
                                                                                        {
                                                                                             @Override
                                                                                             public void onClick(View v)
                                                                                             {
                                                                                                 etStartDate.setText("");
                                                                                                 etEndDate.setText("");
                                                                                                 popupView.setVisibility(View.INVISIBLE);
                                                                                                 popupWindow.dismiss();
                                                                                                 state = false;
                                                                                             }
                                                                                         }
                                                                                    );
    
                                                        dateListener = new DatePickerDialog.OnDateSetListener()
                                                        {
                                                            @Override
                                                            public void onDateSet(DatePicker view, int yr, int monthOfYear, int dayOfMonth)
                                                            {
                                                                SimpleDateFormat DateFormatToDisplay = new SimpleDateFormat("MMMM dd, yyyy");
                                                                SimpleDateFormat DateFormatToCalculate = new SimpleDateFormat("yyyy/MM/dd");
                                                                Calendar tmpC1 = Calendar.getInstance();
                                                                tmpC1.set(yr, monthOfYear, dayOfMonth);
                                                                Date tmpD1 = tmpC1.getTime();
                                                                String tmpDateString = DateFormatToDisplay.format(tmpD1);
                                                                String dateToCalculate = DateFormatToCalculate.format(tmpD1);
                                                                update(placeData, tmpDateString, dateToCalculate);
                                                            }
    
                                                            private void update(int position, String strDate, String date)
                                                            {
                                                                switch(position)
                                                                {
                                                                    case 1:
    
                                                                        etStartDate.setText(strDate);
                                                                        startDateToCalculate = date;
                                                                        break;
    
                                                                    case 2:
    
                                                                        etEndDate.setText(strDate);
                                                                        endDateToCalculate = date;
                                                                        break;
                                                                }
                                                            }
                                                        };
                                                        popupWindow.showAsDropDown(iv_filter);
                                                    }                                               
                                                }
                                            });
    
            loadDB();
    
            Cursor cursor = database.query("category", new String[]{"cat_id"}, "cat_name=?", new String[]{cat_name}, null, null, null);
    
            //----------------------fetching id-------------------
    
            if(cursor.getCount() > 0)
                while(cursor.moveToNext())
                    cat_id = cursor.getInt(0);
            cursor.close();
    
            //----------------------fetching attribute----------------
    
            String attribute = null;
            Cursor attributeCursor = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
            if(attributeCursor.getCount() > 0)
                while(attributeCursor.moveToNext())
                    attribute = attributeCursor.getString(0);
            cursor.close();
    
            //----------------------fetching total-------------------
    
            int totalCounter;
            Cursor totalCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+";", null);
            if(totalCursor.moveToNext())
                totalCounter = totalCursor.getInt(0);
            else
                totalCounter = 0;
            totalCursor.close();
            tv_total.setText(totalCounter+"  "+attribute);
    
            //----------------------fetching today's count---------------
    
            Calendar cal1 = Calendar.getInstance();
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd");
    
            String todays_date = dateFormat1.format(cal1.getTime());
            int todayCounter;
    
            Cursor todayCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date = '"+todays_date+"';", null);
            if(todayCursor.moveToNext())
                todayCounter = todayCursor.getInt(0);
            else
                todayCounter = 0;
            todayCursor.close();
    
            tv_today.setText(todayCounter+"  "+attribute);
    
            //----------------------fetching yesterdays count------------------
    
            Calendar cal2 = Calendar.getInstance();
            SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy/MM/dd");
            cal2.add(Calendar.DATE, -1);
    
            String yesterdays_date = dateFormat2.format(cal2.getTime());
    
            int yesterdayCounter = 0;
    
            Cursor yesterdayCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date = '"+yesterdays_date+"';", null);
    
            if(yesterdayCursor.moveToFirst())
                yesterdayCounter = yesterdayCursor.getInt(0);
            else
                yesterdayCounter = 0;
    
            yesterdayCursor.close();
    
            tv_yesterday.setText(yesterdayCounter+"  "+attribute);
    
            //-------------------------fetching current week count--------------------
    
            SimpleDateFormat weekDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Calendar c1 = Calendar.getInstance();
            c1.set(Calendar.DAY_OF_WEEK, 1);
            Date weekFirstDate = c1.getTime();
            String strWeekFirstDay = weekDateFormat.format(weekFirstDate);
    
            Cursor weekCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date BETWEEN '"+strWeekFirstDay+"' AND '"+todays_date+"';", null);
    
            int weekCounter = 0;
            if(weekCursor.moveToFirst())
                weekCounter = weekCursor.getInt(0);
            else
                weekCounter = 0;
            weekCursor.close();
    
            tv_this_week.setText(weekCounter+"  "+attribute);
    
            //----------------------fetching current month count--------------------
    
            SimpleDateFormat monthDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Calendar c2 = Calendar.getInstance();
            c2.set(Calendar.DAY_OF_MONTH, 1);
            Date monthFirstDate = c2.getTime();
            String strMonthFirstDay = monthDateFormat.format(monthFirstDate);
    
            Cursor monthCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date BETWEEN '"+strMonthFirstDay+"' AND '"+todays_date+"';", null);
            int monthCounter = 0;
            if(monthCursor.moveToFirst())
                monthCounter = monthCursor.getInt(0);
            else
                monthCounter = 0;
            monthCursor.close();
    
            tv_this_month.setText(monthCounter+"  "+attribute);
            database.close();
        }
    
        private void loadDB() 
        {
            database = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.OPEN_READWRITE, null);
        }
    
        protected Dialog onCreateDialog(int id)
        {
            return new DatePickerDialog(this, dateListener, year, month, day);
        }
    
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event)
        {
            if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
            {
                finish();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    }