Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Raport: Ciudin S

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Ministerul Educației al Republicii Moldova

Universitatea Tehnică a Moldovei


Facultatea Calculatoare, Informatică și Microelectronică

Departamentul Inginerie Software și Automatica

Desciplina: Proiectarea Aplicațiilor Mobile

Raport
Lucrare de laborator Nr.2
Tema: Organiser Mobile Application (DAILY PLANNER)

A verificat: asistent univ.


Ciudin S.

A efectuat: Studentul gr. TI-151


Poseletchi Cristi

Chișinău 2017
Obiective : Dezvoltarea unui Organiser pe platforma stabilită conform condițiilor puse.
Scopul lucrării de laborator:
De realizat aplicație tip Organiser pe platforma aleasă. La formarea și proiectarea aplicațiilor sunt
introduse puncte stricte, ce sunt obligatorii de respectat. La discreția personală rămâne designul aplicației și
API-ul/Framework-ul în care va fi dezvoltată lucrarea de laborator #2. Componentele și structura fiecărei
Activități va fi descrisă mai jos.
UI Components:
Aplicația va conține minim 3 Activități de baza care vor fi numerotate în lucrare sub forma:
1. MainActivity (structura/componente)
 Calendar View (custom or default)
 Buttons (Add/Remove/Update)
 Căutare (caută conform cuvintelor cheie)
2. AddtActivity
 Data/Time controller
 Info TextBoxButtons
 și altele (la discreție conform specificului aplicației)
3. UpdateActivity - practic e una și aceeași activitate de la Add, doar ca completata deja.
Datele operaționale din interiorul aplicației vor fi stocate în fișier/e XML forma cărora rămâne la
discreția personală. (cuvinte cheie, XML Serialization).
Logical/Operational Component
Toate evenimentele și acțiunile de notificare/semnalizare (sonore/vizuale) intreprinse în Organiser
vor fi tratate într-un serviciu aparte, care logic funcțional va extrage datele din acel fișier XML.

Mersul lucrării
 Setarea unui layout
 Setarea unui calendar view
 Crearea funcționalului
Setarea layout-ului
Pentru aplicația dată am creat 3 layout-uri:

Figura 1 – Layout-urile create


Layout-ul activității principale MainActivity este creat din 2 layout-uri: activity_main.xml și
content_main.xml aceasta este din cauza că acesta este un material design layout, unul conține componentele
de bară de instrumente și elemente adăugate recent, iar unul conține elemente de UI mai vechi.
Pentru activitatea de adăugare și activitatea de editare a unui eveniment a fost folosit același layout
activity_add_event.xml din cauza că ambele activități conțin aceleași elemente și îndeplinesc aproximativ
același lucru.

Crearea aplicației
Pentru lucrarea dată de laborator au fost create 4 activități:

 MainActivity [Anexa A]
 AddEventActivity [Anexa B]
Au fost create 2 clase:

 Events [Anexa C]
 Data [Anexa D]
A fost creat un serviciu NotificationSercive [Anexa E] și un broadcast reciver
NotificationBroadcastReciver [Anexa F].
Activitatea principală (MainActivity)
Activitatea principală conține calendarul care afișează luna întreagă. Aici utilizatorul poate vizualiza în
ce zile sunt setate ceva evenimente, zilele acestea au indicatoare de eveniment, tot din această activitate se
poate efectua căutarea unui eveniment după cuvinte cheie, conform figurii 2.

Figura 2 – Activitatea principală


Activitatea de adăugare (AddEventActivity)
Activitatea de adăugare conține 2 EditText pentru introducerea denumirii și descrierea eventului, 1
date_label pentru introducerea datei și un time_label pentru timp aici se introduc datele și se transmit mai
departe la prelucrare, conform figurii 2.

Figura 3 – Activitatea de adăugare


Concluzie
În cadrul lucrării date de laborator a fost elaborat un organiser personal pe platforma Android.Pentru
aceasta au fost elaborate: activitatea de vizualizare a calendarului de unde utilizatorul poate vedea un rezumat
al tuturor evenimetelor sale, activitatea de vizualizare a listei de evenimente dintr-o zi sau evenimentele căutate
după cuvinte cheie, activitatea de adăugare a unui eveniment nou, activitatea de editare a unui eveniment și
serviciile de notificare.
Pentru salvarea evenimentelor în fișier a fost folosită biblioteca XStream, aceasta este o bibliotecă
puternică din limbajul Java care permite serializarea și deserializarea obiectelor și convertarea acestora în xml.
La elaborarea alicației au fost întâlnite mai multe probleme, cele mai grele au fost legate de logica de
funcționare a aplicației și toate excepțiile care au fost necesar de prevăzut și prelucrat. A fost necesar de
prevăzut toate cazurile de manipulare cu lista de evenimente și fișierul xml generat, ceea ce s-a nimerit a fi
destul de dificil.
Pentru asigurarea notificării evenimentelor au fost create serviciul de notificare, care se rulează în
background pe dispozitivul pe care această aplicație este instalată și broadcast reciver-ul care primește pending
intent-ul de la serviul de notificare și creează notificarea.
Bibliografie
1 XStream [Resursă electronică] - Regim de acces: http://x-stream.github.io/
2 Animații pentru Floating Action Buttons[Resursă electronică] - Regim de acces:
https://www.learn2crack.com/2015/10/android-floating-action-button-animations.html
3 Date/TimePickerDialog[Resursă electronică] - Regim de acces:
https://developer.android.com/reference/android/app/DatePickerDialog.html
4 java.util.ConcurrentModificationException [Resursă electronică] - Regim de acces:
http://www.programcreek.com/2014/01/java-util-concurrentmodificationexception/
5 Intent Filter [Resursă electronică] - Regim de acces:
https://developer.android.com/guide/topics/manifest/intent-filter-element.html
6 BroadcastReciver [Resursă electronică] - Regim de acces:
https://developer.android.com/reference/android/content/BroadcastReceiver.html
Anexa A
Cod Sursă (MainActivity)
package com.example.misha.organiser;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

public class MainActivity extends AppCompatActivity {


private final static int ADD_EVENT = 43;
private final static String ADD_EVENT_ACTION = "add";
private final static int MODIFY_EVENT = 37;
private final static String MODIFY_EVENT_ACTION = "modify";
private SimpleDateFormat dateFormatForMonth = new SimpleDateFormat("MMMM yyyy",
Locale.getDefault());
private Date currentDate;
private CompactCalendarView compactCalendarView;
private Events events;
private XStream xstream = new XStream(new DomDriver());
private Button delete;
private Button show;
private Button search;
private Button fab;
private Button modify;
private EditText searchField;
private Toolbar toolbar;
private ActionBar actionBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
delete = (Button) findViewById(R.id.button_delete);
show = (Button) findViewById(R.id.button_show);
search = (Button) findViewById(R.id.button_search);
modify = (Button) findViewById(R.id.button_modify);
searchField = (EditText) findViewById(R.id.editText);
fab = (Button) findViewById(R.id.fab);
actionBar = getSupportActionBar();
actionBar.setTitle(null);
compactCalendarView = (CompactCalendarView) findViewById(R.id.compactcalendar_view);

actionBar.setTitle(dateFormatForMonth.format(compactCalendarView.getFirstDayOfCurrentMonth()))
;
currentDate = new Date();
compactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener()
{
@Override
public void onDayClick(Date dateClicked) {
currentDate = dateClicked;
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteData();
}
});
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showData();
}
});
}
@Override
public void onMonthScroll(Date firstDayOfNewMonth) {
actionBar.setTitle(dateFormatForMonth.format(firstDayOfNewMonth));

}
});
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchData(searchField);
}
});
modify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
modifyData();
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), AddEventActivity.class);
intent.putExtra("beginDate", currentDate.getTime());
intent.setAction(ADD_EVENT_ACTION);
startActivityForResult(intent, ADD_EVENT);
}
});
refresh();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK || (resultCode == RESULT_CANCELED && requestCode ==
MODIFY_EVENT)) {
Data event = new Data();
event
.setDescription(data.getExtras().getString("description"))
.setTitle(data.getExtras().getString("title"))
.setId(new Random().nextInt(543254))
.setCalendarDate(data.getExtras().getLong("time"));
if (events == null) events = new Events();
ArrayList<Data> datas = new ArrayList<>();
if (events.getData() == null) {
events.data = datas;
}
events.data.add(event);
saveToXML();
refresh();
}
}

private void modifyData() {


final List<Event> ev = compactCalendarView.getEvents(currentDate);
if (!ev.isEmpty()) {
List<String> stockList = new ArrayList<>();
for (Event event : ev) {
Data data = (Data) event.getData();
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date = new Date();
date.setTime(data.getCalendarDate());
stockList.add("Title:" + data.getTitle() + "\nDescription:" +
data.getDescription() + "\nLocation:" + data.getLocation() +
"\nAt " + format.format(date));
}
String[] value = new String[stockList.size()];
value = stockList.toArray(value);
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle("Dates");
alertDialogBuilder.setItems(value, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Data data = (Data) ev.get(which).getData();
Intent intent = new Intent(getApplicationContext(),
NotificationService.class);
intent.setAction(NotificationService.CANCEL);
intent.putExtra("requestCode", data.getId());
startService(intent);
events.data.remove(data);
compactCalendarView.removeEvent(ev.get(which), true);
Intent modifyIntent = new Intent(getApplicationContext(),
AddEventActivity.class);
modifyIntent.putExtra("title", data.getTitle());
modifyIntent.putExtra("description", data.getDescription());
modifyIntent.putExtra("time", data.getCalendarDate());
modifyIntent.setAction(MODIFY_EVENT_ACTION);
startActivityForResult(modifyIntent, MODIFY_EVENT);
}
});
AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
} else Toast.makeText(MainActivity.this, "No events on this day!",
Toast.LENGTH_SHORT).show();
}

private void searchData(EditText searchField) {


if(!(events == null)) {
final List<Data> ev = events.data;
List<String> stockList = new ArrayList<>();
for (Data data : ev) {
if (data.getTitle().contains(searchField.getText().toString())) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm EEE, dd MMM yyyy");
Date date = new Date();
date.setTime(data.getCalendarDate());
stockList.add("Title:" + data.getTitle() + " Description:" +
data.getDescription() + " Location:" + data.getLocation() +
" at " + format.format(date));
}
}
if (!stockList.isEmpty()) {
String[] value = new String[stockList.size()];
value = stockList.toArray(value);
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle("Dates");
alertDialogBuilder.setItems(value, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
searchField.setText("");

} else {
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
searchField.setText("");
Toast.makeText(MainActivity.this, "No events found!",
Toast.LENGTH_SHORT).show();
}
}else Toast.makeText(MainActivity.this, "No events in calendar!",
Toast.LENGTH_SHORT).show();

private void showData() {


final List<Event> ev = compactCalendarView.getEvents(currentDate);
if (!ev.isEmpty()) {
List<String> stockList = new ArrayList<>();
for (Event event : ev) {
Data data = (Data) event.getData();
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date = new Date();
date.setTime(data.getCalendarDate());
stockList.add("Title:" + data.getTitle() + " Description:" +
data.getDescription() + " Location:" + data.getLocation() +
" at " + format.format(date));
}
String[] value = new String[stockList.size()];
value = stockList.toArray(value);
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle("Dates");
alertDialogBuilder.setItems(value, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = alertDialogBuilder.create();
dialog.show();

} else Toast.makeText(MainActivity.this, "No events on this day!",


Toast.LENGTH_SHORT).show();
}

private void deleteData() {


final List<Event> ev = compactCalendarView.getEvents(currentDate);
if (!ev.isEmpty()) {
List<String> stockList = new ArrayList<>();
for (Event event : ev) {
Data data = (Data) event.getData();
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date = new Date();
date.setTime(data.getCalendarDate());
stockList.add("Title:" + data.getTitle() + " Description:" +
data.getDescription() + " Location:" + data.getLocation() +
" at " + format.format(date));
}
String[] value = new String[stockList.size()];
value = stockList.toArray(value);
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle("Dates");
alertDialogBuilder.setItems(value, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Data data = (Data) ev.get(which).getData();
Intent intent = new Intent(getApplicationContext(),
NotificationService.class);
intent.setAction(NotificationService.CANCEL);
intent.putExtra("requestCode", data.getId());
startService(intent);
events.data.remove(data);
compactCalendarView.removeEvent(ev.get(which), true);
if (events.data.isEmpty()) {
getApplicationContext().deleteFile("events.xml");
events = null;
refresh();
} else {
saveToXML();
refresh();
}
}
});
AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
} else Toast.makeText(MainActivity.this, "No events on this day!",
Toast.LENGTH_SHORT).show();
}

private void saveToXML() {


xstream.processAnnotations(Events.class);
xstream.processAnnotations(Data.class);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(new
File(getApplicationContext().getFilesDir(), "events.xml"));
outputStream.write(xstream.toXML(events).getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private void refresh() {


compactCalendarView.removeAllEvents();
compactCalendarView.invalidate();
Intent intent = new Intent(getApplicationContext(), NotificationService.class);
intent.setAction(NotificationService.UPDATE);
startService(intent);
XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(Events.class);
xstream.processAnnotations(Data.class);
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(this.getFilesDir(), "events.xml"));
events = (Events) xstream.fromXML(inputStream);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (events != null) {
compactCalendarView.removeAllEvents();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
Calendar currentDate = Calendar.getInstance();
Date time = new Date();
for (Data data : events.data) {
time.setTime(data.getCalendarDate());
currentDate.setTimeInMillis(data.getCalendarDate());
Event event = new Event(data.getColor(), data.getCalendarDate(), data);
int interval = calendar.getMaximum(Calendar.DAY_OF_YEAR) -
currentDate.get(Calendar.DAY_OF_YEAR);
if(data.getRepeating() == 0) {
compactCalendarView.addEvent(event, true);
} else if(data.getRepeating() == NotificationBroadcastReceiver.INTERVAL_DAY) {
currentDate.setTimeInMillis(data.getCalendarDate());
for (int i = 0; i <= interval; i++) {
event = new Event(data.getColor(),time.getTime(),data);
compactCalendarView.addEvent(event,true);
time.setTime(time.getTime() +
NotificationBroadcastReceiver.INTERVAL_DAY);
}
} else if(data.getRepeating() == NotificationBroadcastReceiver.INTERVAL_WEEK)
{
currentDate.setTimeInMillis(data.getCalendarDate());
for (int i = 0; i <= interval/7; i++) {
event = new Event(data.getColor(),time.getTime(),data);
compactCalendarView.addEvent(event,true);
time.setTime(time.getTime() +
NotificationBroadcastReceiver.INTERVAL_WEEK);
}
} else if(data.getRepeating() == NotificationBroadcastReceiver.INTERVAL_MONTH)
{
currentDate.setTimeInMillis(data.getCalendarDate());
for (int i = 0; i <= interval/30; i++) {
event = new Event(data.getColor(),time.getTime(),data);
compactCalendarView.addEvent(event,true);
time.setTime(time.getTime() +
NotificationBroadcastReceiver.INTERVAL_MONTH);
}
} else if(data.getRepeating() == NotificationBroadcastReceiver.INTERVAL_YEAR)
{
currentDate.setTimeInMillis(data.getCalendarDate());
for (int i = 0; i <= 10; i++) {
event = new Event(data.getColor(),time.getTime(),data);
compactCalendarView.addEvent(event,true);
time.setTime(time.getTime() +
NotificationBroadcastReceiver.INTERVAL_YEAR);
}
}
}
}
}

private void updateData(Data info) {


if (events == null) events = new Events();
ArrayList<Data> data = new ArrayList<>();
if (events.getData() == null) {
events.data = data;
}
events.data.add(info);
saveToXML();
refresh();

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.search) {
return true;
} else if (id == R.id.current_day) {

compactCalendarView.setCurrentDate(Calendar.getInstance(Locale.getDefault()).getTime());

actionBar.setTitle(dateFormatForMonth.format(compactCalendarView.getFirstDayOfCurrentMonth()))
;
}
return false;
}
}
Anexa B
Codul sursă (AddEventActivity)
package com.example.misha.organiser;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

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

public class AddEventActivity extends AppCompatActivity {


private Date parsedDate;
private TextView descriptionLabel;
private TextView eventTitleLabel;
private Calendar calendar = Calendar.getInstance();
private static SimpleDateFormat dateFormatForMonth = new SimpleDateFormat("EEE, dd MMM
yyyy", Locale.getDefault());
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_event);
final ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Event create");
TextView startTimeLabel = (TextView) findViewById(R.id.time_label);
TextView beginDateLabel = (TextView) findViewById(R.id.date_label);
eventTitleLabel = (TextView) findViewById(R.id.event_title_label);
descriptionLabel = (TextView) findViewById(R.id.description_label);
Date date = new Date();
if(getIntent().getAction().equals("modify")) {
date.setTime(getIntent().getExtras().getLong("time"));
calendar.setTime(date);
beginDateLabel.setText(dateFormatForMonth.format(date));
startTimeLabel.setText(timeFormat.format(date));
eventTitleLabel.setText(getIntent().getExtras().getString("title"));
descriptionLabel.setText(getIntent().getExtras().getString("description"));
} else if(getIntent().getAction().equals("add")){
date.setTime(getIntent().getLongExtra("beginDate",-1));
calendar.setTime(date);
beginDateLabel.setText(dateFormatForMonth.format(date));
}
startTimeLabel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
});
beginDateLabel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
}
private class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
TextView viewById = (TextView)getActivity().findViewById(R.id.time_label);
if(minute < 10) {
viewById.setText(hourOfDay + ":0" + minute);
}
else {
viewById.setText(hourOfDay + ":" + minute);
}
calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
calendar.set(Calendar.MINUTE,minute);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
parsedDate = calendar.getTime();
}
}
private class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
TextView beginDateLabel = (TextView)getActivity().findViewById(R.id.date_label);
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,day);
parsedDate = calendar.getTime();
beginDateLabel.setText(dateFormatForMonth.format(parsedDate));
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.add, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.cancel_button) {
Intent intent = new Intent();
if(getIntent().getAction().equals("modify")){
intent.putExtra("title", getIntent().getExtras().getString("title"));

intent.putExtra("description",getIntent().getExtras().getString("description"));
intent.putExtra("time", getIntent().getExtras().getLong("time"));

}
setResult(RESULT_CANCELED, intent);
finish();
return true;
}else if(id == R.id.save_button){
if(parsedDate != null
&& !TextUtils.isEmpty(eventTitleLabel.getText().toString())
&& !TextUtils.isEmpty(descriptionLabel.getText().toString())) {
Intent intent = new Intent();
intent.putExtra("title", eventTitleLabel.getText().toString());
intent.putExtra("description", descriptionLabel.getText().toString());
intent.putExtra("time", parsedDate.getTime());
setResult(RESULT_OK, intent);
finish();
} else Toast.makeText(AddEventActivity.this, "Enter Dates",
Toast.LENGTH_SHORT).show();
}

return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
Intent intent = new Intent();
if(getIntent().getAction().equals("modify")){
intent.putExtra("title", getIntent().getExtras().getString("title"));
intent.putExtra("description",getIntent().getExtras().getString("description"));
intent.putExtra("time", getIntent().getExtras().getLong("time"));
}
setResult(RESULT_CANCELED, intent);
finish();
super.onBackPressed();
}
}
Anexa C
Codul sursă (Events)
package com.example.misha.organiser;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

import java.util.ArrayList;
@XStreamAlias("Events")
public class Events {
@XStreamImplicit(itemFieldName = "Data")
public ArrayList<Data> data;

public ArrayList<Data> getData() {


return data;
}
}
Anexa D
Codul sursă (Data)
package com.example.misha.organiser;

import com.thoughtworks.xstream.annotations.XStreamAlias;

public class Data{


@XStreamAlias("ID")
private int id;
@XStreamAlias("Title")
private String title;
@XStreamAlias("Description")
private String description;
@XStreamAlias("Location")
private String location;
@XStreamAlias("CalendarDate")
private long calendarDate;
@XStreamAlias("Repeating")
private long repeating;
@XStreamAlias("Color")
private int color;

@XStreamAlias("Remind")
private int remind;

public int getRemind() {


return remind;
}

public Data setRemind(int remind) {


this.remind = remind;
return this;
}

public int getColor() {


return color;
}

public Data setColor(int color) {


this.color = color;
return this;
}

public long getRepeating() {


return repeating;
}

public Data setRepeating(long repeating) {


this.repeating = repeating;
return this;
}

public long getCalendarDate() {


return calendarDate;
}

public Data setCalendarDate(long calendarDate) {


this.calendarDate = calendarDate;
return this;
}
public int getId() {
return id;
}

public Data setId(int id) {


this.id = id;
return this;
}

public String getTitle() {


return title;
}

public Data setTitle(String title) {


this.title = title;
return this;
}

public String getDescription() {


return description;
}

public Data setDescription(String description) {


this.description = description;
return this;
}

public String getLocation() {


return location;
}

public Data setLocation(String location) {


this.location = location;
return this;
}
}
Anexa E
Codul sursă (NotificationService)
package com.example.misha.organiser;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class NotificationService extends IntentService {


public static final String CANCEL = "CANCEL";
public static final String UPDATE = "UPDATE";
private Events events;

public NotificationService() {
super("StudentOrganizerService");
}

@Override
protected void onHandleIntent(Intent intent) {
if (UPDATE.equals(intent.getAction())) {
executeUpdate();
} else if(CANCEL.equals(intent.getAction())) {
executeCancel(intent.getExtras().getInt("requestCode"));
}
}
private void executeCancel(int requestCode){
Intent notificationIntent = new Intent(this, NotificationBroadcastReceiver.class);
notificationIntent.setAction(requestCode+"");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
private void executeUpdate() {
XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(Events.class);
xstream.processAnnotations(Data.class);
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(this.getFilesDir(), "events.xml"));
events = (Events) xstream.fromXML(inputStream);
inputStream.close();
} catch (IOException ignored) {
}
if (events != null) {
for (Data data : events.data) {
Intent notificationIntent = new Intent(this,
NotificationBroadcastReceiver.class);
notificationIntent.putExtra(NotificationBroadcastReceiver.NOTIFICATION_ID,
data.getId());
notificationIntent.putExtra("title", data.getTitle());
notificationIntent.putExtra("description", data.getDescription());
notificationIntent.setAction(data.getId() + "");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, data.getId(),
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Date g = new Date();
g.setTime(data.getCalendarDate());
if (new Date().before(g)) {
if(data.getRepeating() == 0) {
alarmManager.set(AlarmManager.RTC_WAKEUP, data.getCalendarDate() -
data.getRemind(), pendingIntent);
} else
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
data.getCalendarDate(), data.getRepeating() - data.getRemind(), pendingIntent);
}
}
}
}
}
Anexa F
Codul sursă (NotificationBroadcastReciver)
package com.example.misha.organiser;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;

import java.util.Calendar;
public class NotificationBroadcastReceiver extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";


public static long INTERVAL_MINUTE = AlarmManager.INTERVAL_FIFTEEN_MINUTES / 15;
public static long INTERVAL_HOUR = AlarmManager.INTERVAL_FIFTEEN_MINUTES * 4;
public static long INTERVAL_DAY = AlarmManager.INTERVAL_DAY;
public static long INTERVAL_WEEK = INTERVAL_DAY * 7;
public static long INTERVAL_MONTH =
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH) * INTERVAL_DAY;
public static long INTERVAL_YEAR =
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_YEAR) * INTERVAL_DAY;

public void onReceive(Context context, Intent intent) {


NotificationManager notificationManager =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Data info = new Data();
info
.setLocation(intent.getExtras().getString("location"))
.setDescription(intent.getExtras().getString("description"))
.setTitle(intent.getExtras().getString("title"));
Notification notification = getNotification(info,context);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(id, notification);
}
private Notification getNotification(Data data,Context context) {
Notification.Builder builder = new Notification.Builder(context);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder
.setContentTitle(data.getTitle())
.setShowWhen(false)
.setContentText(data.getDescription()+ "\n" + "at " + data.getLocation())
.setSmallIcon(R.drawable.calendar_clock)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.drawable.calendar_clock))
.setSound(alarmSound)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.setLights(0xff00ff00, 300, 100);
return builder.build();
}
}

You might also like