0

我正在构建需要这种复杂机制的应用程序。请帮帮我。当我单击图像按钮时,它应该显示一个弹出窗口。在这个弹出窗口中,我保留了两个 editText。我已将两个 editTexts 都设置为 OnclickListener。现在,当我单击 edittext 时,它应该显示 DatePicker,最后当我在 datepicker 上设置日期时,它应该在那些 editTexts 上设置。

我不知道该怎么做。阅读一些教程,我使我的 java 代码看起来像:

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();
}
}

这是我的主要 xml 文件,其中包含 imageview,从中显示弹出窗口:

<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>

这是我的弹出布局 xml 代码:

<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>

这是我的日期选择器布局:

<?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>

我没有运行代码,因为它在 java 代码中的某些行或其他行上显示错误,而我自己被困住了,使这变得更加复杂。

4

2 回答 2

0

你是怎么解决的?我也想像你打开的那样打开日期选择器。

我的解决方案

//.java 文件

public void InitializePopupWindow() {
    LayoutInflater inflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // Inflate the view from a predefined XML layout
    layout = inflater.inflate(R.layout.popup_datepicker,
            (ViewGroup) getActivity().findViewById(R.id.popup));
    // create a 300px width and 470px height PopupWindow
    popup_window = new PopupWindow(layout, LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, true);
    popup_window.setOutsideTouchable(true);
    try {
        datepicker = (DatePicker) layout.findViewById(R.id.date_picker);
        popup_ok = (Button) layout.findViewById(R.id.btn_ok);
        popup_ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (dateSelection == 1) {
                    fromDate.set(Calendar.DAY_OF_MONTH,
                            datepicker.getDayOfMonth());
                    fromDate.set(Calendar.MONTH, datepicker.getMonth());
                    fromDate.set(Calendar.YEAR, datepicker.getYear());

                    fromDate = CommonFunctios
                            .getCurrentDateFromTime(fromDate);
                    btnFromDate.setText(fromDate.get(Calendar.DATE) + "/"
                            + fromDate.get(Calendar.MONTH) + "/"
                            + fromDate.get(Calendar.YEAR));

                } else if (dateSelection == 2) {

                    ToDate.set(Calendar.DAY_OF_MONTH,
                            datepicker.getDayOfMonth());
                    ToDate.set(Calendar.MONTH, datepicker.getMonth());
                    ToDate.set(Calendar.YEAR, datepicker.getYear());
                    ToDate = CommonFunctios.getCurrentDatetoTime(ToDate);
                    btnToDate.setText(ToDate.get(Calendar.DATE) + "/"
                            + ToDate.get(Calendar.MONTH) + "/"
                            + ToDate.get(Calendar.YEAR));
                }
                popup_window.dismiss();

            }
        });

        popup_cancel = (Button) layout.findViewById(R.id.btn_cancel);
        popup_cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                popup_window.dismiss();

            }
        });

        txtDateTitle = (TextView) layout.findViewById(R.id.txtDateTitle);
        txtDateTitle.setTypeface(CommonFunctios
                .getSegoUIBold(getActivity()));

        popup_window.setOutsideTouchable(true);
        popup_window.setTouchable(true);
        popup_window.setBackgroundDrawable(new BitmapDrawable());
        popup_window.setTouchInterceptor(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                return false;
            }
        });
    } catch (Exception e) {

    }
}

用于弹出窗口的 .xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/popup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/alert_light_frame"
android:gravity="center"
android:orientation="vertical" >

<TextView
    android:id="@+id/txtDateTitle"
    style="@style/thankyouTextstyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Select Date" />

<DatePicker
    android:id="@+id/date_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingTop="10dp" >

    <Button
        android:id="@+id/btn_ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@android:string/ok" />

    <Button
        android:id="@+id/btn_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@android:string/cancel" />
</LinearLayout>
</LinearLayout>

调用此弹出窗口

popup_window.showAsDropDown(btnFromDate);
popup_window.update();

这样我就解决了我的问题

于 2013-05-14T05:59:54.720 回答
0

这就是我实现我想要的方式:

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);
    }
}
于 2013-05-15T16:01:24.177 回答