Repository: ImangazalievM/Notelin Branch: master Commit: 9eea4d499727 Files: 44 Total size: 47.9 KB Directory structure: gitextract_kamnq6du/ ├── .gitignore ├── README.md ├── app/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── kotlin/ │ │ │ └── com/ │ │ │ └── imangazaliev/ │ │ │ └── notelin/ │ │ │ ├── NotelinApplication.kt │ │ │ ├── bus/ │ │ │ │ ├── NoteDeleteAction.kt │ │ │ │ └── NoteEditAction.kt │ │ │ ├── di/ │ │ │ │ ├── AppComponent.kt │ │ │ │ └── NoteDaoModule.kt │ │ │ ├── mvp/ │ │ │ │ ├── model/ │ │ │ │ │ ├── AppDatabase.kt │ │ │ │ │ ├── Note.kt │ │ │ │ │ └── NoteDao.kt │ │ │ │ ├── presenters/ │ │ │ │ │ ├── MainPresenter.kt │ │ │ │ │ └── NotePresenter.kt │ │ │ │ └── views/ │ │ │ │ ├── MainView.kt │ │ │ │ └── NoteView.kt │ │ │ ├── ui/ │ │ │ │ ├── activities/ │ │ │ │ │ ├── MainActivity.kt │ │ │ │ │ └── NoteActivity.kt │ │ │ │ ├── adapters/ │ │ │ │ │ └── NotesAdapter.kt │ │ │ │ └── commons/ │ │ │ │ └── ItemClickSupport.kt │ │ │ └── utils/ │ │ │ ├── DateUtils.kt │ │ │ └── PrefsUtils.kt │ │ └── res/ │ │ ├── layout/ │ │ │ ├── activity_main.xml │ │ │ ├── activity_note.xml │ │ │ ├── note_info_dialog.xml │ │ │ └── note_item_layout.xml │ │ ├── menu/ │ │ │ ├── main.xml │ │ │ └── note.xml │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── ids.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── values-w820dp/ │ │ └── dimens.xml │ └── test/ │ └── kotlin/ │ └── imangazaliev/ │ └── notelin/ │ └── ExampleUnitTest.java ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /.idea /Notelin.iml .gradle /local.properties .DS_Store /build /captures /.idea/ ================================================ FILE: README.md ================================================ ![Image](https://raw.githubusercontent.com/ImangazalievM/Notelin/master/art/splash.png) Libraries and tools included: - Google AppCompat Support Libraries - Google Material Design Support Libraries - [ReActiveAndroid](https://github.com/ImangazalievM/ReActiveAndroid) - for persistence - [Eventbus](https://github.com/greenrobot/EventBus) - for change notifications - [Material Dialogs](https://github.com/afollestad/material-dialogs) - for dialogs - [Dagger 2](https://github.com/google/dagger) - for dependency injection - [Moxy](https://github.com/Arello-Mobile/Moxy) - for MVP pattern implementation ## License ``` The MIT License Copyright (c) 2017 Mahach Imangazaliev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 26 buildToolsVersion "27.0.1" defaultConfig { applicationId "com.com.imangazaliev.notelin" minSdkVersion 16 targetSdkVersion 26 versionCode 2 versionName "1.1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } sourceSets { main.java.srcDirs += 'src/main/kotlin' androidTest.java.srcDirs += 'src/androidTest/kotlin' } } dependencies { implementation "com.android.support:appcompat-v7:26.1.0" implementation "com.android.support:recyclerview-v7:26.1.0" implementation "com.android.support:cardview-v7:26.1.0" implementation "com.android.support:design:26.1.0" implementation "com.pawegio.kandroid:kandroid:0.8.5@aar" implementation "com.arello-mobile:moxy:1.5.3" implementation 'com.arello-mobile:moxy-app-compat:1.5.3' kapt 'com.arello-mobile:moxy-compiler:1.5.3' implementation "com.reactiveandroid:reactiveandroid:1.2.1" implementation "org.greenrobot:eventbus:3.0.0" implementation "com.github.afollestad.material-dialogs:core:0.8.5.6@aar" kapt "com.google.dagger:dagger-compiler:2.11" implementation "com.google.dagger:dagger:2.11" compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } repositories { mavenCentral() } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in D:\Mahach\AndroidDeveloment\Programms\sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/NotelinApplication.kt ================================================ package com.imangazaliev.notelin import android.annotation.SuppressLint import android.app.Application import android.content.Context import com.imangazaliev.notelin.di.AppComponent import com.imangazaliev.notelin.di.DaggerAppComponent import com.imangazaliev.notelin.di.NoteDaoModule import com.imangazaliev.notelin.mvp.model.AppDatabase import com.imangazaliev.notelin.mvp.model.Note import com.reactiveandroid.ReActiveAndroid import com.reactiveandroid.ReActiveConfig import com.reactiveandroid.internal.database.DatabaseConfig class NotelinApplication : Application() { companion object { lateinit var graph: AppComponent @SuppressLint("StaticFieldLeak") lateinit var context: Context } override fun onCreate() { super.onCreate() context = this graph = DaggerAppComponent.builder().noteDaoModule(NoteDaoModule()).build() val appDatabaseConfig = DatabaseConfig.Builder(AppDatabase::class.java) .addModelClasses(Note::class.java) .build() ReActiveAndroid.init(ReActiveConfig.Builder(this) .addDatabaseConfigs(appDatabaseConfig) .build()) } } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/bus/NoteDeleteAction.kt ================================================ package com.imangazaliev.notelin.bus class NoteDeleteAction(val noteId: Long) ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/bus/NoteEditAction.kt ================================================ package com.imangazaliev.notelin.bus class NoteEditAction(val noteId: Long) ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/di/AppComponent.kt ================================================ package com.imangazaliev.notelin.di import dagger.Component import com.imangazaliev.notelin.mvp.presenters.MainPresenter import com.imangazaliev.notelin.mvp.presenters.NotePresenter import javax.inject.Singleton @Singleton @Component(modules = [NoteDaoModule::class]) interface AppComponent { fun inject(mainPresenter: MainPresenter) fun inject(notePresenter: NotePresenter) } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/di/NoteDaoModule.kt ================================================ package com.imangazaliev.notelin.di import dagger.Module import dagger.Provides import com.imangazaliev.notelin.mvp.model.NoteDao import javax.inject.Singleton @Module class NoteDaoModule { @Provides @Singleton fun provideNoteDao(): NoteDao = NoteDao() } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/mvp/model/AppDatabase.kt ================================================ package com.imangazaliev.notelin.mvp.model import com.reactiveandroid.annotation.Database @Database(name = "AppDatabase", version = 1) class AppDatabase ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/mvp/model/Note.kt ================================================ package com.imangazaliev.notelin.mvp.model import com.imangazaliev.notelin.utils.formatDate import com.reactiveandroid.Model import com.reactiveandroid.annotation.Column import com.reactiveandroid.annotation.PrimaryKey import com.reactiveandroid.annotation.Table import java.util.* @Table(name = "Notes", database = AppDatabase::class) class Note : Model { @PrimaryKey var id: Long = 0 @Column(name = "title") var title: String? = null @Column(name = "text") var text: String? = null @Column(name = "created_at") var createAt: Date? = null @Column(name = "change_at") var changedAt: Date? = null constructor(title: String, createDate: Date) { this.title = title this.createAt = createDate this.changedAt = createDate } constructor() fun getInfo(): String = "Title:\n$title\n" + "Created at:\n${formatDate(createAt)}\n" + "Changed at:\n${formatDate(changedAt)}" } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/mvp/model/NoteDao.kt ================================================ package com.imangazaliev.notelin.mvp.model import com.reactiveandroid.query.Delete import com.reactiveandroid.query.Select import org.jetbrains.annotations.Nullable import java.util.* class NoteDao { fun createNote(): Note { val note = Note("New note", Date()) note.save() return note } fun saveNote(note: Note): Long = note.save() fun loadAllNotes(): MutableList = Select.from(Note::class.java).fetch() fun getNoteById(noteId: Long): Note? = Select.from(Note::class.java).where("id = ?", noteId).fetchSingle() fun deleteAllNotes() = Delete.from(Note::class.java).execute() fun deleteNote(note: Note) = note.delete() } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/mvp/presenters/MainPresenter.kt ================================================ package com.imangazaliev.notelin.mvp.presenters import android.util.Log import com.arellomobile.mvp.InjectViewState import com.arellomobile.mvp.MvpPresenter import com.imangazaliev.notelin.NotelinApplication import com.imangazaliev.notelin.bus.NoteDeleteAction import com.imangazaliev.notelin.bus.NoteEditAction import com.imangazaliev.notelin.mvp.model.Note import com.imangazaliev.notelin.mvp.model.NoteDao import com.imangazaliev.notelin.mvp.views.MainView import com.imangazaliev.notelin.utils.getNotesSortMethodName import com.imangazaliev.notelin.utils.setNotesSortMethod import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import java.util.* import javax.inject.Inject @InjectViewState class MainPresenter : MvpPresenter() { enum class SortNotesBy : Comparator { DATE { override fun compare(note1: Note, note2: Note) = note1.changedAt!!.compareTo(note2.changedAt) }, NAME { override fun compare(note1: Note, note2: Note) = note1.title!!.compareTo(note2.title!!) }, } @Inject lateinit var noteDao: NoteDao private lateinit var notesList: MutableList init { NotelinApplication.graph.inject(this) EventBus.getDefault().register(this) } override fun onFirstViewAttach() { super.onFirstViewAttach() loadAllNotes() } fun deleteAllNotes() { noteDao.deleteAllNotes() notesList.removeAll(notesList) viewState.onAllNotesDeleted() } fun deleteNoteByPosition(position: Int) { val note = notesList[position] noteDao.deleteNote(note) notesList.remove(note) viewState.onNoteDeleted() } fun openNewNote() { val newNote = noteDao.createNote() notesList.add(newNote) sortNotesBy(getCurrentSortMethod()) viewState.openNoteScreen(newNote.id) } fun openNote(position: Int) { viewState.openNoteScreen(notesList[position].id) } fun search(query: String) { if (query == "") { viewState.onSearchResult(notesList) } else { val searchResults = notesList.filter { it.title!!.startsWith(query, ignoreCase = true) } viewState.onSearchResult(searchResults) } } fun sortNotesBy(sortMethod: SortNotesBy) { notesList.sortWith(sortMethod) setNotesSortMethod(sortMethod.toString()) viewState.updateView() } @Subscribe fun onNoteEdit(action: NoteEditAction) { val notePosition = getNotePositionById(action.noteId) notesList[notePosition] = noteDao.getNoteById(action.noteId)!! sortNotesBy(getCurrentSortMethod()) } @Subscribe fun onNoteDelete(action: NoteDeleteAction) { Log.d("Notelin", "onDeleted" + action.noteId); val notePosition = getNotePositionById(action.noteId) notesList.removeAt(notePosition) viewState.updateView() } fun showNoteContextDialog(position: Int) { viewState.showNoteContextDialog(position) } fun hideNoteContextDialog() { viewState.hideNoteContextDialog() } fun showNoteDeleteDialog(position: Int) { viewState.showNoteDeleteDialog(position) } fun hideNoteDeleteDialog() { viewState.hideNoteDeleteDialog() } fun showNoteInfo(position: Int) { viewState.showNoteInfoDialog(notesList[position].getInfo()) } fun hideNoteInfoDialog() { viewState.hideNoteInfoDialog() } private fun loadAllNotes() { notesList = noteDao.loadAllNotes() Collections.sort(notesList, getCurrentSortMethod()) viewState.onNotesLoaded(notesList) } private fun getCurrentSortMethod(): SortNotesBy { val defaultSortMethodName = SortNotesBy.DATE.toString() val currentSortMethodName = getNotesSortMethodName(defaultSortMethodName) return SortNotesBy.valueOf(currentSortMethodName) } private fun getNotePositionById(noteId: Long) = notesList.indexOfFirst { it.id == noteId } } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/mvp/presenters/NotePresenter.kt ================================================ package com.imangazaliev.notelin.mvp.presenters import com.arellomobile.mvp.InjectViewState import com.arellomobile.mvp.MvpPresenter import com.imangazaliev.notelin.NotelinApplication import com.imangazaliev.notelin.bus.NoteDeleteAction import com.imangazaliev.notelin.bus.NoteEditAction import com.imangazaliev.notelin.mvp.model.Note import com.imangazaliev.notelin.mvp.model.NoteDao import com.imangazaliev.notelin.mvp.views.NoteView import org.greenrobot.eventbus.EventBus import java.util.* import javax.inject.Inject @InjectViewState class NotePresenter(val noteId: Long) : MvpPresenter() { @Inject lateinit var noteDao: NoteDao private lateinit var note: Note init { NotelinApplication.graph.inject(this) } override fun onFirstViewAttach() { super.onFirstViewAttach() note = noteDao.getNoteById(noteId)!! viewState.showNote(note) } fun saveNote(title: String, text: String) { note.title = title note.text = text note.changedAt = Date() noteDao.saveNote(note) EventBus.getDefault().post(NoteEditAction(note.id)) viewState.onNoteSaved() } fun deleteNote() { //after deletion note id will be 0, // so we should save one before delete operation val noteId = note.id noteDao.deleteNote(note) EventBus.getDefault().post(NoteDeleteAction(noteId)) viewState.onNoteDeleted() } fun showNoteDeleteDialog() { viewState.showNoteDeleteDialog() } fun hideNoteDeleteDialog() { viewState.hideNoteDeleteDialog() } fun showNoteInfoDialog() { viewState.showNoteInfoDialog(note.getInfo()) } fun hideNoteInfoDialog() { viewState.hideNoteInfoDialog() } } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/mvp/views/MainView.kt ================================================ package com.imangazaliev.notelin.mvp.views import com.arellomobile.mvp.MvpView import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy import com.arellomobile.mvp.viewstate.strategy.StateStrategyType import com.imangazaliev.notelin.mvp.model.Note @StateStrategyType(value = AddToEndSingleStrategy::class) interface MainView : MvpView { fun onNotesLoaded(notes: List) fun updateView() fun onSearchResult(notes: List) fun onAllNotesDeleted() fun onNoteDeleted() fun showNoteInfoDialog(noteInfo: String) fun hideNoteInfoDialog() fun showNoteDeleteDialog(notePosition: Int) fun hideNoteDeleteDialog() fun showNoteContextDialog(notePosition: Int) fun hideNoteContextDialog() fun openNoteScreen(noteId: Long) } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/mvp/views/NoteView.kt ================================================ package com.imangazaliev.notelin.mvp.views import com.arellomobile.mvp.MvpView import com.imangazaliev.notelin.mvp.model.Note interface NoteView : MvpView { fun showNote(note: Note) fun onNoteSaved() fun onNoteDeleted() fun showNoteInfoDialog(noteInfo: String) fun hideNoteInfoDialog() fun showNoteDeleteDialog() fun hideNoteDeleteDialog() } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/ui/activities/MainActivity.kt ================================================ package com.imangazaliev.notelin.ui.activities import android.os.Bundle import android.support.v7.widget.SearchView import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import com.afollestad.materialdialogs.MaterialDialog import com.arellomobile.mvp.MvpAppCompatActivity import com.arellomobile.mvp.presenter.InjectPresenter import com.pawegio.kandroid.onQueryChange import com.imangazaliev.notelin.R import com.imangazaliev.notelin.mvp.model.Note import com.imangazaliev.notelin.mvp.presenters.MainPresenter import com.imangazaliev.notelin.mvp.views.MainView import com.imangazaliev.notelin.ui.adapters.NotesAdapter import com.imangazaliev.notelin.ui.commons.ItemClickSupport import kotlinx.android.synthetic.main.activity_main.* class MainActivity : MvpAppCompatActivity(), MainView { @InjectPresenter lateinit var presenter: MainPresenter private var noteContextDialog: MaterialDialog? = null private var noteDeleteDialog: MaterialDialog? = null private var noteInfoDialog: MaterialDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) with(ItemClickSupport.addTo(notesList)) { setOnItemClickListener { _, position, _ -> presenter.openNote(position) } setOnItemLongClickListener { _, position, _ -> presenter.showNoteContextDialog(position); true } } newNoteFab.setOnClickListener { presenter.openNewNote() } } override fun onNotesLoaded(notes: List) { notesList.adapter = NotesAdapter(notes) updateView() } override fun updateView() { notesList.adapter.notifyDataSetChanged() if (notesList.adapter.itemCount == 0) { notesList.visibility = View.GONE tvNotesIsEmpty.visibility = View.VISIBLE } else { notesList.visibility = View.VISIBLE tvNotesIsEmpty.visibility = View.GONE } } override fun onNoteDeleted() { updateView() Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show() } override fun onAllNotesDeleted() { updateView() Toast.makeText(this, R.string.all_notes_deleted, Toast.LENGTH_SHORT).show() } override fun onSearchResult(notes: List) { notesList.adapter = NotesAdapter(notes) } override fun showNoteContextDialog(notePosition: Int) { noteContextDialog = MaterialDialog.Builder(this) .items(R.array.main_note_context) .itemsCallback { _, _, position, _ -> onContextDialogItemClick(position, notePosition) presenter.hideNoteContextDialog() } .cancelListener { presenter.hideNoteContextDialog() } .show() } override fun hideNoteContextDialog() { noteContextDialog?.dismiss() } override fun showNoteDeleteDialog(notePosition: Int) { noteDeleteDialog = MaterialDialog.Builder(this) .title(getString(R.string.note_deletion_title)) .content(getString(R.string.note_deletion_message)) .positiveText(getString(R.string.yes)) .negativeText(getString(R.string.no)) .onPositive { _, _ -> presenter.deleteNoteByPosition(notePosition) noteInfoDialog?.dismiss() } .onNegative { _, _ -> presenter.hideNoteDeleteDialog() } .cancelListener { presenter.hideNoteDeleteDialog() } .show() } override fun hideNoteDeleteDialog() { noteDeleteDialog?.dismiss() } override fun showNoteInfoDialog(noteInfo: String) { noteInfoDialog = MaterialDialog.Builder(this) .title(R.string.note_info) .positiveText(getString(R.string.ok)) .content(noteInfo) .onPositive { materialDialog, dialogAction -> presenter.hideNoteInfoDialog() } .cancelListener { presenter.hideNoteInfoDialog() } .show() } override fun hideNoteInfoDialog() { noteInfoDialog?.dismiss() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) initSearchView(menu) return true } override fun openNoteScreen(noteId: Long) { startActivity(NoteActivity.buildIntent(this, noteId)) } private fun initSearchView(menu: Menu) { val searchViewMenuItem = menu.findItem(R.id.action_search) val searchView = searchViewMenuItem.actionView as SearchView searchView.onQueryChange { query -> presenter.search(query) } searchView.setOnCloseListener { presenter.search(""); false } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuDeleteAllNotes -> presenter.deleteAllNotes() R.id.menuSortByName -> presenter.sortNotesBy(MainPresenter.SortNotesBy.NAME) R.id.menuSortByDate -> presenter.sortNotesBy(MainPresenter.SortNotesBy.DATE) } return super.onOptionsItemSelected(item) } private fun onContextDialogItemClick(contextItemPosition: Int, notePosition: Int) { when (contextItemPosition) { 0 -> presenter.openNote(notePosition) 1 -> presenter.showNoteInfo(notePosition) 2 -> presenter.showNoteDeleteDialog(notePosition) } } } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/ui/activities/NoteActivity.kt ================================================ package com.imangazaliev.notelin.ui.activities import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.EditText import android.widget.Toast import com.afollestad.materialdialogs.MaterialDialog import com.arellomobile.mvp.MvpAppCompatActivity import com.arellomobile.mvp.presenter.InjectPresenter import com.arellomobile.mvp.presenter.ProvidePresenter import com.imangazaliev.notelin.R import com.imangazaliev.notelin.mvp.model.Note import com.imangazaliev.notelin.mvp.presenters.NotePresenter import com.imangazaliev.notelin.mvp.views.NoteView import com.imangazaliev.notelin.utils.formatDate import kotlinx.android.synthetic.main.activity_note.* class NoteActivity : MvpAppCompatActivity(), NoteView { companion object { const val NOTE_DELETE_ARG = "note_id" fun buildIntent(activity: Activity, noteId: Long) : Intent{ val intent = Intent(activity, NoteActivity::class.java) intent.putExtra(NOTE_DELETE_ARG, noteId) return intent } } @InjectPresenter lateinit var presenter: NotePresenter private var noteDeleteDialog: MaterialDialog? = null private var noteInfoDialog: MaterialDialog? = null @ProvidePresenter fun provideHelloPresenter(): NotePresenter { val noteId = intent.extras.getLong(NOTE_DELETE_ARG, -1) return NotePresenter(noteId) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_note) etTitle.onFocusChangeListener = View.OnFocusChangeListener { view, hasFocus -> if (hasFocus) { val editText = view as EditText editText.setSelection((editText.text.length)) } } } override fun showNote(note: Note) { tvNoteDate.text = formatDate(note.changedAt) etTitle.setText(note.title) etText.setText(note.text) } override fun showNoteInfoDialog(noteInfo: String) { noteInfoDialog = MaterialDialog.Builder(this) .title(R.string.note_info) .positiveText(R.string.ok) .content(noteInfo) .onPositive { materialDialog, dialogAction -> presenter.hideNoteInfoDialog() } .cancelListener { presenter.hideNoteInfoDialog() } .show() } override fun hideNoteInfoDialog() { noteInfoDialog?.dismiss() } override fun showNoteDeleteDialog() { noteDeleteDialog = MaterialDialog.Builder(this) .title(getString(R.string.note_deletion_title)) .content(getString(R.string.note_deletion_message)) .positiveText(getString(R.string.yes)) .negativeText(getString(R.string.no)) .onPositive { _, _ -> presenter.hideNoteDeleteDialog() presenter.deleteNote() } .onNegative { _, _ -> presenter.hideNoteDeleteDialog() } .cancelListener { presenter.hideNoteDeleteDialog() } .show() } override fun hideNoteDeleteDialog() { noteDeleteDialog?.dismiss() } override fun onNoteSaved() { Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show() } override fun onNoteDeleted() { Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show() finish() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.note, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuSaveNote -> presenter.saveNote(etTitle.text.toString(), etText.text.toString()) R.id.menuDeleteNote -> presenter.showNoteDeleteDialog() R.id.menuNoteInfo -> presenter.showNoteInfoDialog() } return super.onOptionsItemSelected(item) } } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/ui/adapters/NotesAdapter.kt ================================================ package com.imangazaliev.notelin.ui.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.imangazaliev.notelin.R import com.imangazaliev.notelin.mvp.model.Note import com.imangazaliev.notelin.utils.formatDate class NotesAdapter(private val notesList: List) : RecyclerView.Adapter() { override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): NotesAdapter.ViewHolder { val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.note_item_layout, viewGroup, false) return NotesAdapter.ViewHolder(v) } override fun onBindViewHolder(viewHolder: NotesAdapter.ViewHolder, i: Int) { val note = notesList[i] viewHolder.noteTitle.text = note.title viewHolder.noteDate.text = formatDate(note.changedAt) } override fun getItemCount(): Int { return notesList.size } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var noteTitle: TextView = itemView.findViewById(R.id.tvItemNoteTitle) as TextView var noteDate: TextView = itemView.findViewById(R.id.tvItemNoteDate) as TextView } } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/ui/commons/ItemClickSupport.kt ================================================ package com.imangazaliev.notelin.ui.commons import android.support.v7.widget.RecyclerView import android.view.View import com.imangazaliev.notelin.R class ItemClickSupport private constructor(private val recyclerView: RecyclerView) { companion object { fun addTo(view: RecyclerView) = view.getTag(R.id.item_click_support) as? ItemClickSupport ?: ItemClickSupport(view) fun removeFrom(view: RecyclerView): ItemClickSupport? { val support = view.getTag(R.id.item_click_support) as? ItemClickSupport support?.detach(view) return support } } interface ItemClickListener { fun onClick(recyclerView: RecyclerView, position: Int, view: View) } interface ItemLongClickListener { fun onLongClick(recyclerView: RecyclerView, position: Int, view: View): Boolean } private var itemClickListener: ItemClickListener? = null private var itemLongClickListener: ItemLongClickListener? = null private val onClickListener = View.OnClickListener { val holder = recyclerView.getChildViewHolder(it) itemClickListener?.onClick(recyclerView, holder.adapterPosition, it) } private val onLongClickListener = View.OnLongClickListener listener@{ val position = recyclerView.getChildViewHolder(it).adapterPosition return@listener itemLongClickListener?.onLongClick(recyclerView, position, it) ?: false } private val attachListener = object : RecyclerView.OnChildAttachStateChangeListener { override fun onChildViewAttachedToWindow(view: View) { if (itemClickListener != null) { view.setOnClickListener(onClickListener) } if (itemLongClickListener != null) { view.setOnLongClickListener(onLongClickListener) } } override fun onChildViewDetachedFromWindow(view: View) = Unit } init { recyclerView.setTag(R.id.item_click_support, this) recyclerView.addOnChildAttachStateChangeListener(attachListener) } fun setOnItemClickListener(listener: ItemClickListener): ItemClickSupport { itemClickListener = listener return this } fun setOnItemClickListener(listener: (RecyclerView, Int, View) -> Unit) = setOnItemClickListener(object : ItemClickListener { override fun onClick(recyclerView: RecyclerView, position: Int, view: View) { listener(recyclerView, position, view) } }) fun setOnItemLongClickListener(listener: ItemLongClickListener): ItemClickSupport { itemLongClickListener = listener return this } fun setOnItemLongClickListener(block: (RecyclerView, Int, View) -> Boolean): ItemClickSupport = setOnItemLongClickListener(object : ItemLongClickListener { override fun onLongClick(recyclerView: RecyclerView, position: Int, view: View): Boolean { return block (recyclerView, position, view) } }) private fun detach(view: RecyclerView) { view.removeOnChildAttachStateChangeListener(attachListener) view.setTag(R.id.item_click_support, null) } } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/utils/DateUtils.kt ================================================ @file:JvmName("DateUtils") package com.imangazaliev.notelin.utils import java.text.SimpleDateFormat import java.util.* fun formatDate(date: Date?): String { val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm") return dateFormat.format(date) } ================================================ FILE: app/src/main/kotlin/com/imangazaliev/notelin/utils/PrefsUtils.kt ================================================ @file:JvmName("PrefsUtils") package com.imangazaliev.notelin.utils import android.content.Context import com.imangazaliev.notelin.NotelinApplication private val prefs by lazy { NotelinApplication.context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE) } fun getNotesSortMethodName(defaultValue: String): String = prefs.getString("sort_method", defaultValue) fun setNotesSortMethod(sortMethod: String) { prefs.edit().putString("sort_method", sortMethod).apply() } ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_note.xml ================================================ ================================================ FILE: app/src/main/res/layout/note_info_dialog.xml ================================================ ================================================ FILE: app/src/main/res/layout/note_item_layout.xml ================================================ ================================================ FILE: app/src/main/res/menu/main.xml ================================================ ================================================ FILE: app/src/main/res/menu/note.xml ================================================ ================================================ FILE: app/src/main/res/values/colors.xml ================================================ #5E9E76 #3b8657 #5E9E76 ================================================ FILE: app/src/main/res/values/dimens.xml ================================================ 16dp 16dp ================================================ FILE: app/src/main/res/values/ids.xml ================================================ ================================================ FILE: app/src/main/res/values/strings.xml ================================================ Notelin All notes deleted Delete Delete all Input your text... No Note deleted Note deletion Do you want to delete this note? Information No notes found OK Save Search Sort by Title Date Title Yes Open @string/note_info @string/delete ================================================ FILE: app/src/main/res/values/styles.xml ================================================ ================================================ FILE: app/src/main/res/values-w820dp/dimens.xml ================================================ 64dp ================================================ FILE: app/src/test/kotlin/imangazaliev/notelin/ExampleUnitTest.java ================================================ package com.imangazaliev.notelin; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } } ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.2.0' repositories { jcenter() mavenCentral() maven { url 'https://maven.google.com' } google() } dependencies { classpath 'com.android.tools.build:gradle:3.1.0-alpha04' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { jcenter() mavenCentral() maven { url "https://jitpack.io" } maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' } google() } } task clean(type: Delete) { delete rootProject.buildDir } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Fri Dec 01 08:07:32 MSK 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions-snapshots/gradle-4.4-20171031235950+0000-all.zip ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle ================================================ include ':app'