File tree 3 files changed +12
-5
lines changed
app/src/main/java/org/ninetripods/mq/study/jetpack/datastore
3 files changed +12
-5
lines changed Original file line number Diff line number Diff line change @@ -36,6 +36,7 @@ val Context.bookDataStorePt: DataStore<BookProto.Book> by dataStore(
36
36
context,
37
37
BOOK_PREFERENCES_NAME
38
38
) { sharedPrefs: SharedPreferencesView , currentData: BookProto .Book ->
39
+ // 从SP中取出数据
39
40
val bookName: String = sharedPrefs.getString(KEY_BOOK_NAME , " " ) ? : " "
40
41
val bookPrice: Float = sharedPrefs.getFloat(KEY_BOOK_PRICE , 0f )
41
42
@@ -52,5 +53,4 @@ val Context.bookDataStorePt: DataStore<BookProto.Book> by dataStore(
52
53
}
53
54
)
54
55
}
55
-
56
56
)
Original file line number Diff line number Diff line change 1
1
package org.ninetripods.mq.study.jetpack.datastore.proto
2
2
3
+ import androidx.datastore.core.CorruptionException
3
4
import androidx.datastore.core.Serializer
5
+ import com.google.protobuf.InvalidProtocolBufferException
4
6
import org.ninetripods.mq.study.BookProto
5
7
import java.io.InputStream
6
8
import java.io.OutputStream
7
9
8
10
object BookSerializer : Serializer<BookProto.Book> {
11
+ override val defaultValue: BookProto .Book = BookProto .Book .getDefaultInstance()
9
12
10
13
override suspend fun readFrom (input : InputStream ): BookProto .Book {
11
- return BookProto .Book .parseFrom(input)
14
+ try {
15
+ return BookProto .Book .parseFrom(input)
16
+ } catch (exception: InvalidProtocolBufferException ) {
17
+ throw CorruptionException (" Cannot read proto." , exception)
18
+ }
12
19
}
13
20
14
21
override suspend fun writeTo (t : BookProto .Book , output : OutputStream ) {
15
22
t.writeTo(output)
16
23
}
17
-
18
- override val defaultValue: BookProto .Book = BookProto .Book .getDefaultInstance()
19
-
20
24
}
Original file line number Diff line number Diff line change @@ -32,6 +32,9 @@ android {
32
32
// protoc版本参见:https://repo1.maven.org/maven2/com/google/protobuf/protoc/
33
33
artifact = " com.google.protobuf:protoc:3.18.0"
34
34
}
35
+ // Generates the java Protobuf-lite code for the Protobufs in this project. See
36
+ // https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
37
+ // for more information.
35
38
generateProtoTasks {
36
39
all(). each { task ->
37
40
task. builtins {
You can’t perform that action at this time.
0 commit comments