Facebook integration with blackberry - blackberry-eclipse-plugin

I am new in Blackberry. I want to post information on wall in Facebook from my application. I read some documents. What are the steps to integrate with Facebook? Would anyone have a working example Java code for this? How to get api_key,secret_key,application_id?
Thanks

visit the below link. Here you can download the Facebook SDK for blackberry. also you can download the samples which demonstrates clearly about facebook integration into your native bb app.
Find Facebook SDK from GITGUB here

#krishna Check out the following code. This is basically used to post messages on wall.
/**
* Copyright (c) E.Y. Baskoro, Research In Motion Limited.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* This License shall be included in all copies or substantial
* portions of the Software.
*
* The name(s) of the above copyright holders shall not be used
* in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization.
*
*/
package samples.strawberry;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.sf.blackberry.facebook.FBUser;
import net.sf.blackberry.facebook.FacebookContext;
import net.sf.blackberry.facebook.User;
import net.sf.blackberry.facebook.ui.FacebookScreen;
final class PostWallScreen extends FacebookScreen {
// List of actions:
static final String ACTION_ENTER = "postWall";
static final String ACTION_SUCCESS = "posted";
static final String ACTION_ERROR = "error";
// List of labels:
private static final String LABEL_TITLE = "Post To Wall";
private static final String LABEL_USERS = "Post wall to";
private static final String LABEL_NAME = "Title:";
private static final String LABEL_LINK = "Link:";
private static final String LABEL_CAPTION = "Caption:";
private static final String LABEL_CONTENT = "Content:";
private static final String LABEL_POST = "Post";
private User[] users = null;
private ObjectChoiceField objectChoiceField;
private EditField titleEditField;
private EditField hrefEditField;
private EditField captionEditField;
private EditField descriptionEditField;
private ButtonField buttonField;
/**
* Default constructor.
*
*/
PostWallScreen(FacebookContext pfbc) {
super(pfbc);
setTitle(new LabelField(LABEL_TITLE, LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH));
objectChoiceField = new ObjectChoiceField();
objectChoiceField.setLabel(LABEL_USERS);
add(objectChoiceField);
add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
titleEditField = new EditField(LABEL_NAME, "", 80, LabelField.USE_ALL_WIDTH);
add(titleEditField);
hrefEditField = new EditField(LABEL_LINK, "", 80, LabelField.USE_ALL_WIDTH);
add(hrefEditField);
captionEditField = new EditField(LABEL_CAPTION, "", 80, LabelField.USE_ALL_WIDTH);
add(captionEditField);
descriptionEditField = new EditField(LABEL_CONTENT, "", 255, LabelField.USE_ALL_WIDTH);
add(descriptionEditField);
buttonField = new ButtonField(LABEL_POST);
buttonField.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (users == null) {
return;
}
try {
users[objectChoiceField.getSelectedIndex()].publishStream(descriptionEditField.getText(), hrefEditField.getText(), titleEditField.getText(), descriptionEditField.getText(), captionEditField.getText());
fireAction(ACTION_SUCCESS);
} catch (Exception e) {
fireAction(ACTION_ERROR, e.getMessage());
}
}
});
add(buttonField);
}
/**
* Load list of users comprising of friends and self.
*
*/
void loadList() {
try {
User[] friends = new FBUser("me", fbc.getAccessToken()).getFriends();
if (friends == null) {
users = new User[1];
} else {
users = new User[friends.length + 1];
}
users[0] = new FBUser("me", fbc.getAccessToken());
for (int i = 1; i < (friends.length + 1); i++) {
users[i] = friends[i - 1];
}
objectChoiceField.setChoices(users);
} catch (Exception e) {
fireAction(ACTION_ERROR, e.getMessage());
}
}
}

Related

StreamingMessageSource keeps firing when a filter is applied

I am trying to poll an FTP directory for a certain kind of file, the polling of a directory works, but whenever I try to apply a filter to filter the files by extension, the messagesource keeps spamming messages about the file with no regard to the polling delay. Without the filters everything works fine, once I enable them my application authenticates with the FTP, downloads the file and sends the message nonstop over and over again. I have the following beans:
/**
* Factory that creates the remote connection
*
* #return DefaultSftpSessionFactory
*/
#Bean
public DefaultSftpSessionFactory sftpSessionFactory(#Value("${ftp.host}") String ftpHost,
#Value("${ftp.port}") int ftpPort,
#Value("${ftp.user}") String ftpUser,
#Value("${ftp.pass}") String ftpPass) {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setAllowUnknownKeys(true);
factory.setHost(ftpHost);
factory.setPort(ftpPort);
factory.setUser(ftpUser);
factory.setPassword(ftpPass);
return factory;
}
/**
* Template to handle remote files
*
* #param sessionFactory SessionFactory bean
* #return SftpRemoteFileTemplate
*/
#Bean
public SftpRemoteFileTemplate fileTemplate(DefaultSftpSessionFactory sessionFactory) {
SftpRemoteFileTemplate template = new SftpRemoteFileTemplate(sessionFactory);
template.setAutoCreateDirectory(true);
template.setUseTemporaryFileName(false);
return template;
}
/**
* To listen to multiple directories, declare multiples of this bean with the same inbound channel
*
* #param fileTemplate FileTemplate bean
* #return MessageSource
*/
#Bean
#InboundChannelAdapter(channel = "deeplinkAutomated", poller = #Poller(fixedDelay = "6000", maxMessagesPerPoll = "-1"))
public MessageSource inboundChannelAdapter(SftpRemoteFileTemplate fileTemplate) {
SftpStreamingMessageSource source = new SftpStreamingMessageSource(fileTemplate);
source.setRemoteDirectory("/upload");
source.setFilter(new CompositeFileListFilter<>(
Arrays.asList(new AcceptOnceFileListFilter<>(), new SftpSimplePatternFileListFilter("*.trg"))
));
return source;
}
/**
* Listener that activates on new messages on the specified input channel
*
* #return MessageHandler
*/
#Bean
#ServiceActivator(inputChannel = "deeplinkAutomated")
public MessageHandler handler(JobLauncher jobLauncher, Job deeplinkBatch) {
return message -> {
Gson gson = new Gson();
SFTPFileInfo info = gson.fromJson((String) message.getHeaders().get("file_remoteFileInfo"), SFTPFileInfo.class);
System.out.println("File to download: " + info.getFilename().replace(".trg", ".xml"));
};
}
I think AcceptOnceFileListFilter is not suitable for SFTP files. The returned LsEntry doesn't match previously stored in the HashSet: just their hashes are different!
Consider to use a SftpPersistentAcceptOnceFileListFilter instead.
Also it would be better to configure a DefaultSftpSessionFactory for the isSharedSession:
/**
* #param isSharedSession true if the session is to be shared.
*/
public DefaultSftpSessionFactory(boolean isSharedSession) {
To avoid session recreation on each polling task.
you don't have a 6 seconds delay between calls because you have a maxMessagesPerPoll = "-1". That means poll remote files until they are there in remote dir. In your case with the AcceptOnceFileListFilter you always end up with the same file by the hash reason.

Android Studio - data moving within tabs/fragments

I am currently doing on a project that requires me to move my data between tabs/fragments.. Let's say the user clicks on the listView item, they will move to another tab, instead of staying in the same tab. May I know how can I achieve that? Can someone help to solve my query? Thank you!
You can trasnfer data between tabs by set and get Arguments,
Here is Example
FragmentTwo fragmentTwo = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("key1", "data1");
bundle.putString("key2", "data2");
bundle.putString("key3", "data3");
fragmentTwo.setArguments(bundle);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, fragmentTwo);
fragmentTransaction.commit();
There are 3 ways to do this
1) Use Interfaces -use interface to pass data objects. Meshy solution
Read more
public interface onDataCHange{
public void updateData(String data);
}
2) Use Activity Class - Store model object in activity class and set and get using activity Instance. Quick and Dirty solution
Read more
//Get
Object dataModel = (ContainerActivity) getActivity()).getData();
//Set
((ContainerActivity) getActivity()).setData(dataModel );
3) Clean architecture - Center repository hold model objects. View update model via Singleton Center repository object. Single copy of data flow between throughout the App.
Read more
#Singleton
public class UserDataRepository implements UserRepository {
private final UserDataStoreFactory userDataStoreFactory;
private final UserEntityDataMapper userEntityDataMapper;
/**
* Constructs a {#link UserRepository}.
*
* #param dataStoreFactory A factory to construct different data source implementations.
* #param userEntityDataMapper {#link UserEntityDataMapper}.
*/
#Inject
UserDataRepository(UserDataStoreFactory dataStoreFactory,
UserEntityDataMapper userEntityDataMapper) {
this.userDataStoreFactory = dataStoreFactory;
this.userEntityDataMapper = userEntityDataMapper;
}
#Override public Observable<List<User>> users() {
//we always get all users from the cloud
final UserDataStore userDataStore = this.userDataStoreFactory.createCloudDataStore();
return userDataStore.userEntityList().map(this.userEntityDataMapper::transform);
}
#Override public Observable<User> user(int userId) {
final UserDataStore userDataStore = this.userDataStoreFactory.create(userId);
return userDataStore.userEntityDetails(userId).map(this.userEntityDataMapper::transform);
}
}

Got force close in SongsManager

i am developing a simple media player application but while building the apk in Marshmallow API 23 my applicatioin crashes. Here is my code.
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
And this is the full code of SongsManager
package ph.zyber.zybermp;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
public class SongsManager {
// SDCard Path
final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
public SongsManager(){
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList(){
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which are having .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
}
I am following the tutorial.
http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/#
Please help me out.
Thanks in advance.
In Eclipse you need to find the path to the folder with the music:
Window-Show View-Other-file explorer (The phone must be connected to a computer).
Where searches the full path, I have turned it - "/storage/extSdCard/Music".
After I put it in the code and it worked:
final String MEDIA_PATH = new String("/storage/extSdCard/Music");
Good luck.
Modify SongsManger like this and you have to pass context of appropriate activity during object creation of songsmanger in that activity
I have corrected the code for getplaylist() function and dont forget to add runtime permission in manifest and also
check the permission using a dialog box
extend appcombatActivity in each of your activity it contains the content resolver
eg:
SongsManager plm = new SongsManager(PlayListActivity.this);
// get all songs from sdcard
this.songsList = plm.getPlayList();
public class SongsManager {
private ArrayList<hashmap<string, string="">> songsList = new ArrayList<hashmap<string, string="">>();
Cursor cursor;
Context context;
// Constructor
public SongsManager(Context context){
this.context = context;
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<hashmap<string, string="">> getPlayList(){
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION
};
ContentResolver contentResolver = context.getContentResolver();
cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection, selection,null,null);
while(cursor.moveToNext()) {
HashMap<string, string=""> song = new HashMap<string, string="">();
song.put("songID",cursor.getString(0));
song.put("songTitle",cursor.getString(2));
song.put("songPath",cursor.getString(3));
// Adding each song to SongList
songsList.add(song);
}
// return songs list array
return songsList;
}
}

Can you use xPages DominoViewData in a JAVA class?

I'd like to use com.ibm.xsp.model.domino.DominoViewData() in my Java class to filter and sort domino view data, but I'm not sure how to go about it.
There aren't a lot of examples out there, and most I've found are using it on an xPage or with a Data Table.
In a JAVA class, I'd like to:
Create a new DominoViewData object.
Set the view name.
Set the column to sort on.
Optionally set a filter.
Finally, retrieve a ViewEntryCollection for further processing.
Can the DominoViewData class be used in that way?
Thanks for your help and any examples would be appreciated.
-- Jeff
As long as your are using them in an XPage application, this is possible. I am not sure what benefits you will have instead of accessing a view directly, but here is the code:
1.You need a helper class to access the tabular data model
/**
* Returns the tabular data model from a datasource
*
* #author Christian Guedemann, Sven Hasselbach
* #param dsCurrent
* datasource to get the tdm from
* #param context
* current FacesContext instance
* #return
* TabularDataModel
*/
public static TabularDataModel getTDM(DataSource dsCurrent, FacesContext context) {
try {
if (dsCurrent instanceof ModelDataSource) {
ModelDataSource mds = (ModelDataSource) dsCurrent;
AbstractDataSource ads = (AbstractDataSource) mds;
ads.load(context);
DataModel tdm = mds.getDataModel();
if (tdm instanceof TabularDataModel) {
TabularDataModel tds = (TabularDataModel) tdm;
return tds;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2.You have to create your datasource and add them to a component, f.e. the view root
DominoViewData dvd = new DominoViewData();
dvd.setViewName( "YOUR VIEW NAME" );
dvd.setComponent( FacesContext.getCurrentInstance().getViewRoot() );
3.Now you can add the filter options or any additional options to your datasource, f.e. these:
dvd.setSortOrder( "ascending" );
dvd.setSortColumn( "NAME OF COLUMN" );
4.Then access the TDM of the datasource, get the first entry and you have a handle to the parent, a ViewNavigator
TabularDataModel tdm = getTDM( dvd, FacesContext.getCurrentInstance() );
tdm.setDataControl( new UIDataEx() );
Entry noiEntry = (Entry) tdm.getRowData();
ViewNavigator nav = null;
try {
nav = (ViewNavigator) noiEntry.getParent();
System.out.println( "NAV COUNT: " + nav.getCount() );
nav.recylce();
} catch (NotesException e) {
e.printStackTrace();
}
(OK, you now have a ViewNavigator instead of a ViewEntryCollection)

J2ME Back command - returning to previous screen

I'm stuck trying to figure out how to create a back command to the previous screen.The page I'm trying to return to does not have a form but a List but when I set the 'back' command listener to the list it just seems to throw a null pointer exception.
Here is my main class
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
/**
*
*/
public class CalFrontEnd extends MIDlet implements CommandListener
{
private Display display;
protected List list = new List("Please Select a Option", List.IMPLICIT);
private Command select = new Command("Select", Command.SCREEN, 1);
private Command exit = new Command("Exit", Command.EXIT, 2);
private Command save = new Command("Save,", Command.SCREEN, 2);
private DateField calendar;
/**
*
*/
public CalFrontEnd()
{
display = Display.getDisplay(this);
list.append("Select Date", null);
list.append("Add Events", null);
list.append("Remove Events", null);
list.append("Browse Events", null);
list.addCommand(select);
list.addCommand(exit);
list.setCommandListener(this);
}
/**
* Start Application
*/
public void startApp()
{
display.setCurrent(list);
}
/**
* Pause Application Method
*/
public void pauseApp()
{}
/**
* Destroy Application Method
*/
public void destroyApp(boolean unconditional)
{}
/**
*
* #param command
* #param displayable
*/
public void commandAction(Command command, Displayable displayable)
{
if (displayable == list) {
if (command == List.SELECT_COMMAND) {
switch (list.getSelectedIndex()) {
case 0: // select Date
SelectDate myDate = new SelectDate(display);
myDate.BuildCalendar();
break;
case 1: //add Events
AddEvents myAEvents = new AddEvents(display);
myAEvents.BuildAddEvents();
break;
case 2: //Remove Events
RemoveEvents myREvents = new RemoveEvents(display);
myREvents.BuildRemoveEvents();
break;
case 3: //Browse Events
BrowseEvents myBEvents = new BrowseEvents(display);
myBEvents.BuildBrowseEvents();
break;
}
} else if (command == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}
}
And this is the class which I'm trying to use the back button on
import java.util.*;
import javax.microedition.lcdui.*;
/**
*
*/
public class SelectDate extends CalFrontEnd implements CommandListener
{
private DateField calendar;
private Form form = new Form("Please Select a Date");
private Command select = new Command("Select", Command.SCREEN, 1);
private Command back = new Command("Back", Command.BACK, 2);
private Command save = new Command("Save,", Command.SCREEN, 2);
private Display display;
/**
*
*/
public SelectDate(Display display)
{
this.display = display;
}
/**
*
*/
public void BuildCalendar()
{
calendar = new DateField("Date In :", DateField.DATE, TimeZone.getTimeZone("GMT"));
form.append(calendar);
form.addCommand(back);
form.setCommandListener(this);
display.setCurrent(form);
}
/**
*
* #param command
* #param displayable
*/
public void commandAction(Command command, Display display)
{
if (command == back)
{
display.setCurrent(list);
}
}
}
Inappropriate use of inheritance has brought you into trouble here. Look, there is a list field in SelectDate class but it is not visible in code, because it is inherited from superclass (extends CalFrontEnd and protected List list are where all your trouble really begins).
When you create an instance of SelectDate (new SelectDate(display)) this field is initialized with null - and you never change it after that. It's hard for you to notice that because the very declaration of list is buried in other file in superclass. And, which makes things even harder, compiler can't help you here because the field is visible to it and it believes things are OK.
You know, this is only a beginning of your troubles related to overuse of inheritance. Further down the road, more headaches are waiting to happen. Think for example of what would happen if you accidentally remove or rename commandAction in SelectDate? Compiler will think it's all-right - just because superclass has this method, too. You'll only notice that things went wrong in some misterious way when you run the code and find out that commands at select date screen stop responding or began doing weird things. Actually it would be safer to hide CommandListener for both classes just to avoid this kind mistakes but that was discussed in another question.
I strongly recommend to wipe out extends CalFrontEnd from SelectDate. That will help compiler help you to find various logical issues in your code.
As for list to show by Back command, you can for example pass it as additional constructor parameter, like as below:
public class SelectDate implements CommandListener // drop "extends CalFrontEnd"
{
// ...
private Display display;
private List list; // add the field for the list
public SelectDate(Display display, List list) // add list as parameter
{
this.display = display;
this.list = list; // initialize field
}
// ... commandAction code will get the right "list" now
}
There are a number of problems regarding your code.
One gnat has already mentioned (Remove extends CalFrontEnd in SelectData class).
Secondly you are not calling select command in commandAction of your code (command you are calling is List.SELECT_COMMAND which is not select). So change if (command == List.SELECT_COMMAND) to if (command == select).
Thirdly documentation of commandAction in CommandListener declares its second parameter to be Displayable while you are declaring it with Display.
the error is that there's no variable called list, the solution however is to simply change the code under your back button from
display.setCurrent(list)
to
display.setCurrent(CalFrontEnd.list)

Resources