Sample: Posting a Comment with a File Attachment

In SFDC Apex Code Developer, a sample to post a comment with file attachment using Chatter Apex (ConnectAPI) is given. But, the code is not copy paste-able. You may see the following error for messageInput.messageSegments.add(textSegment);

System.NullPointerException: Attempt to de-reference a null object

The correct code looks as below. 

String communityId = null;
String feedItemId = '0D5x0000000azYd';
ConnectApi.CommentInput input = new ConnectApi.CommentInput();

ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
//Added
messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

ConnectApi.TextSegmentInput textSegment;
textSegment = new ConnectApi.TextSegmentInput();
textSegment.text = 'Comment Text Body';
messageInput.messageSegments.add(textSegment);
input.body = messageInput;
ConnectApi.NewFileAttachmentInput attachmentInput = new ConnectApi.NewFileAttachmentInput();
attachmentInput.description = 'The description of the file';
attachmentInput.title = 'contentFile.txt';
input.attachment = attachmentInput;
String fileContents = 'This is the content of the file.';
Blob fileBlob = Blob.valueOf(fileContents);
ConnectApi.BinaryInput binaryInput = new ConnectApi.BinaryInput(fileBlob, 'text/plain',
'contentFile.txt');

ConnectApi.Comment commentRep = ConnectApi.ChatterFeeds.postComment(communityId, feedItemId, input, binaryInput);

Comments

Popular posts from this blog

How to prepare your LOB app for Intune?

Information Architecture - Setup your term store to scale

Generate token signing .CER from ADFS Federation Metadata XML