如何打开对话窗口

时间:2014-04-25 04:32:54

标签: java android sqlite dialog

我正在尝试打开一个对话框窗口。我的程序是关于设置警报来完成硬件。因此,程序将提示用户键入主题和目标时间来完成它。当闹钟响起时,应弹出一个对话窗口,询问用户是否已完成。对话框窗口未显示。我不知道我做错了什么。我有以下四个类:Android Time Activity(主)类,Alarm接收器类,Database Handler类和输出类。

AndroidTimeActivity.java

import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;


public class AndroidTimeActivity extends Activity {

    TimePicker myTimePicker;
    Button buttonstartSetDialog;
    TextView textAlarmPrompt;
    EditText homeworkBar;
    DatabaseHandler db;

    TimePickerDialog timePickerDialog;
    //final Context context = this;

    final static int RQS_1 = 1;

    /* Called when the acitivity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_time);

        db = new DatabaseHandler(this);
        homeworkBar = (EditText)findViewById(R.id.Homework);

        textAlarmPrompt =(TextView)findViewById(R.id.alarmprompt);
        buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
        buttonstartSetDialog.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                textAlarmPrompt.setText("");
                openTimePickerDialog(false);

            }


        });
    }

    private void openTimePickerDialog(boolean is24r){
        Calendar calendar = Calendar.getInstance();

        timePickerDialog = new TimePickerDialog(
                AndroidTimeActivity.this,
                onTimeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                is24r);
        timePickerDialog.setTitle("Set Alarm Time");
        timePickerDialog.show();
    }

    OnTimeSetListener onTimeSetListener = new OnTimeSetListener(){

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute){

        Calendar calNow = Calendar.getInstance();
        Calendar calSet = (Calendar) calNow.clone();

        calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
        calSet.set(Calendar.MINUTE, minute);
        calSet.set(Calendar.SECOND, 0);
        calSet.set(Calendar.MILLISECOND,0);

        if(calSet.compareTo(calNow)<=0){
            calSet.add(Calendar.DATE, 1);
        }

        setAlarm(calSet);



        /* CONVERSION TO STRING TO BE SAVED IN DATABASE */
        int hours = calSet.getTime().getHours();
        int mins = calSet.getTime().getMinutes();

        String timeSet = "";
        if (hours > 12) {
            hours -= 12;
            timeSet = "PM";
        } else if (hours == 0) {
            hours += 12;
            timeSet = "AM";
        } else if (hours == 12)
            timeSet = "PM";
        else
            timeSet = "AM";


        String minutes = "";
        if (mins < 10)
            minutes = "0" + mins;
        else
            minutes = String.valueOf(mins);

        // Append in a StringBuilder
       String aTime = new StringBuilder().append(hours).append(':')
                .append(minutes).append(" ").append(timeSet).toString();

        String getHW = homeworkBar.getText().toString();

        db.addHW(getHW, aTime);
         Toast.makeText(getBaseContext(), "Homework Alarm is set!",
                    Toast.LENGTH_LONG).show(); 


    }

};


    private void setAlarm(Calendar targetCal){

        int hour = targetCal.getTime().getHours();
        int minute = targetCal.getTime().getMinutes();

           String timeSet = "";
            if (hour > 12) {
                hour -= 12;
                timeSet = "PM";
            } else if (hour == 0) {
                hour += 12;
                timeSet = "AM";
            } else if (hour == 12)
                timeSet = "PM";
            else
                timeSet = "AM";


            String minutes = "";
            if (minute < 10)
                minutes = "0" + minute;
            else
                minutes = String.valueOf(minute); 

           // Converting Time To String
           String TimeToString = new StringBuilder().append(hour).append(':')
                    .append(minutes).append(" ").append(timeSet).toString(); 

           db = new DatabaseHandler(getBaseContext());
           Cursor cursor = db.returnData();


           if(cursor.moveToFirst())
           {
               do{                  
                   if(TimeToString.equals(cursor.getString(1)))
                   {
                        Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), (int) System.currentTimeMillis(), intent, 0);
                        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
                   } 
               }while(cursor.moveToNext());


               }

           }

    }

AlarmReceiver.java

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;


public class AlarmReceiver extends BroadcastReceiver {
    private final String HOMEWORK = "com.example.alarm.ACTION";
    final AlarmReceiver context = this;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        generateNotification(context,"What's your next homework?");
        String action = intent.getAction();
        if (HOMEWORK.equals(action)) {
            //do what you want here
            generateNotification(context,"What's your next homework?");
        }
    }

    @SuppressWarnings("deprecation")
    private void generateNotification(Context context, String message) {
          System.out.println(message+"++++++++++2");
          int icon = R.drawable.ic_launcher;
          long when = System.currentTimeMillis();
          NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
          Notification notification = new Notification(icon, message, when);
          String title = context.getString(R.string.app_name);
          String subTitle = context.getString(R.string.app_name);
          Intent notificationIntent = new Intent(context, Output.class);
          notificationIntent.putExtra("content", message);
          PendingIntent intent = PendingIntent.getActivity(context,(int) System.currentTimeMillis(),notificationIntent, 0);
          notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

            LayoutInflater li = LayoutInflater.from(context);
            View promptsView = li.inflate(R.layout.prompts, null);

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);
            alertDialogBuilder
            .setCancelable(false)
            .setPositiveButton("Finish",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {

                }
              })
            .setNegativeButton("Not Finish",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
                }
              });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

          notification.setLatestEventInfo(context, title, subTitle, intent);
          //To play the default sound with your notification:
          notification.defaults |= Notification.DEFAULT_SOUND;
          notification.flags |= Notification.FLAG_AUTO_CANCEL;
          notification.defaults |= Notification.DEFAULT_VIBRATE;
          notificationManager.notify(0, notification);



    }

}

DatabaseHandler.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "TheDataBase";

    private static final String TABLE_HOMEWORK = "homework";



    SQLiteDatabase db;


    //Columns for Homework table 

        public static final String HOMEWORK = "subject";
        public static final String TIME = "time";


    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    //to create the tables
    public void onCreate(SQLiteDatabase db) {


        //String CREATE_MEDICATION_TABLE = "CREATE TABLE TABLE_MEDICATION(MEDICINES)";
        String CREATE_SCHEDULE_TABLE = "CREATE TABLE " + TABLE_HOMEWORK + "(" 
                + HOMEWORK + " TEXT," + TIME + " TEXT" + ")"; 

        db.execSQL(CREATE_SCHEDULE_TABLE);
        System.out.println("Tables created");
    }


    //to upgrade the database
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_HOMEWORK);
        onCreate(db);
    }


    public void addHW(String hw, String when){

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(HOMEWORK, hw);
        values.put(TIME, when);

        db.insertOrThrow(TABLE_HOMEWORK, null, values);
        db.close();
    }

    public Cursor returnData()
    {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.query(TABLE_HOMEWORK, new String[]{HOMEWORK, TIME}, null, null, null, null, null);
    }



}

Output.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class Output extends Activity{
    TextView textmessage;
     String stringValue;

     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_output);

      textmessage = (TextView)findViewById(R.id.textView1);

      Intent intent = getIntent();
      stringValue = intent.getStringExtra("content");
      textmessage.setText(stringValue);
      System.out.println(stringValue);

     }
}

0 个答案:

没有答案