Search code examples
javagoogle-classroom

Announce text to course through classroom api with java


I am new to Google Classroom API integration and want to announce text in one of the courses through classroom API, I completed Java Quickstart here! it works well for getting all courses data, right now how I implement the announcement() method to create a post for student

public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Classroom service = new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, 
            getCredentials(HTTP_TRANSPORT)).setApplicationName(APPLICATION_NAME).build();
    ListCoursesResponse response = service.courses().list().setPageSize(10).execute();
    List<Course> courses = response.getCourses();
    if (courses == null || courses.size() == 0) {
        System.out.println("No courses found.");
    } else {
        System.out.println("Courses:");
        for (Course course : courses) {
            System.out.println(course.getName());

            //--  How do I create a new announcement?  I tried this getting error ------

            Classroom.Courses.Announcements.Create a = new Classroom.Courses
                            .Announcements.Create().setCourseId("423178037220");

            // -------------------------------
        }
    }
}

after all, I'm getting this error

com.google.api.services.classroom.Classroom.Courses.Announcements' is not an enclosing class


Solution

  • Create is an inner class of Announcements, that is, it implicitly contains a reference to an instance of Announcements.

    So you can't create an instance of Create, except in the context of an instance of Announcements.

    See the code below for a simple example:

    class Sample {
    
        public static class Foo {
            // a non-static inner class
            public class Bar {}
    
            public Bar create() { return new Bar(); }
        }
    
        public static void main(String[] args) {
           Foo.Bar bar1 = new Foo.Bar(); // this line won't compile
           Foo.Bar bar2 = new Foo().create();
        }
    }
    

    You need to call the create method on an Announcements instance to create a a Create instance. (see https://developers.google.com/resources/api-libraries/documentation/classroom/v1/java/latest/com/google/api/services/classroom/Classroom.Courses.Announcements.html#create-java.lang.String-com.google.api.services.classroom.model.Announcement-)

    Try:

    courses.announcements().create("423178037220", new Announcement())
    

    I have not done this myself, as I don't have a Google Classroom project set up.