Tuesday 17 July 2012

Sample Remainder Using Service and Sqlite

Create an application which remands you some thing on selected  date and time which

main.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Time"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/editTexttime"
            android:layout_width="300px"
            android:layout_height="wrap_content"
            android:editable="false" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/buttontime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="Time" />
    </LinearLayout>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Date"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/editTextdate"
            android:layout_width="300px"
            android:layout_height="wrap_content"
            android:editable="false" />

        <Button
            android:id="@+id/buttondate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="Date" />
    </LinearLayout>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Remainder Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/editTextremaindtext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radiovibrate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Vibrate" />

        <RadioButton
            android:id="@+id/radioring"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Ring" />
    </RadioGroup>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/buttonsave"
            android:layout_width="200px"
            android:layout_height="wrap_content"
            android:text="Save" />
    </LinearLayout>

</LinearLayout>

 
Graphical layout 


Sqlite Helper class looks as fallows 

public class SqliteHelper extends SQLiteOpenHelper {

    static final String DBNAME = "DBNAME";
    static final String REMAINDER_TABLE = "REMAINDER_TABLE";
    static final String ID = "ID";
    static final String TIME = "TIME";
    static final String Date = "DATE";
    static final String REMAIND_TEXT = "REMAIND";
    static final String ALERT_FLAG = "ALERT_FLAG";
    static final String ALERT_TYPE = "ALERT_TYPE";

    public SqliteHelper(Context context) {
        super(context, DBNAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE " + REMAINDER_TABLE + " (" + TIME + " TEXT, "
                + Date + " TEXT, " + REMAIND_TEXT + " TEXT, " + ALERT_FLAG
                + " TEXT, " + ALERT_TYPE + " TEXT," + ID + " TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

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

    }

    public int remaindMySchedule(String time, String date, String desc,
            String flag, String type) {
        SQLiteDatabase db = null;
        int a = 0;
        try {
            db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put(TIME, time);
            cv.put(Date, date);
            cv.put(REMAIND_TEXT, desc);
            cv.put(ALERT_FLAG, flag);
            cv.put(ALERT_TYPE, type);
            cv.put(ID, "" + Sequncer() + 1);

            a = (int) db.insert(REMAINDER_TABLE, null, cv);

        } catch (Exception e) {
            Log.d("Exception", "Sorry" + e);

        } finally {
            db.close();
        }
        return a;

    }

    public ArrayList<HashMap<String, String>> CheckMyschedule(String time,
            String date) {
        SQLiteDatabase db = null;
        Cursor cur = null;
        ArrayList<HashMap<String, String>> DATA = new ArrayList<HashMap<String, String>>();
        try {
            db = this.getReadableDatabase();
            String query = "SELECT " + REMAIND_TEXT + ", " + ALERT_FLAG + ","
                    + ALERT_TYPE + "," + ID + " FROM " + REMAINDER_TABLE
                    + " WHERE " + TIME + "='" + time + "' AND " + Date + "='"
                    + date + "' AND " + ALERT_FLAG + "='true'";
            Log.d("Message", "query" + query);
            cur = db.rawQuery(query, null);
            Log.d("Message", "count" + cur.getCount());

            while (cur.moveToNext()) {
                HashMap<String, String> values = new HashMap<String, String>();
                values.put(REMAIND_TEXT, cur.getString(0));
                values.put(ALERT_FLAG, cur.getString(1));
                values.put(ALERT_TYPE, cur.getString(2));
                values.put(ID, cur.getString(3));

                DATA.add(values);
                Log.d("Message", "values" + DATA.toString());

            }

        } catch (Exception e) {
            e.printStackTrace();
            // Log.d("Message", "Failed" + e);
        } finally {
            cur.close();
            db.close();
        }
        return DATA;

    }

    private int Sequncer() {
        // TODO Auto-generated method stub
        SQLiteDatabase db = null;
        Cursor cur = null;
        int PK = 0;
        try {
            db = this.getReadableDatabase();
            String query = "SELECT * FROM " + REMAINDER_TABLE;
            cur = db.rawQuery(query, null);
            if (cur.moveToNext()) {
                PK = cur.getCount();
            }

        } catch (Exception e) {
            Log.d("Message", "Failed" + e);

        }
        return PK;

    }

    public void FlagUpdate(String id) {
        SQLiteDatabase db = null;

        try {
            db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put(ALERT_FLAG, "false");
            cv.put(ID, id);

            int a = db.update(REMAINDER_TABLE, cv, ID + "=?",
                    new String[] { id });
            Log.d("Message", "update-->" + a);

        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}


Activity Class 


public class Schedule extends Activity {
    EditText time;
    EditText date;
    Button TimeBut;
    Button DateBut;
    EditText Remainder;
    Button Save;
    int hours, min, sec;
    RadioButton vibrate;
    RadioButton ring;
    static final int ID = 3;
    static String alert = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        time = (EditText) findViewById(R.id.editTexttime);
        date = (EditText) findViewById(R.id.editTextdate);
        TimeBut = (Button) findViewById(R.id.buttontime);
        DateBut = (Button) findViewById(R.id.buttondate);
        Save = (Button) findViewById(R.id.buttonsave);
        Save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startService(new Intent(Schedule.this, ServiceExample.class));
                SaveRemainder();

            }
        });
        vibrate = (RadioButton) findViewById(R.id.radiovibrate);
        vibrate.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                alert = "VIBRATE";
            }
        });
        ring = (RadioButton) findViewById(R.id.radioring);
        ring.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                alert = "RING";
            }
        });
        Remainder = (EditText) findViewById(R.id.editTextremaindtext);
        TimeBut.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onCreateDialog(ID).show();
            }
        });
        Calendar cad = Calendar.getInstance();
        hours = cad.get(Calendar.HOUR_OF_DAY);
        min = cad.get(Calendar.MINUTE);
        sec = cad.get(Calendar.SECOND);
        UpdateTime();
    }

    TimePickerDialog.OnTimeSetListener datedata = new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // TODO Auto-generated method stub
            hours = hourOfDay;
            min = minute;
            UpdateTime();
        }
    };

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case ID:
            return new TimePickerDialog(this, datedata, hours, min, true);

        }
        return null;
    }

    private void UpdateTime() {

        this.time.setText(new StringBuilder().append(hours).append("-")
                .append(min));

    }

    private void SaveRemainder() {

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        String date = sdf.format(new Date());
        Log.d("Time----->", time.getText().toString());
        SqliteHelper sqliteHelper = new SqliteHelper(this);
        int a = sqliteHelper.remaindMySchedule(time.getText().toString(), date,
                Remainder.getText().toString(), "true", alert);
        if (a > 0) {
            Toast.makeText(this, "Done", Toast.LENGTH_LONG).show();
        }

    }
}


Service Class 
This class used to check the time and date which is selected by user for every 3000 mill seconds  

 public class ServiceExample extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        looper();
    }

    private void looper() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Method();
            }
        }, 10, 30 * 1000);
    }

    void Method() {

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        String date = sdf.format(new Date());
        Log.d("Date", date);

        SimpleDateFormat sdf2 = new SimpleDateFormat("HH-mm");
        String time = sdf2.format(new Date());
        Log.d("Message", time);

        SqliteHelper helper = new SqliteHelper(this);

        ArrayList<HashMap<String, String>> names = new ArrayList<HashMap<String, String>>();
        names = helper.CheckMyschedule(time, date);

        if (names.isEmpty()) {
            Log.d("Message", "No data Found");
        } else {
            HashMap<String, String> values = names.get(0);
            if (values.isEmpty()) {
                Log.d("Message", "No data Found");

            } else {
                String text = values.get(SqliteHelper.REMAIND_TEXT);
                Message message = new Message();
                Bundle bundel = new Bundle();
                bundel.putString("Name", text);
                message.obj = bundel;
                handler.sendMessage(message);
                String id = values.get(SqliteHelper.ID);
                helper.FlagUpdate(id);
            }
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(getApplicationContext(),    "Hi Sai to day you have a meeting please check the details",Toast.LENGTH_LONG).show();

        };
    };
}


This is the screen when condition get satisfied throws a toast on the screen







get more about vibrate and ring options of the application



Vibrate on Toast Sample


public class ToastNotification extends Toast {

    public ToastNotification(Context context, CharSequence text, int long1) {
        super(context);
        Vibrator vib = (Vibrator) context
                .getSystemService(Context.VIBRATOR_SERVICE);
        vib.vibrate(5000);
        super.makeText(context, text, long1);
    }

}

Call Toast Class in the service



private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String Alerttype = SqliteHelper.ALERT_TYPE;
            Ringer(Alerttype);

        };
    };

    private void Ringer(String name) {

        if (SqliteHelper.ALERT_TYPE.equals("vibrate")) {

            vibrate();

        } else if (SqliteHelper.ALERT_TYPE.equals("ring")) {

            RingTone();

        }

    }

    private void RingTone() {

        new ToastNotification(getApplicationContext(),
                "Hi Sai to day you have a meeting please check the details",
                Toast.LENGTH_LONG);
    }

    private void vibrate() {

        Uri notification = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
                notification);
        r.play();

    }




where u can get the alert based on your sqlite data if the sqlite.ALERT_TYPE="vibrate" thenj it calls the method vibrate() else case it calls RingTone


No comments:

Post a Comment