-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainActivity.java
281 lines (237 loc) · 10.7 KB
/
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package com.example.dittotasks;
import android.app.AlertDialog;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import androidx.activity.ComponentActivity;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import kotlin.Unit;
import live.ditto.Ditto;
import live.ditto.DittoDependencies;
import live.ditto.DittoError;
import live.ditto.DittoIdentity;
import live.ditto.DittoStoreObserver;
import live.ditto.DittoSyncSubscription;
import live.ditto.android.DefaultAndroidDittoDependencies;
import live.ditto.transports.DittoSyncPermissions;
import live.ditto.transports.DittoTransportConfig;
public class MainActivity extends ComponentActivity {
private TaskAdapter taskAdapter;
private SwitchCompat syncSwitch;
Ditto ditto;
DittoSyncSubscription taskSubscription;
DittoStoreObserver taskObserver;
private String DITTO_APP_ID = "<put your Ditto Portal App ID here>";
private String DITTO_PLAYGROUND_TOKEN = "<put your Ditto Portal Playground Token here>";
private String DITTO_AUTH_URL = "<put your Ditto Portal Auth URL here>";
private String DITTO_WEBSOCKET_URL = "<put your Ditto Portal WebSocket URL here>";
// This is required to be set to false to use the correct URLs
private Boolean DITTO_ENABLE_CLOUD_SYNC = false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDitto();
// Populate AppID view
TextView appId = findViewById(R.id.ditto_app_id);
appId.setText(String.format("App ID: %s", DITTO_APP_ID));
// Populate Playground Token view
TextView playgroundToken = findViewById(R.id.ditto_playground_token);
playgroundToken.setText(String.format("Playground Token: %s", DITTO_PLAYGROUND_TOKEN));
// Initialize "add task" fab
FloatingActionButton addButton = findViewById(R.id.add_button);
addButton.setOnClickListener(v -> showAddTaskModal());
// Initialize sync switch
syncSwitch = findViewById(R.id.sync_switch);
syncSwitch.setChecked(true);
syncSwitch.setOnCheckedChangeListener(((buttonView, isChecked) -> {
toggleSync();
}));
// Initialize task list
RecyclerView taskList = findViewById(R.id.task_list);
taskList.setLayoutManager(new LinearLayoutManager(this));
taskAdapter = new TaskAdapter();
taskList.setAdapter(taskAdapter);
taskAdapter.setOnTaskToggleListener((task, isChecked) -> {
toggleTask(task);
});
taskAdapter.setOnTaskDeleteListener(this::deleteTask);
taskAdapter.setOnTaskLongPressListener(this::showEditTaskModal);
taskAdapter.setTasks(List.of());
}
void initDitto() {
requestPermissions();
try {
DittoDependencies androidDependencies = new DefaultAndroidDittoDependencies(getApplicationContext());
/*
* Setup Ditto Identity
* https://docs.ditto.live/sdk/latest/install-guides/java#integrating-and-initializing
*/
var identity = new DittoIdentity
.OnlinePlayground(
androidDependencies,
DITTO_APP_ID,
DITTO_PLAYGROUND_TOKEN,
DITTO_ENABLE_CLOUD_SYNC, // This is required to be set to false to use the correct URLs
DITTO_AUTH_URL);
ditto = new Ditto(androidDependencies, identity);
// Set the Ditto Websocket URL
DittoTransportConfig config = new DittoTransportConfig();
config.getConnect().getWebsocketUrls().add(DITTO_WEBSOCKET_URL);
// Enable all P2P transports
config.enableAllPeerToPeer();
ditto.setTransportConfig(config);
// disable sync with v3 peers, required for DQL
ditto.disableSyncWithV3();
// register subscription
// https://docs.ditto.live/sdk/latest/sync/syncing-data#creating-subscriptions
taskSubscription = ditto.sync.registerSubscription("SELECT * FROM tasks");
// register observer for live query
// https://docs.ditto.live/sdk/latest/crud/observing-data-changes#setting-up-store-observers
taskObserver = ditto.store.registerObserver("SELECT * FROM tasks WHERE deleted=false ORDER BY _id", null, result -> {
var tasks = result.getItems().stream().map(Task::fromQueryItem).collect(Collectors.toCollection(ArrayList::new));
runOnUiThread(() -> {
taskAdapter.setTasks(new ArrayList<>(tasks));
});
return Unit.INSTANCE;
});
ditto.startSync();
} catch (DittoError e) {
e.printStackTrace();
}
}
// Request permissions for Ditto
// https://docs.ditto.live/sdk/latest/install-guides/java#requesting-permissions-at-runtime
void requestPermissions() {
DittoSyncPermissions permissions = new DittoSyncPermissions(this);
String[] missing = permissions.missingPermissions(permissions.requiredPermissions());
if (missing.length > 0) {
this.requestPermissions(missing, 0);
}
}
private void createTask(String title) {
HashMap<String, Object> task = new HashMap<>();
task.put("title", title);
task.put("done", false);
task.put("deleted", false);
HashMap<String, Object> args = new HashMap<>();
args.put("task", task);
try {
// Add tasks into the ditto collection using DQL INSERT statement
// https://docs.ditto.live/sdk/latest/crud/write#inserting-documents
ditto.store.execute("INSERT INTO tasks DOCUMENTS (:task)", args);
} catch (DittoError e) {
e.printStackTrace();
}
}
private void editTaskTitle(Task task, String newTitle) {
HashMap<String, Object> args = new HashMap<>();
args.put("id", task.getId());
args.put("title", newTitle);
try {
// Update tasks into the ditto collection using DQL UPDATE statement
// https://docs.ditto.live/sdk/latest/crud/update#updating
ditto.store.execute("UPDATE tasks SET title=:title WHERE _id=:id", args);
} catch (DittoError e) {
e.printStackTrace();
}
}
private void toggleTask(Task task) {
HashMap<String, Object> args = new HashMap<>();
args.put("id", task.getId());
args.put("done", !task.isDone());
try {
// Update tasks into the ditto collection using DQL UPDATE statement
// https://docs.ditto.live/sdk/latest/crud/update#updating
ditto.store.execute("UPDATE tasks SET done=:done WHERE _id=:id", args);
} catch (DittoError e) {
e.printStackTrace();
}
}
private void deleteTask(Task task) {
HashMap<String, Object> args = new HashMap<>();
args.put("id", task.getId());
try {
// UPDATE DQL Statement using Soft-Delete pattern
// https://docs.ditto.live/sdk/latest/crud/delete#soft-delete-pattern
ditto.store.execute("UPDATE tasks SET deleted=true WHERE _id=:id", args);
} catch (DittoError e) {
e.printStackTrace();
}
}
private void toggleSync() {
if (ditto == null) {
return;
}
boolean isSyncActive = ditto.isSyncActive();
var nextColor = isSyncActive ? null : ColorStateList.valueOf(0xFFBB86FC);
var nextText = isSyncActive ? "Sync Inactive" : "Sync Active";
// implement Ditto Sync
// https://docs.ditto.live/sdk/latest/sync/start-and-stop-sync
try {
if (isSyncActive) {
ditto.stopSync();
} else {
ditto.startSync();
}
syncSwitch.setChecked(!isSyncActive);
syncSwitch.setTrackTintList(nextColor);
syncSwitch.setText(nextText);
} catch (DittoError e) {
e.printStackTrace();
}
}
private void showAddTaskModal() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogView = getLayoutInflater().inflate(R.layout.modal_new_task, null);
EditText modalTaskTitle = dialogView.findViewById(R.id.modal_task_title);
builder.setView(dialogView)
.setPositiveButton("Add", (dialog, which) -> {
String text = modalTaskTitle.getText().toString().trim();
if (!text.isEmpty()) {
createTask(text);
}
})
.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());
AlertDialog dialog = builder.create();
dialog.show();
// Show keyboard automatically
modalTaskTitle.requestFocus();
Objects.requireNonNull(dialog.getWindow()).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
private void showEditTaskModal(Task task) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogView = getLayoutInflater().inflate(R.layout.modal_edit_task, null);
EditText modalEditTaskTitle = dialogView.findViewById(R.id.modal_edit_task_title);
// Pre-fill the current task title
modalEditTaskTitle.setText(task.getTitle());
modalEditTaskTitle.setSelection(task.getTitle().length()); // Place cursor at end
builder.setView(dialogView)
.setTitle("Edit Task")
.setPositiveButton("Save", (dialog, which) -> {
String newTitle = modalEditTaskTitle.getText().toString().trim();
if (!newTitle.isEmpty()) {
editTaskTitle(task, newTitle);
}
})
.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());
AlertDialog dialog = builder.create();
dialog.show();
// Show keyboard automatically
modalEditTaskTitle.requestFocus();
Objects.requireNonNull(dialog.getWindow())
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
}