Skip to content

Commit

Permalink
Add RoomWordsWithUpdate
Browse files Browse the repository at this point in the history
  • Loading branch information
alekshaecky committed Jun 15, 2018
1 parent 3ccb1e7 commit f088809
Show file tree
Hide file tree
Showing 43 changed files with 1,794 additions and 0 deletions.
1 change: 1 addition & 0 deletions RoomWordsWithUpdate/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
49 changes: 49 additions & 0 deletions RoomWordsWithUpdate/app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright (C) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

apply plugin: 'com.android.application'

android {
compileSdkVersion 27
defaultConfig {
applicationId "com.android.example.roomwordssampleupdate"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.android.support:design:27.1.1'

// Room components
implementation "android.arch.persistence.room:runtime:$rootProject.roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"

// Lifecycle components
implementation "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
annotationProcessor "android.arch.lifecycle:compiler:$rootProject.archLifecycleVersion"
}
21 changes: 21 additions & 0 deletions RoomWordsWithUpdate/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# 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 *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
42 changes: 42 additions & 0 deletions RoomWordsWithUpdate/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>

<!-- Copyright 2018 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.example.roomwordssample">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.android.example.roomwordssample.MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.android.example.roomwordssample.NewWordActivity"
android:label="@string/app_name" />
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
/*
* Copyright (C) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.android.example.roomwordssample;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import java.util.List;

/**
* This class displays a list of words in a RecyclerView.
* The words are saved in a Room database.
* The layout for this activity also displays a FAB that
* allows users to start the NewWordActivity to add new words.
* Users can delete a word by swiping it away, or delete all words
* through the Options menu.
* Whenever a new word is added, deleted, or updated, the RecyclerView
* showing the list of words automatically updates.
*/
public class MainActivity extends AppCompatActivity {

public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
public static final int UPDATE_WORD_ACTIVITY_REQUEST_CODE = 2;

public static final String EXTRA_DATA_UPDATE_WORD = "extra_word_to_be_updated";
public static final String EXTRA_DATA_ID = "extra_data_id";

private WordViewModel mWordViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

// Set up the RecyclerView.
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final WordListAdapter adapter = new WordListAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

// Set up the WordViewModel.
mWordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);
// Get all the words from the database
// and associate them to the adapter.
mWordViewModel.getAllWords().observe(this, new Observer<List<Word>>() {
@Override
public void onChanged(@Nullable final List<Word> words) {
// Update the cached copy of the words in the adapter.
adapter.setWords(words);
}
});

// Floating action button setup
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, NewWordActivity.class);
startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);
}
});

// Add the functionality to swipe items in the
// RecyclerView to delete the swiped item.
ItemTouchHelper helper = new ItemTouchHelper(
new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
// We are not implementing onMove() in this app.
public boolean onMove(RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
return false;
}

@Override
// When the use swipes a word,
// delete that word from the database.
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
Word myWord = adapter.getWordAtPosition(position);
Toast.makeText(MainActivity.this,
getString(R.string.delete_word_preamble) + " " +
myWord.getWord(), Toast.LENGTH_LONG).show();

// Delete the word.
mWordViewModel.deleteWord(myWord);
}
});
// Attach the item touch helper to the recycler view.
helper.attachToRecyclerView(recyclerView);

adapter.setOnItemClickListener(new WordListAdapter.ClickListener() {

@Override
public void onItemClick(View v, int position) {
Word word = adapter.getWordAtPosition(position);
launchUpdateWordActivity(word);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

// The options menu has a single item "Clear all data now"
// that deletes all the entries in the database.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, as long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.clear_data) {
// Add a toast just for confirmation
Toast.makeText(this, R.string.clear_data_toast_text, Toast.LENGTH_LONG).show();

// Delete the existing data.
mWordViewModel.deleteAll();
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* When the user enters a new word in the NewWordActivity,
* that activity returns the result to this activity.
* If the user entered a new word, save it in the database.
* @param requestCode ID for the request
* @param resultCode indicates success or failure
* @param data The Intent sent back from the NewWordActivity,
* which includes the word that the user entered
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
Word word = new Word(data.getStringExtra(NewWordActivity.EXTRA_REPLY));
// Save the data.
mWordViewModel.insert(word);
} else if (requestCode == UPDATE_WORD_ACTIVITY_REQUEST_CODE
&& resultCode == RESULT_OK) {
String word_data = data.getStringExtra(NewWordActivity.EXTRA_REPLY);
int id = data.getIntExtra(NewWordActivity.EXTRA_REPLY_ID, -1);

if (id != -1) {
mWordViewModel.update(new Word(id, word_data));
} else {
Toast.makeText(this, R.string.unable_to_update,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(
this, R.string.empty_not_saved, Toast.LENGTH_LONG).show();
}
}

public void launchUpdateWordActivity( Word word) {
Intent intent = new Intent(this, NewWordActivity.class);
intent.putExtra(EXTRA_DATA_UPDATE_WORD, word.getWord());
intent.putExtra(EXTRA_DATA_ID, word.getId());
startActivityForResult(intent, UPDATE_WORD_ACTIVITY_REQUEST_CODE);
}
}
Loading

0 comments on commit f088809

Please sign in to comment.