diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..94b4696 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +Notes \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index ae78c11..f24a632 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -1,5 +1,8 @@ + + diff --git a/.idea/gradle.xml b/.idea/gradle.xml index ee635a3..5cd135a 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -1,11 +1,10 @@ + diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..eb2873e --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/markdown-navigator-enh.xml b/.idea/markdown-navigator-enh.xml new file mode 100644 index 0000000..a8fcc84 --- /dev/null +++ b/.idea/markdown-navigator-enh.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/markdown-navigator.xml b/.idea/markdown-navigator.xml new file mode 100644 index 0000000..a2fc086 --- /dev/null +++ b/.idea/markdown-navigator.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 29bb4c5..703e5d4 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -5,7 +5,7 @@ - + diff --git a/README.md b/README.md index 23b619d..c999c20 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Notes App allows you to save your important informations that you need to remember.
You can set notifications and share your notes. +You can also add your location # Used technologies and Android components - MVVM diff --git a/app/build.gradle b/app/build.gradle index 345d501..15a4a39 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -16,9 +16,15 @@ android { proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } } dependencies { + implementation 'com.google.android.gms:play-services-maps:17.0.0' + implementation 'com.google.android.libraries.places:places:1.1.0' // ViewModel and LiveData def lifecycle_version = "2.1.0" @@ -38,7 +44,7 @@ dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' - + implementation 'com.google.android.gms:play-services-location:17.0.0' // Toasty implementation 'com.github.GrenderG:Toasty:1.4.2' diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 2b7c9c5..3099ec6 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,16 +2,24 @@ + - + + + + + @@ -23,7 +31,7 @@ @@ -32,8 +40,8 @@ + android:name=".activities.AddEditActivity" + android:parentActivityName=".activities.MainActivity" /> () { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful() && task.getResult() != null) { + mLastLocation = task.getResult(); + latitude = 2; + + } else { + + //showSnackbar("No location detected. Make sure location is enabled on the device."); + } + } + }); + } + @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); @@ -129,10 +174,45 @@ protected void onActivityResult(int requestCode, int resultCode, @Nullable Inten String text = data.getStringExtra(AddEditActivity.EXTRA_TEXT); int priority = data.getIntExtra(AddEditActivity.EXTRA_PRIORITY, 1); Date pickedDate = (Date) data.getSerializableExtra(AddEditActivity.EXTRA_DATE); + double lat = data.getDoubleExtra(AddEditActivity.EXTRA_LAT, -500); + double lng = data.getDoubleExtra(AddEditActivity.EXTRA_LNG, -500); + if (mLastLocation == null) { + + latitude = -1; + longitude = -1; + } else { + latitude = mLastLocation.getLatitude(); + longitude = mLastLocation.getLongitude(); + } + if (lat != -500 && lng != -500) + { + latitude = lat; + longitude = lng; + } + try { + LatLng latLng = new LatLng(latitude, longitude); + Log.d("Location", String.valueOf(latitude)); + Log.d("Location", String.valueOf(longitude)); + List
addresses = geocoder.getFromLocation(latitude, longitude, 1); + if (addresses.size() > 0) { + Address address = addresses.get(0); + streetAddress = address.getAddressLine(0); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + Log.d("Hello", streetAddress); + } + catch (Exception e) + { + e.printStackTrace(); + } + Note note = new Note(text, pickedDate, priority,latitude,longitude, 0, streetAddress); - Note note = new Note(text, pickedDate, priority); noteViewModel.insert(note); - + //Toasty.success(this, streetAddress, Toast.LENGTH_SHORT).show(); + //Toasty.success(this, String.valueOf(latitude), Toast.LENGTH_SHORT).show(); Toasty.success(this, getString(R.string.activity_note_successfully_saved), Toast.LENGTH_SHORT).show(); } else if (requestCode == EDIT_NOTE_REQUEST && resultCode == RESULT_OK) { @@ -145,16 +225,18 @@ protected void onActivityResult(int requestCode, int resultCode, @Nullable Inten int priority = data.getIntExtra(AddEditActivity.EXTRA_PRIORITY, 1); Date pickedDate = (Date) data.getSerializableExtra(AddEditActivity.EXTRA_DATE); - Note note = new Note(text, pickedDate, priority); + Note note = new Note(text, pickedDate, priority,latitude,longitude, 0, streetAddress); note.setId(id); noteViewModel.update(note); + Toasty.info(this, getString(R.string.activity_update_message), Toast.LENGTH_SHORT).show(); } else { // Note not saved } } + @SuppressLint("RestrictedApi") @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); @@ -194,6 +276,13 @@ public boolean onOptionsItemSelected(MenuItem item) { case R.id.menu_sort_by_priority: noteViewModel.sortNotes(SORT_BY_PRIORITY); return true; + case R.id.menu_sort_by_distance: + Log.d("HELLO", "Sort by distance clicked!"); + noteViewModel.updateDistance(); + Log.d("Hello","Distance updated"); + noteViewModel.sortNotes(SORT_BY_DISTANCE); + Log.d("Hello","Sorted by distance"); + return true; default: return super.onOptionsItemSelected(item); } @@ -213,6 +302,8 @@ public void onItemClick(Note note) { intent.putExtra(AddEditActivity.EXTRA_TEXT, note.getNote()); intent.putExtra(AddEditActivity.EXTRA_DATE, note.getDate()); intent.putExtra(AddEditActivity.EXTRA_PRIORITY, note.getPriority()); + intent.putExtra(AddEditActivity.EXTRA_LAT, note.getLatitude()); + intent.putExtra(AddEditActivity.EXTRA_LNG, note.getLongitude()); startActivityForResult(intent, EDIT_NOTE_REQUEST); } } diff --git a/app/src/main/java/patryk/tasks/activities/MapsActivity.java b/app/src/main/java/patryk/tasks/activities/MapsActivity.java new file mode 100644 index 0000000..7db7638 --- /dev/null +++ b/app/src/main/java/patryk/tasks/activities/MapsActivity.java @@ -0,0 +1,333 @@ +package patryk.tasks.activities; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.fragment.app.FragmentActivity; + +import android.Manifest; +import android.app.Activity; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.location.Address; +import android.location.Location; +import android.location.Geocoder; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; + +import com.google.android.gms.common.api.ApiException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.maps.CameraUpdateFactory; +import com.google.android.gms.maps.GoogleMap; +import com.google.android.gms.maps.OnMapReadyCallback; +import com.google.android.gms.maps.SupportMapFragment; +import com.google.android.gms.maps.model.BitmapDescriptorFactory; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.gms.maps.model.Marker; +import com.google.android.gms.maps.model.MarkerOptions; + +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.OnSuccessListener; +import com.google.android.gms.tasks.Task; +import com.google.android.libraries.places.api.Places; +import com.google.android.libraries.places.api.model.Place; +import com.google.android.libraries.places.api.model.PlaceLikelihood; +import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest; +import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse; +import com.google.android.libraries.places.api.net.PlacesClient; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import patryk.tasks.R; + +public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener { + private GoogleMap mMap; + private Marker GlobalMarker; + private Geocoder geocoder; + // New variables for Current Place Picker + private static final String TAG = "MapsActivity"; + ListView lstPlaces; + private PlacesClient mPlacesClient; + private FusedLocationProviderClient mFusedLocationProviderClient; + + // The geographical location where the device is currently located. That is, the last-known + // location retrieved by the Fused Location Provider. + private Location mLastKnownLocation; + LatLng sydney; + // A default location (Sydney, Australia) and default zoom to use when location permission is + // not granted. + private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085); + private static final int DEFAULT_ZOOM = 15; + private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; + private boolean mLocationPermissionGranted; + + // Used for selecting the current place. + private static final int M_MAX_ENTRIES = 5; + private String[] mLikelyPlaceNames; + private String[] mLikelyPlaceAddresses; + private String[] mLikelyPlaceAttributions; + private LatLng[] mLikelyPlaceLatLngs; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_maps); + Log.d(TAG, "beirtgarden"); + sydney = getIntent().getExtras().getParcelable("Latlng"); + + // Obtain the SupportMapFragment and get notified when the map is ready to be used. + SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() + .findFragmentById(R.id.map); + mapFragment.getMapAsync(this); + geocoder = new Geocoder(this); + + + // Set up the action toolbar + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + // Set up the views + //lstPlaces = (ListView) findViewById(R.id.listPlaces); + + // Initialize the Places client + String apiKey = getString(R.string.google_maps_key); + Places.initialize(getApplicationContext(), apiKey); + mPlacesClient = Places.createClient(this); + mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); + } + + /** + * Populates the app bar with the menu. + */ + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu, menu); + + return super.onCreateOptionsMenu(menu); + } + + /** + * Handles user clicks on menu items. + */ + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + + case R.id.action_geolocate: + + // COMMENTED OUT UNTIL WE DEFINE THE METHOD + // Present the current place picker + pickCurrentPlace(); + return true; + + default: + // If we got here, the user's action was not recognized. + // Invoke the superclass to handle it. + return super.onOptionsItemSelected(item); + + } + } + + /** + * Prompts the user for permission to use the device location. + */ + private void getLocationPermission() { + /* + * Request location permission, so that we can get the location of the + * device. The result of the permission request is handled by a callback, + * onRequestPermissionsResult. + */ + mLocationPermissionGranted = false; + if (ContextCompat.checkSelfPermission(this.getApplicationContext(), + android.Manifest.permission.ACCESS_FINE_LOCATION) + == PackageManager.PERMISSION_GRANTED) { + mLocationPermissionGranted = true; + } else { + ActivityCompat.requestPermissions(this, + new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, + PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); + } + } + + + /** + * Manipulates the map once available. + * This callback is triggered when the map is ready to be used. + * This is where we can add markers or lines, add listeners or move the camera. In this case, + * we just add a marker near Sydney, Australia. + * If Google Play services is not installed on the device, the user will be prompted to install + * it inside the SupportMapFragment. This method will only be triggered once the user has + * installed Google Play services and returned to the app. + */ + @Override + public void onMapReady(GoogleMap googleMap) { + mMap = googleMap; + + // Add a marker in Sydney and move the camera + // LatLng sydney = new LatLng(-34, 151); + if(GlobalMarker!=null){ + GlobalMarker.remove(); + } + try { + List
addresses = geocoder.getFromLocation(sydney.latitude, sydney.longitude, 1); + if (addresses.size() > 0) { + Address address = addresses.get(0); + String streetAddress = address.getAddressLine(0); + GlobalMarker = mMap.addMarker(new MarkerOptions() + .position(sydney) + .title(streetAddress) + ); + mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, DEFAULT_ZOOM)); + } + } catch (IOException e) { + e.printStackTrace(); + } + + // + // PASTE THE LINES BELOW THIS COMMENT + // + + // Enable the zoom controls for the map + + mMap.getUiSettings().setZoomControlsEnabled(true); + mMap.setOnMapLongClickListener(this); + + + // Prompt the user for permission. + getLocationPermission(); + + } + + + + /** + * Get the current location of the device, and position the map's camera + */ + private void getDeviceLocation() { + /* + * Get the best and most recent location of the device, which may be null in rare + * cases when a location is not available. + */ + try { + if (mLocationPermissionGranted) { + Task locationResult = mFusedLocationProviderClient.getLastLocation(); + locationResult.addOnSuccessListener(this, new OnSuccessListener() { + @Override + public void onSuccess(Location location) { + if (location != null) { + // Set the map's camera position to the current location of the device. + mLastKnownLocation = location; + Log.d(TAG, "Latitude: " + mLastKnownLocation.getLatitude()); + Log.d(TAG, "Longitude: " + mLastKnownLocation.getLongitude()); + mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( + new LatLng(mLastKnownLocation.getLatitude(), + mLastKnownLocation.getLongitude()), DEFAULT_ZOOM)); + if(GlobalMarker!=null){ + GlobalMarker.remove(); + } + try { + LatLng latLng = new LatLng(mLastKnownLocation.getLatitude(), + mLastKnownLocation.getLongitude()); + List
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); + if (addresses.size() > 0) { + Address address = addresses.get(0); + String streetAddress = address.getAddressLine(0); + GlobalMarker = mMap.addMarker(new MarkerOptions() + .position(latLng) + .title(streetAddress) + ); + } + } catch (IOException e) { + e.printStackTrace(); + } + } else { + Log.d(TAG, "Current location is null. Using defaults."); + mMap.moveCamera(CameraUpdateFactory + .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM)); + + } + + } + }); + } + } catch (Exception e) { + Log.e("Exception: %s", e.getMessage()); + } + } + + /** + * Fetch a list of likely places, and show the current place on the map - provided the user + * has granted location permission. + */ + private void pickCurrentPlace() { + if (mMap == null) { + return; + } + + if (mLocationPermissionGranted) { + getDeviceLocation(); + } else { + // The user has not granted permission. + Log.i(TAG, "The user did not grant location permission."); + + // Add a default marker, because the user hasn't selected a place. + if(GlobalMarker!=null){ + GlobalMarker.remove(); + } + GlobalMarker = mMap.addMarker(new MarkerOptions() + .title(getString(R.string.default_info_title)) + .position(mDefaultLocation) + .snippet(getString(R.string.default_info_snippet))); + + // Prompt the user for permission. + getLocationPermission(); + } + } + + + + @Override + public void onMapLongClick(LatLng latLng) { + if(GlobalMarker!=null){ + GlobalMarker.remove(); + } + try { + List
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); + if (addresses.size() > 0) { + Address address = addresses.get(0); + String streetAddress = address.getAddressLine(0); + GlobalMarker = mMap.addMarker(new MarkerOptions() + .position(latLng) + .title(streetAddress) + ); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void sendLocationResult(View view){ + Intent resultIntent = new Intent(); + // TODO Add extras or a data URI to this intent as appropriate. + final LatLng latLng = GlobalMarker.getPosition(); + String streetAddress = GlobalMarker.getTitle(); + resultIntent.putExtra("streetAddress", streetAddress); + resultIntent.putExtra("latLng", latLng); + setResult(Activity.RESULT_OK, resultIntent); + finish(); + + } +} \ No newline at end of file diff --git a/app/src/main/java/patryk/tasks/activities/SearchActivity.java b/app/src/main/java/patryk/tasks/activities/SearchActivity.java new file mode 100644 index 0000000..3277d9a --- /dev/null +++ b/app/src/main/java/patryk/tasks/activities/SearchActivity.java @@ -0,0 +1,134 @@ +package patryk.tasks.activities; + +import androidx.appcompat.app.AppCompatActivity; + +import android.app.Activity; +import android.app.Dialog; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; +import android.widget.Toast; + +import com.google.android.gms.common.ConnectionResult; +import com.google.android.gms.common.GoogleApiAvailability; +import com.google.android.gms.common.api.Status; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.libraries.places.api.Places; +import com.google.android.libraries.places.api.model.Place; +import com.google.android.libraries.places.api.net.PlacesClient; +import com.google.android.libraries.places.widget.AutocompleteSupportFragment; +import com.google.android.libraries.places.widget.listener.PlaceSelectionListener; + +import java.util.Arrays; + +import patryk.tasks.R; + +public class SearchActivity extends AppCompatActivity { + + PlacesClient placesClient; + private final int MY_MAP_ACTIVITY = 200; + private static final String TAG = "SearchActivity"; + + private static final int ERROR_DIALOG_REQUEST = 9001; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_search); + + if(isServicesOK()){ + init(); + } + + } + + private void init(){ + String apiKey = getString(R.string.google_maps_key); + + // Setup Places Client + if (!Places.isInitialized()) { + Places.initialize(SearchActivity.this, apiKey); + } + // Retrieve a PlacesClient (previously initialized - see MainActivity) + placesClient = Places.createClient(this); + + final AutocompleteSupportFragment autocompleteSupportFragment = + (AutocompleteSupportFragment) + getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment); + + autocompleteSupportFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME,Place.Field.LAT_LNG,Place.Field.ADDRESS)); + + autocompleteSupportFragment.setOnPlaceSelectedListener( + new PlaceSelectionListener() { + @Override + public void onPlaceSelected(Place place) { + final LatLng latLng = place.getLatLng(); + Toast.makeText(SearchActivity.this, ""+latLng.latitude, Toast.LENGTH_SHORT).show(); + + Intent intent = new Intent(SearchActivity.this, MapsActivity.class); + intent.putExtra("Latlng", latLng); + startActivityForResult(intent, MY_MAP_ACTIVITY); + + } + + @Override + public void onError(Status status) { + Toast.makeText(SearchActivity.this, ""+status.getStatusMessage(), Toast.LENGTH_SHORT).show(); + } + }); +// Button btnMap = (Button) findViewById(R.id.btnMap); +// btnMap.setOnClickListener(new View.OnClickListener() { +// @Override +// public void onClick(View view) { +// Intent intent = new Intent(MainActivity.this, MapActivity.class); +// startActivity(intent); +// } +// }); + } + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + switch(requestCode) { + case (MY_MAP_ACTIVITY) : { + if (resultCode == Activity.RESULT_OK) { + // TODO Extract the data returned from the child Activity. + Bundle bundle = data.getExtras(); + LatLng selectedLocation = bundle.getParcelable("latLng"); + String streetAddress = bundle.getString("streetAddress"); + + Intent resultIntent = new Intent(); + // TODO Add extras or a data URI to this intent as appropriate. + resultIntent.putExtra("latLng", selectedLocation); + resultIntent.putExtra("streetAddress", streetAddress); + setResult(Activity.RESULT_OK, resultIntent); + finish(); + + } + break; + } + } + } + + public boolean isServicesOK(){ + Log.d(TAG, "isServicesOK: checking google services version"); + + int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(SearchActivity.this); + + if(available == ConnectionResult.SUCCESS){ + //everything is fine and the user can make map requests + Log.d(TAG, "isServicesOK: Google Play Services is working"); + return true; + } + else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){ + //an error occured but we can resolve it + Log.d(TAG, "isServicesOK: an error occured but we can fix it"); + Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(SearchActivity.this, available, ERROR_DIALOG_REQUEST); + dialog.show(); + }else{ + Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show(); + } + return false; + } + +} \ No newline at end of file diff --git a/app/src/main/java/patryk/tasks/adapters/NoteAdapter.java b/app/src/main/java/patryk/tasks/adapters/NoteAdapter.java index 3abef10..f20f2f7 100644 --- a/app/src/main/java/patryk/tasks/adapters/NoteAdapter.java +++ b/app/src/main/java/patryk/tasks/adapters/NoteAdapter.java @@ -56,6 +56,15 @@ public void onBindViewHolder(@NonNull NoteHolder holder, int position) { holder.note.setText(note.getNote()); holder.date.setText(dateFormat.format(note.getDate())); holder.priority.setText(String.format(context.getResources().getString(R.string.adapter_priority_formatted_string), note.getPriority())); + double latitude = note.getLatitude(); + //String lat = new Double(latitude).toString(); + String lat = String.format("%.2f", latitude); + //double longitude = note.getLongitude(); + //String lon = new Double(longitude).toString(); + //String lon = String.format("%.2f", longitude); + String lon = note.getStreetAddress(); + //holder.latitude.setText(lat); + holder.longitude.setText(lon); } public Note getNoteAt(int position) { @@ -72,6 +81,8 @@ public interface OnItemClickListener { public class NoteHolder extends RecyclerView.ViewHolder implements View.OnClickListener { + public TextView latitude; + public TextView longitude; private TextView note; private TextView date; private TextView priority; @@ -82,7 +93,8 @@ private NoteHolder(@NonNull View itemView) { note = itemView.findViewById(R.id.note); date = itemView.findViewById(R.id.date); priority = itemView.findViewById(R.id.priority); - + longitude = itemView.findViewById(R.id.longitude); + //latitude = itemView.findViewById(R.id.latitude); itemView.setOnClickListener(this); } diff --git a/app/src/main/java/patryk/tasks/database/NoteDB.java b/app/src/main/java/patryk/tasks/database/NoteDB.java index 028deec..4da8afa 100644 --- a/app/src/main/java/patryk/tasks/database/NoteDB.java +++ b/app/src/main/java/patryk/tasks/database/NoteDB.java @@ -22,7 +22,7 @@ import patryk.tasks.interfaces.NoteDao; import patryk.tasks.models.Note; -@Database(entities = Note.class, version = 1, exportSchema = false) +@Database(entities = Note.class, version = 2, exportSchema = false) @TypeConverters(Converters.class) public abstract class NoteDB extends RoomDatabase { @@ -75,7 +75,7 @@ protected Void doInBackground(Void... voids) { BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream)); String line; while ((line = reader.readLine()) != null) { - noteDao.insert(new Note(line, new Date(), 1)); + noteDao.insert(new Note(line, new Date(), 1,-1,-1, 0, "")); } reader.close(); } catch (IOException e) { diff --git a/app/src/main/java/patryk/tasks/interfaces/NoteDao.java b/app/src/main/java/patryk/tasks/interfaces/NoteDao.java index 12cd508..ef5cec9 100644 --- a/app/src/main/java/patryk/tasks/interfaces/NoteDao.java +++ b/app/src/main/java/patryk/tasks/interfaces/NoteDao.java @@ -32,6 +32,9 @@ public interface NoteDao { @Query("SELECT * FROM notes_table ORDER BY lower(note) ASC") LiveData> getNotesByName(); + @Query("SELECT * FROM notes_table ORDER BY distance ASC") + LiveData> getNotesByDistance(); + @Query("SELECT * FROM notes_table ORDER BY date ASC") LiveData> getNotesByDate(); } diff --git a/app/src/main/java/patryk/tasks/models/Note.java b/app/src/main/java/patryk/tasks/models/Note.java index 75ad28c..88d0b55 100644 --- a/app/src/main/java/patryk/tasks/models/Note.java +++ b/app/src/main/java/patryk/tasks/models/Note.java @@ -9,18 +9,33 @@ public class Note { @PrimaryKey(autoGenerate = true) - private int id; + public int id; - private String note; + public String note; - private Date date; + public Date date; - private int priority; + public int priority; - public Note(String note, Date date, int priority) { + public double latitude; + + private double longitude; + + public double distance; + + public String streetAddress; + + public Note(String note, Date date, int priority,double latitude,double longitude, double distance, String streetAddress) { this.note = note; this.date = date; this.priority = priority; + this.latitude = latitude; + //this.latitude = Math.random()*200-100; + this.longitude = longitude; + //this.longitude = Math.random()*200-100; + //this.distance = distance; + this.distance = Math.sqrt((this.longitude-81.86)*(this.longitude-81.86) + (this.latitude-25.45)*(this.latitude-25.45)); + this.streetAddress = streetAddress; } public int getId() { @@ -42,4 +57,27 @@ public Date getDate() { public int getPriority() { return priority; } + public double getLatitude(){ + return latitude; + } + + public double getLongitude() + { + return longitude; + } + + public double getDistance() + { + return distance; + } + + public void setDistance(double distance) + { + this.distance = distance; + } + + public String getStreetAddress() + { + return streetAddress; + } } diff --git a/app/src/main/java/patryk/tasks/repository/NoteRepository.java b/app/src/main/java/patryk/tasks/repository/NoteRepository.java index c1ae8f4..459b7da 100644 --- a/app/src/main/java/patryk/tasks/repository/NoteRepository.java +++ b/app/src/main/java/patryk/tasks/repository/NoteRepository.java @@ -63,6 +63,12 @@ public LiveData> getNotes() { return mNotes; } + public void updateDistance() { + Log.d("Hello", "In updateDistance() in NoteRepository.java"); + new UpdateDistanceAsyncTask(noteDao).execute(); + Log.d("Hello", "UpdateDistanceAsync finished"); + } + public void setSortingOrder(String order) { this.order.setValue(order); } @@ -80,6 +86,9 @@ private LiveData> getSortedNotes(String orderBy) { case "priority": sortedNotes = noteDao.getNotesByPriority(); break; + case "distance": + sortedNotes = noteDao.getNotesByDistance(); + break; default: // Wrong sorting parameter Log.w("SORTING", "Wrong sorting parameter in getSortedNotes(String orderBy). Available sorting order types: note, date, priority."); @@ -99,6 +108,7 @@ private InsertAsyncTask(NoteDao noteDao) { @Override protected Void doInBackground(Note... notes) { noteDao.insert(notes[0]); + Log.d("Hello", String.valueOf(notes[0].distance)); return null; } } @@ -118,6 +128,37 @@ protected Void doInBackground(Note... notes) { } } + private static class UpdateDistanceAsyncTask extends AsyncTask { + + private NoteDao noteDao; + + private UpdateDistanceAsyncTask(NoteDao noteDao) { + this.noteDao = noteDao; + } + @Override + protected Void doInBackground(Note... notes) { + //double lat1 = 37; + //double lng1 = 50; + //Log.d("Hello", String.valueOf(notes[0])); + //double lat2 = notes[0].getLatitude(); + //double lng2 = notes[0].getLongitude(); + //notes[0].distance = Math.sqrt((lng2-lng1)*(lng2-lng1) + (lat2-lat1)*(lat2-lat1)); + Log.d("Hello", String.valueOf(notes.length)); + for (int i = 0; i { private NoteDao noteDao; diff --git a/app/src/main/java/patryk/tasks/viewmodels/NoteViewModel.java b/app/src/main/java/patryk/tasks/viewmodels/NoteViewModel.java index fb6536d..ceb1ced 100644 --- a/app/src/main/java/patryk/tasks/viewmodels/NoteViewModel.java +++ b/app/src/main/java/patryk/tasks/viewmodels/NoteViewModel.java @@ -1,6 +1,7 @@ package patryk.tasks.viewmodels; import android.app.Application; +import android.util.Log; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; @@ -54,4 +55,10 @@ public LiveData> getNotes() { public void sortNotes(String orderBy) { repository.setSortingOrder(orderBy); } + + public void updateDistance() + { + Log.d("Hello", "In NoteViewModel.java"); + repository.updateDistance(); + } } diff --git a/app/src/main/res/drawable-hdpi/ic_icon_tranparentbg.png b/app/src/main/res/drawable-hdpi/ic_icon_tranparentbg.png new file mode 100644 index 0000000..b596b7e Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_icon_tranparentbg.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_icon_tranparentbg.png b/app/src/main/res/drawable-mdpi/ic_icon_tranparentbg.png new file mode 100644 index 0000000..088e81b Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_icon_tranparentbg.png differ diff --git a/app/src/main/res/drawable-v24/ic_geolocate.xml b/app/src/main/res/drawable-v24/ic_geolocate.xml new file mode 100644 index 0000000..f8ae310 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_geolocate.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable-xhdpi/ic_icon_tranparentbg.png b/app/src/main/res/drawable-xhdpi/ic_icon_tranparentbg.png new file mode 100644 index 0000000..6c50f22 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_icon_tranparentbg.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_icon_tranparentbg.png b/app/src/main/res/drawable-xxhdpi/ic_icon_tranparentbg.png new file mode 100644 index 0000000..8c7f67e Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_icon_tranparentbg.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_icon_tranparentbg.png b/app/src/main/res/drawable-xxxhdpi/ic_icon_tranparentbg.png new file mode 100644 index 0000000..04fea1e Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_icon_tranparentbg.png differ diff --git a/app/src/main/res/drawable/ic_icon_location.xml b/app/src/main/res/drawable/ic_icon_location.xml new file mode 100644 index 0000000..8306534 --- /dev/null +++ b/app/src/main/res/drawable/ic_icon_location.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_icon_sort.png b/app/src/main/res/drawable/ic_icon_sort.png new file mode 100644 index 0000000..72daa6f Binary files /dev/null and b/app/src/main/res/drawable/ic_icon_sort.png differ diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 8b8eec2..36035e4 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -20,7 +20,7 @@ android:layout_height="wrap_content" android:layout_gravity="center" android:adjustViewBounds="true" - android:src="@drawable/empty" + android:src="@drawable/ic_icon_tranparentbg" android:visibility="gone" /> + + + + + +