'How to setup protobuf in kotlin/android studio?

First time using protobuf, so following googles instructions I placed all my .protos in a protos folder in my android studio project. I know the .proto files are setup correctly. I compile the files from that folder using:

protoc -I=. --java_out=. --kotlin_out=. filename.proto

This generates a bunch of kotlin and java files that look like what I am supposed to get. However, android studio throws a ton of errors and doesn't seem to like most of the code in those files.

So my question is there something additional I need to do with the setup, bring in a dependency in the gradle file? I saw an example like that but it seemed only relevant to the plugin for compiling using gradle - since I'm compiling from the command line I don't think I should need that?



Solution 1:[1]

One cannot add *.proto files into Java or Kotlin source directories ...
For Android use protobuf-lite; the configuration looks about like this:

plugins {
    id 'com.android.application' version '7.2.0' apply false
    id 'com.google.protobuf' version '0.8.18' apply false
}

Module build.gradle:

plugins {
    id 'com.android.application'
    id 'com.google.protobuf'
}

android {
    sourceSets {
        main {
            java {
                srcDirs += 'build/generated/source/proto/main/java'
            }
            kotlin {
                srcDirs += 'build/generated/source/proto/main/kotlin'
            }
            proto {
                srcDir 'src/main/proto' // default value
            }
        }
    }
}

dependencies {
    implementation 'com.google.protobuf:protobuf-javalite:3.20.1'
    implementation 'com.google.protobuf:protobuf-kotlin-lite:3.20.1'
}

There's also a protoc compiler and protoc-gen-javalite generator available:

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.20.1'
    }
    plugins {
        javalite {
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }
    generateProtoTasks {
        all().each { task ->
            java {
                option 'lite'
            }
            kotlin {
                option 'lite'
            }
        }
    }
}

Also see protobuf-gradle-plugin (the Kotlin/GRPC example there isn't for Android).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1