I want to create a group to make the current device tablet as the access point, however in the callback method onGroupInfoAvailable() I got a null pointer of group. Why?
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
manager.createGroup(channel, new ActionListener() {
#Override
public void onSuccess() {
manager.requestGroupInfo(channel, new GroupInfoListener() {
public void onGroupInfoAvailable(WifiP2pGroup group) {
if(group != null)
Toast.makeText(SasetBladderPadActivity.this, "Group Passphrase: "
+ group.getPassphrase(), Toast.LENGTH_LONG).show();
else
Toast.makeText(SasetBladderPadActivity.this, "Group is null ",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(int arg0) {
// TODO Auto-generated method stub
Toast.makeText(SasetBladderPadActivity.this, "Create group failed: " + arg0, \
Toast.LENGTH_LONG).show();
}
});
I think you need to implement the grouplistener and then #override the ongroupinfoavailable method. On success is just the asyn call. Actual callback needs to be modified.
Yes, the group is created but not shown. I will suggest to do it with the trick of implementing countdowntimer(or you may use any other timer) to start the requestGroupInfo() after a second. The modified code will be:
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
manager.createGroup(channel, new ActionListener() {
#Override
public void onSuccess() {
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
manager.requestGroupInfo(channel, new GroupInfoListener() {
public void onGroupInfoAvailable(WifiP2pGroup group) {
if(group != null)
Toast.makeText(SasetBladderPadActivity.this, "Group Passphrase: "
+ group.getPassphrase(), Toast.LENGTH_LONG).show();
else
Toast.makeText(SasetBladderPadActivity.this, "Group is null ",
Toast.LENGTH_LONG).show();
}
});
}
}.start();
}
#Override
public void onFailure(int arg0) {
...
Related
I would like to validate user is signed in or not to achieve it i found something called VaadinServiceInitListener in vaadin 13.0.2 This class is used to listen to BeforeEnter event of all UIs in order to check whether a user is signed in or not before allowing entering any page.
I have created an vaadin 13.0.2 project with app-layout-addon by appreciated implemented login functionality and VaadinServiceInitListener to check whether a user is signed in or not.
public class AAACATInitListener implements VaadinServiceInitListener {
private static final long serialVersionUID = 1L;
private static InAppSessionContextImpl appContextImpl;
#Override
public void serviceInit(ServiceInitEvent event) {
System.out.println("in service init event");
event.getSource().addUIInitListener(new UIInitListener() {
private static final long serialVersionUID = 1L;
#Override
public void uiInit(UIInitEvent event) {
event.getUI().addBeforeEnterListener(new BeforeEnterListener() {
private static final long serialVersionUID = 1L;
#Override
public void beforeEnter(BeforeEnterEvent event) {
appContextImpl = (InAppSessionContextImpl)VaadinSession.getCurrent().getAttribute("context");
if (appContextImpl == null) {
WebBrowser webBrowser = UI.getCurrent().getSession().getBrowser();
String address = webBrowser.getAddress();
if(RememberAuthService.isAuthenticated(address) != null && !RememberAuthService.isAuthenticated(address).isEmpty()) {
//System.out.println("Found Remembered User....");
IBLSessionContext iblSessionContext = null;
try {
iblSessionContext = new UserBLManager().doRememberedStaffUserLogin(RememberAuthService.isAuthenticated(address), "");
if(iblSessionContext != null) {
InAppSessionContextImpl localAppContextImpl = new InAppSessionContextImpl();
localAppContextImpl.setBLSessionContext(iblSessionContext);
localAppContextImpl.setModuleGroupList(iblSessionContext.getSessionAccessControl().getPermittedModuleGroups());
appContextImpl = localAppContextImpl;
event.rerouteTo(ApplicationMainView.class);
}else {
Notification.show("Your access has been expired, Please contact your administrator", 5000, Position.BOTTOM_CENTER);
}
} catch (AuthenticationFailedException e) {
Notification.show("Authentication Failed, Please Reset Cookies And Try Again", 5000, Position.BOTTOM_CENTER);
} catch (Exception e){
e.printStackTrace();
Notification.show("Unexpected Error Occurred, Please Reset Cookies And Try Again", 5000, Position.BOTTOM_CENTER);
}
}else {
System.out.println("Session context is null, creating new context");
appContextImpl = new InAppSessionContextImpl();
VaadinSession.getCurrent().setAttribute("context", appContextImpl);
event.rerouteTo(LoginView.class);
}
} else {
System.out.println("Session context is not null");
InAppSessionContextImpl localAppContextImpl = new InAppSessionContextImpl();
localAppContextImpl.setBLSessionContext(appContextImpl.getBLSessionContext());
localAppContextImpl.setModuleGroupList(appContextImpl.getModuleGroupList());
appContextImpl = localAppContextImpl;
event.rerouteTo(ApplicationMainView.class);
}
}
});
}
});
}
public static void setBLSessionContext(IBLSessionContext iblSessionContext) {
appContextImpl.setBLSessionContext(iblSessionContext);
}
public static void setModuleGroupList(List<ModuleGroupVO> moduleGroupList) {
appContextImpl.setModuleGroupList(moduleGroupList);
}
private class InAppSessionContextImpl implements InAppSessionContext {
private static final long serialVersionUID = 1L;
private List<ModuleGroupVO> moduleGroupList;
private IBLSessionContext iblSessionContext;
private Map<String, Object> attributeMap;
public InAppSessionContextImpl() {
this.attributeMap = new HashMap<String, Object>();
}
#Override
public List<ModuleGroupVO> getModuleGroupList() {
return moduleGroupList;
}
public void setModuleGroupList(List<ModuleGroupVO> moduleGroupList) {
this.moduleGroupList = moduleGroupList;
}
#Override
public IBLSessionContext getBLSessionContext() {
return iblSessionContext;
}
public void setBLSessionContext(IBLSessionContext iblSessionContext) {
this.iblSessionContext = iblSessionContext;
}
#Override
public IBLSession getBLSession() {
if(iblSessionContext != null)
return iblSessionContext.getBLSession();
return null;
}
#Override
public boolean isPermittedAction(String actionAlias) {
if (getBLSessionContext() != null) {
if (getBLSessionContext().getSessionAccessControl() != null) {
return getBLSessionContext().getSessionAccessControl().isPermittedAction(actionAlias);
}
}
return false;
}
#Override
public void setAttribute(String key, Object attribute) {
attributeMap.put(key, attribute);
}
#Override
public Object getAttribute(String key) {
return attributeMap.get(key);
}
}
}
Expected results redirect to login page if user not signed in or else to main application page but AAACATInitListener is not listening.
If you are using Spring, simply add a #Component annotation to the class and it should work. If youre not using Spring, follow #codinghaus' answer.
To make Vaadin recognize the VaadinServiceInitListener you have to create a file called com.vaadin.flow.server.VaadinServiceInitListener and put it under src/main/resources/META-INF/services. Its content should be the full path to the class that implements the VaadinServiceInitListener interface. Did you do that?
You can also find a description on that in the tutorial.
The correct pattern to use beforeEnter(..) is not do it via VaadinServiceInitListener , instead you should implement BeforeEnterObserver interface in the view where you need use it and override beforeEnter(..) method with your implementation.
public class MainView extends VerticalLayout implements RouterLayout, BeforeEnterObserver {
...
#Override
public void beforeEnter(BeforeEnterEvent event) {
...
}
}
I am using the paging library with Firebase, and set ValueEventListener on the repository to invalidate the data whenever a change happens. The problem is as soon as I trigger invalidate(), the Observer trigger onChanged and Adapter.submitList(items) gets items with 0 size before the new date is loaded from Firebase via loadInitial method on the ItemKeyedDataSource.
The result is that the DIFF_CALLBACK is never called on PagedListAdapter because there is no comparison between the old list and the new items list (0 size) and when the data received it refresh the list like if I used notifyDataSetChanged().
The only solution so far is to delay Adapter.submitList(items) by 5 seconds until all the data is received from Firebase, but it's not a practical solution.
public class UsersRepository {
private final static String TAG = UsersRepository.class.getSimpleName();
// [START declare_database_ref]
private DatabaseReference mDatabaseRef;
private DatabaseReference mUsersRef;
private Boolean isFirstLoaded = true;
public ValueEventListener usersChangesListener;
public UsersRepository() {
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUsersRef = mDatabaseRef.child("users");
isFirstLoaded = true;
Log.d(TAG, "UsersRepository init. isFirstLoaded= " + isFirstLoaded);
}
public void getUsers(Long initialKey, final int size, #NonNull final ItemKeyedDataSource.LoadInitialCallback < User > callback) {
if (initialKey == null) {
Log.d(TAG, "getUsers initialKey= " + initialKey);
mUsersRef.orderByChild("created").limitToFirst(size).addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// [START_EXCLUDE]
if (dataSnapshot.exists()) {
// loop throw users value
List < User > usersList = new ArrayList < >();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
usersList.add(userSnapshot.getValue(User.class));
Log.d(TAG, "getUsers dataSnapshot. getSnapshotKey= " + userSnapshot.getKey());
}
if (usersList.size() == 0) {
return;
}
Log.d(TAG, "getUsers usersList.size= " + usersList.size() + " lastkey= " + usersList.get(usersList.size() - 1).getCreatedLong());
if (callback instanceof ItemKeyedDataSource.LoadInitialCallback) {
//initial load
/*((ItemKeyedDataSource.LoadInitialCallback)callback)
.onResult(usersList, 0, 14);*/
callback.onResult(usersList);
}
} else {
Log.w(TAG, "getUsers no users exist");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
} else {
Log.d(TAG, "getUsers initialKey= " + initialKey);
mUsersRef.orderByChild("created").startAt(initialKey).limitToFirst(size).addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// [START_EXCLUDE]
if (dataSnapshot.exists()) {
// loop throw users value
List < User > usersList = new ArrayList < >();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
usersList.add(userSnapshot.getValue(User.class));
Log.d(TAG, "getUsers dataSnapshot. getSnapshotKey= " + userSnapshot.getKey());
}
if (usersList.size() == 0) {
return;
}
Log.d(TAG, "getUsers usersList.size= " + usersList.size() + " lastkey= " + usersList.get(usersList.size() - 1).getCreatedLong());
if (callback instanceof ItemKeyedDataSource.LoadInitialCallback) {
//initial load
/*((ItemKeyedDataSource.LoadInitialCallback)callback)
.onResult(usersList, 0, 14);*/
callback.onResult(usersList);
}
} else {
Log.w(TAG, "getUsers no users exist");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
}
}
public void getUsersAfter(final Long key, final int size, #NonNull final ItemKeyedDataSource.LoadCallback < User > callback) {
/*if(key == entireUsersList.get(entireUsersList.size()-1).getCreatedLong()){
Log.d(TAG, "getUsersAfter init. afterKey= " + key+ "entireUsersList= "+entireUsersList.get(entireUsersList.size()-1).getCreatedLong());
return;
}*/
Log.d(TAG, "getUsersAfter. AfterKey= " + key);
mUsersRef.orderByChild("created").startAt(key).limitToFirst(size).addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// [START_EXCLUDE]
if (dataSnapshot.exists()) {
// loop throw users value
List < User > usersList = new ArrayList < >();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
usersList.add(userSnapshot.getValue(User.class));
Log.d(TAG, "getUsersAfter dataSnapshot. getSnapshotKey= " + userSnapshot.getKey());
}
if (usersList.size() == 0) {
return;
}
Log.d(TAG, "getUsersAfter usersList.size= " + usersList.size() + "lastkey= " + usersList.get(usersList.size() - 1).getCreatedLong());
if (callback instanceof ItemKeyedDataSource.LoadCallback) {
//initial After
callback.onResult(usersList);
/*((ItemKeyedDataSource.LoadCallback)callback)
.onResult(usersList);*/
}
} else {
Log.w(TAG, "getUsersAfter no users exist");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
//mUsersRef.addValueEventListener(usersListener);
}
public void getUsersBefore(final Long key, final int size, #NonNull final ItemKeyedDataSource.LoadCallback < User > callback) {
Log.d(TAG, "getUsersBefore. BeforeKey= " + key);
/*if(key == entireUsersList.get(0).getCreatedLong()){
return;
}*/
mUsersRef.orderByChild("created").endAt(key).limitToLast(size).addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// [START_EXCLUDE]
if (dataSnapshot.exists()) {
// loop throw users value
List < User > usersList = new ArrayList < >();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
usersList.add(userSnapshot.getValue(User.class));
Log.d(TAG, "getUsersBefore dataSnapshot. getSnapshotKeys= " + userSnapshot.getKey());
}
if (usersList.size() == 0) {
return;
}
Log.d(TAG, "getUsersBefore usersList.size= " + usersList.size() + "lastkey= " + usersList.get(usersList.size() - 1).getCreatedLong());
if (callback instanceof ItemKeyedDataSource.LoadCallback) {
//initial before
callback.onResult(usersList);
/*((ItemKeyedDataSource.LoadCallback)callback)
.onResult(usersList);*/
}
//initial load
/* ((ItemKeyedDataSource.LoadCallback)callback)
.onResult(usersList, 0, usersList.size());*/
} else {
Log.w(TAG, "getUsersBefore no users exist");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
//mUsersRef.addValueEventListener(usersListener);
}
public void usersChanged(final DataSource.InvalidatedCallback InvalidatedCallback) {
final Query query = mUsersRef.orderByChild("created");
usersChangesListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!isFirstLoaded) {
isFirstLoaded = true;
Log.d(TAG, "entireUsersList Invalidated:");
// Remove post value event listener
if (usersChangesListener != null) {
query.removeEventListener(usersChangesListener);
Log.d(TAG, "usersChanged Invalidated removeEventListener");
}
((ItemKeyedDataSource.InvalidatedCallback)InvalidatedCallback).onInvalidated();
}
isFirstLoaded = false;
/*if(entireUsersList.size() > 0){
entireUsersList.clear();
((ItemKeyedDataSource.InvalidatedCallback)onInvalidatedCallback).onInvalidated();
Log.d(TAG, "entireUsersList Invalidated:");
return;
}
if (dataSnapshot.exists()) {
// loop throw users value
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
entireUsersList.add(userSnapshot.getValue(User.class));
}
Log.d(TAG, "entireUsersList size= "+entireUsersList.size()+"dataSnapshot count= "+dataSnapshot.getChildrenCount());
} else {
Log.w(TAG, "usersChanged no users exist");
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
query.addValueEventListener(usersChangesListener);
//mUsersRef.addValueEventListener(eventListener);
}
}
public class UsersDataSource extends ItemKeyedDataSource < Long,
User >
public class UsersDataSource extends ItemKeyedDataSource < Long,
User > {
private final static String TAG = UsersDataSource.class.getSimpleName();
private UsersRepository usersRepository;
public UsersDataSource() {
usersRepository = new UsersRepository();
}
#Override
public void addInvalidatedCallback(#NonNull InvalidatedCallback onInvalidatedCallback) {
//super.addInvalidatedCallback(onInvalidatedCallback);
Log.d(TAG, "Callback Invalidated ");
usersRepository.usersChanged(onInvalidatedCallback);
}
#Override
public void loadInitial(#NonNull LoadInitialParams < Long > params, #NonNull LoadInitialCallback < User > callback) {
/*List<User> items = usersRepository.getUsers(params.requestedInitialKey, params.requestedLoadSize);
callback.onResult(items);*/
Log.d(TAG, "loadInitial params key" + params.requestedInitialKey + " " + params.requestedLoadSize);
usersRepository.getUsers(params.requestedInitialKey, params.requestedLoadSize, callback);
//usersRepository.getUsers( 0L, params.requestedLoadSize, callback);
}
#Override
public void loadAfter(#NonNull LoadParams < Long > params, #NonNull LoadCallback < User > callback) {
/*List<User> items = usersRepository.getUsers(params.key, params.requestedLoadSize);
callback.onResult(items);*/
Log.d(TAG, "loadAfter params key " + (params.key + 1));
usersRepository.getUsersAfter(params.key + 1, params.requestedLoadSize, callback);
}
#Override
public void loadBefore(#NonNull LoadParams < Long > params, #NonNull LoadCallback < User > callback) {
/*List<User> items = fetchItemsBefore(params.key, params.requestedLoadSize);
callback.onResult(items);*/
Log.d(TAG, "loadBefore params " + (params.key - 1));
usersRepository.getUsersBefore(params.key - 1, params.requestedLoadSize, callback);
}
#NonNull#Override
public Long getKey(#NonNull User user) {
return user.getCreatedLong();
}
}
public MainFragment()
public MainFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
*/
public static MainFragment newInstance(String param1, String param2) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
//fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
/*if(activity != null){
activity.setTitle(R.string.main_frag_title);
}*/
View fragView = inflater.inflate(R.layout.fragment_main, container, false);
// prepare the Adapter
mUserArrayList = new ArrayList < >();
mProfileAdapter = new UsersAdapter();
// Initiate the viewModel
viewModel = ViewModelProviders.of(this).get(UsersViewModel.class);
// Initiate the RecyclerView
mProfileRecycler = (RecyclerView) fragView.findViewById(R.id.users_recycler);
mProfileRecycler.setHasFixedSize(true);
mProfileRecycler.setLayoutManager(new LinearLayoutManager(mActivityContext));
//viewModel.usersList.observe(this, mProfileAdapter::submitList);
//viewModel.getPagedListObservable().observe(this, new Observer<PagedList<User>>() {
viewModel.usersList.observe(this, new Observer < PagedList < User >> () {#Override
public void onChanged(#Nullable PagedList < User > items) {
System.out.println("onChanged");
if (items != null) {
new java.util.Timer().schedule(
new java.util.TimerTask() {#Override
public void run() {
// your code here
Log.d(TAG, "submitList size" + items.size());
mProfileAdapter.submitList(items);
}
},
5000);
}
}
});
mProfileRecycler.setAdapter(mProfileAdapter);
return fragView;
}
Update:
Well, I found a better solution than delaying submitList for 5 second. I decided to use a while loop until the data is received from firebase database, once items.size() is greater than 0 I stops the loop and submit the list to the adapter.
public class MainFragment extends Fragment {
private final static String TAG = MainFragment.class.getSimpleName();
private RecyclerView mUsersRecycler;
private ArrayList<User> mUserArrayList;
private UsersAdapter mUsersAdapter;
private Context mActivityContext;
private Activity activity;
private UsersViewModel viewModel;
public MainFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
*/
public static MainFragment newInstance(String param1, String param2) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
//fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Initiate viewModel for this fragment instance
viewModel = ViewModelProviders.of(this).get(UsersViewModel.class);
//viewModel.getPagedListObservable().observe(this, new Observer<PagedList<User>>() {
viewModel.usersList.observe(this, new Observer<PagedList<User>>() {
#Override
public void onChanged(#Nullable final PagedList<User> items) {
System.out.println("mama onChanged");
if (items != null ){
// Create new Thread to loop until items.size() is greater than 0
new Thread(new Runnable() {
int sleepCounter = 0;
#Override
public void run() {
try {
while(items.size()==0) {
//Keep looping as long as items size is 0
Thread.sleep(20);
Log.d(TAG, "sleep 1000. size= "+items.size()+" sleepCounter="+sleepCounter++);
if(sleepCounter == 1000){
break;
}
//handler.post(this);
}
//Now items size is greater than 0, let's submit the List
Log.d(TAG, "after sleep finished. size= "+items.size());
if(items.size() == 0 && sleepCounter == 1000){
// If we submit List after loop is finish with 0 results
// we may erase another results submitted via newer thread
Log.d(TAG, "Loop finished with 0 items. Don't submitList");
}else{
Log.d(TAG, "submitList");
mUsersAdapter.submitList(items);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
});
}
}
I am trying to get a message from the MQTT Broker using the Android service, but it does not work.
The library used is the Paho MQTT library, and the source code is as follows.
final MqttConnectOptions hIoTConnectionOptions = new MqttConnectOptions();
hIoTConnectionOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
hIoTConnectionOptions.setAutomaticReconnect(true);
hIoTConnectionOptions.setCleanSession(false);`
try {
hIoTAndroid = new MqttClient(ip_addr, clientID, new MemoryPersistence());
IMqttToken conToken = hIoTAndroid.connectWithResult(hIoTConnectionOptions);
hIoTAndroid.setCallback(MqttMessagingService.this);
conToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "onSuccess");
hIoTAndroid.setCallback(MqttMessagingService.this);
try {
IMqttToken subToken = hIoTAndroid.subscribeWithResponse(subtopic, 1);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG, "Successfully subscribe to: " + subtopic);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Couldn't subscribe to: " + subtopic);
}
});
} catch (MqttException | NullPointerException ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Failed Connection");
}
});
} catch (MqttException ex) {
Log.d(getClass().getCanonicalName(), "Connection attempt failed with reason code = " + ex.getReasonCode() + ":" + ex.getCause());
}
#Override
public void connectComplete(boolean reconnect, String serverURI) {
Log.d(TAG, "Connection is established....");
}
#Override
public void connectionLost(Throwable cause) {
Log.d(TAG, "The Connection was lost,,");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG, new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d(TAG, "Sent Message !");
}
The publish and deliveryComplete functions work fine, but the subscribe function and messagArrived do not work. Why?
I have write this simple code for getting tweets from twitter
public static void main(String[] args) throws TwitterException {
// TODO code application logic here
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("**********")
.setOAuthConsumerSecret("**************")
.setOAuthAccessToken("***************")
.setOAuthAccessTokenSecret("**************");
TwitterFactory tf= new TwitterFactory(cb.build());
twitter4j.Twitter tw= tf.getInstance();
List<Status> statuses = tw.getHomeTimeline();
for(Status status1 : statuses){
System.out.println(status1.getUser().getName()+ " : "+ status1.getText());
}
But I want to get about 4000 tweets in urdu language. I don't know how to do. please help me
With that code you will only get Tweets from the Timeline of the register user, from Twitter4j:
ResponseList getHomeTimeline() Returns the 20 most recent
statuses, including retweets, posted by the authenticating user and
that user's friends. This is the equivalent of /timeline/home on the
Web."
If you want to get at least 4000 tweets in urdu you could do several things, for example you could get the sample stream from Twitter:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("**********")
.setOAuthConsumerSecret("**************")
.setOAuthAccessToken("***************")
.setOAuthAccessTokenSecret("**************");
TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
.getInstance();
StatusListener listener = new StatusListener() {
#Override
public void onStatus(Status status) {
System.out.println("#"+status.getUser().getScreenName()+": "+status.getText());
// HERE YOU STORE YOUR TWEETS
}
#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
#Override
public void onDeletionNotice(StatusDeletionNotice arg0) {
// TODO Auto-generated method stub
}
#Override
public void onScrubGeo(long arg0, long arg1) {
}
#Override
public void onStallWarning(StallWarning arg0) {
// TODO Auto-generated method stub
System.out.println(arg0);
}
#Override
public void onTrackLimitationNotice(int arg0) {
// TODO Auto-generated method stub
System.out.println(arg0);
}
};
twitterStream.addListener(listener);
twitterStream.sample("ur");
Until you get the 4000 tweets that you want.
You can use twitter search instead of just getting specific user's tweets. What I have done for getting tweets in Turkish language is just using twitter's advanced search feature. In my situation adding lang:tr after specified search phrase returned tweets in Turkish language to me. You can use lang:ur instead of lang:tr for getting tweets in Urdu Language.
Here is my code:
public class TwitterDataGetter implements Runnable {
private Thread twitterDataGetterThread;
final static Logger logger = Logger.getLogger(TwitterDataGetter.class);
public TwitterDataGetter() {
try {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("your consumer key");
cb.setOAuthConsumerSecret("your consumer secret");
cb.setOAuthAccessToken("your access token");
cb.setOAuthAccessTokenSecret("your access token secret");
cb.setIncludeEntitiesEnabled(true);
this.twitter = new TwitterFactory(cb.build()).getInstance();
logger.info("Twitter API Configuration Successful");
} catch (Exception e) {
logger.error("Twitter API Configuration Error", e);
}
}
public void getTweet(String keyword){
List<Status> statuses = null;
Query query;
QueryResult result;
try {
query = new Query(keyword + " lang:tr");
query.setCount(100);
do {
final long startTime = System.nanoTime();
result = twitter.search(query);
statuses = result.getTweets();
for (Status status : statuses) {
System.out.println(status.getText());
}
final long duration = System.nanoTime() - startTime;
if((5500 - duration/1000000) > 0){
Thread.sleep((5500 - duration/1000000));
}
} while ((query = result.nextQuery()) != null);
} catch (TwitterException e) {
logger.error("TwitterException", e);
} catch (InterruptedException e) {
logger.error("InterruptedException", e);
throw new RuntimeException(e);
}
}
#Override
public void run() {
while(true){
this.getTweet("");
}
}
public void start(){
if(twitterDataGetterThread == null){
twitterDataGetterThread = new Thread(this, "Twitter Thread");
}
twitterDataGetterThread.start();
logger.info("Twitter Thread started");
}
}
Calling getTweet(String keyword) method with empty string returns latest tweets in your language without filtering them with any keyword.
Hope it helps.
PS: you can also check search results for your language from this link https://twitter.com/search?f=tweets&vertical=default&q=lang%3Aur
I have an app that uses a browserfield to connect to a web-page.
All is working ok and the simulator shows the right page.
If I set the simulator Network Properties to "Out of Coverage" and click on a link in my web-page then I get an exception - in the BrowserFieldConnectionManagerImpl
How can catch this exception so I can take appropriate action?
The app is using BlackBerry SDK
The code is here:
public final class example_Screen extends MainScreen {
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
protected MyBrowserFieldErrorHandler(BrowserField browserField){
super(browserField);
}
public void displayContentError(String url, String errorMessage) {
System.out.println("JERRY: displayContentError" + url);
System.out.println("JERRY: displayContentError" + errorMessage);
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void navigationRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public InputConnection resourceRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
InputConnection connection = null;
return connection;
}
}
/**
* Creates a new example_Screen object
*/
public example_Screen() {
GIFEncodedImage ourAnimation = (GIFEncodedImage) GIFEncodedImage.getEncodedImageResource("2.gif");
AnimatedGIFField _ourAnimation = new AnimatedGIFField(ourAnimation, Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourAnimation);
LabelField _ourLabelField = new LabelField("Updating ...", Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourLabelField);
int anim_ht = _ourAnimation.getPreferredHeight();
int label_ht = _ourLabelField.getPreferredHeight();
EncodedImage ei = EncodedImage.getEncodedImageResource("img/menu.png");
int currentWidthFixed32 = Fixed32.toFP(ei.getWidth());
int currentHeightFixed32 = Fixed32.toFP(ei.getHeight());
int displayWidthFixed32 = Fixed32.toFP(Display.getWidth());
int displayHeightFixed32 = Fixed32.toFP((Display.getHeight() - anim_ht - label_ht));
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, displayWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, displayHeightFixed32);
ei = ei.scaleImage32(scaleXFixed32, scaleYFixed32);
BitmapField bmp = new BitmapField(ei.getBitmap(), Field.FIELD_HCENTER + Field.FIELD_VCENTER);
add(bmp);
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
browserField.requestContent("http://www.bbc.co.uk");
BrowserFieldListener listener = new BrowserFieldListener() {
public void documentAborted(BrowserField browserField, Document document) {
System.out.println("JERRY: documentAborted");
}
public void documentCreated(BrowserField browserField, ScriptEngine scriptEngine, Document document) {
System.out.println("JERRY: documentCreated");
}
public void documentError(BrowserField browserField, Document document) {
System.out.println("JERRY: documentError");
}
public void documentLoaded(BrowserField browserField, Document document) {
System.out.println("JERRY: documentLoaded");
Node node = document.getFirstChild();
String nodeText = node.getTextContent();
int index = -1;
if (nodeText != null) {
String errorText = "Error requesting content for:";
index = nodeText.indexOf(errorText);
}
Screen screen = browserField.getScreen();
try {
synchronized (Application.getEventLock()) {
if (index == -1) {
System.out.println("JERRY: documentLoaded: no error");
int count = screen.getFieldCount();
if (count > 1) {
screen.deleteRange(0, (count-1));
System.out.println("JERRY: documentLoaded: " + (count-1) + " fields deleted");
} else {
System.out.println("JERRY: documentLoaded: only 1 field so none deleted");
}
} else {
System.out.println("JERRY: documentLoaded: error");
}
}
} catch (final Exception ex) {
System.out.println("example_Screen: documentLoaded: exception caught: " + ex.toString());
}
}
public void documentUnloading(BrowserField browserField, Document document) {
System.out.println("JERRY: documentUnloading");
}
public void downloadProgress(BrowserField browserField, ContentReadEvent event) {
System.out.println("JERRY: downloadProgress");
}
};
browserField.addListener(listener);
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler(browserField);
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER, eHandler);
}
}
BrowserField contains a method, addListener() which takes a reference to BrowserFieldListener implementation.
Extend BrowserFieldListener and process errors in methods documentError() and documentAborted() of this implementation.
Then add a reference of your class instance that extends BrowserFieldListener to your browser field via browserField.addListener(browserFieldListener);.
EDIT:
If this does not work, then use BrowserFieldErrorHandler class from RIM API. Build your own error handler and pass its instance to the browserfield configuration.
Below, there's sample code:
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
public void displayContentError(String url, String errorMessage) {
String error = "Error: (url=" + url + "): " + t.getMessage();
Dialog.ask(Dialog.D_OK, error);
logMessage(“BrowserFieldError: “ + error );
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t){
displayContentError(request.getURL(), t.getMessage());
}
}
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler();
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER,eHandler);
I get this sample code from DevCon2010 presentation of BrowserField capabilities. You can get it here: http://dev.tuyennguyen.ca/wp-content/uploads/2011/02/DEV49.pdf