PlaceAutocompleteFragment - Identify calling object in onPlaceSelected method - java

I created 2 objects of class PlaceAutocompleteFragment and set OnPlaceSelectedListener on both.
placePickup = (PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.place_source);
placePickup.setOnPlaceSelectedListener(this);
placeDrop = (PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.place_target);
placeDrop.setOnPlaceSelectedListener(this);
Now, I want to find a way to identify which object has invoked onPlaceSelected() method.
#Override
public void onPlaceSelected(Place place) {
latLng = place.getLatLng();
if (invoking object is placePickup){
do this;
}
if (invoking object is placeDrop){
do this;
}
}

you can maintain a boolean variable
when user clicks on pickUp make that variable true.
boolean isPickUp=false;
onCLlick of pickUp where you load PlaceAutoComplete fragment make it true;
and onCLick of drop make it false;
if (isPickUp){
do pickUp related work;
}
else{
do drop related work here;
}

Use Inline call like below.
placePickup = (PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.place_source);
placePickup.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.e(TAG,"Pick Up");
}
#Override
public void onError(Status status) {
}
});
placeDrop = (PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.place_target);
placeDrop.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.e(TAG,"Drop");
}
#Override
public void onError(Status status) {
}
});

Related

Boolean Listener

I've been trying to find a way to create a listener for a boolean on an android code reader. Essentially what I want to happen is, when it stops reading, perform action. So far I've based it off of this example, and have this:
Class:
public class scanStatusListener {
ScanManager scanManager;
private boolean scanStatus = scanManager.isReading(); //this returns if the reader is scanning or not
private ChangeListener listener;
public void setListener(ChangeListener listener) {
this.listener = listener;
}
public interface ChangeListener {
void onChange();
}
}
Activity:
public class ScanHook extends Service implements ScanManager.DataListener, scanStatusListener.ChangeListener{
private ScanManager _scanManager;
#Override
public void onCreate() {
super.onCreate();
_scanManager = ScanManager.createScanManager(getApplicationContext());
scanStatusListener ss = new scanStatusListener();
ss.setListener(new scanStatusListener.ChangeListener() {
public void onChange() {
//perform action
}
});
}
The issue I am getting is:
private boolean scanStatus = scanManager.isReading();
is getting an error saying that I cannot invoke on a null object reference.
I also tried using the LiveData suggestion:
MutableLiveData<Boolean> listen_bool=new MutableLiveData<>();
listen_bool.observe((LifecycleOwner) this, new Observer<Boolean>() {
#Override
public void onChanged(Boolean aBoolean) {
//perform action
}
});
listen_bool.setValue(_scanManager.isReading());
however I am getting an error saying I cannot cast to androidx.lifecycle.LifecycleOwner
Any suggestions?

Callback codes execution

I am trying to understand callbacks in Java, but it's confusing me a lot. I know callbacks are passed as an object by implementing interface. But I'm not able to understand how the functions of those passed objects in arguments are invoked.
I took this example
interface ClickEventHandler {
public void handleClick();
}
//Step 2: Create a callback handler
//implementing the above interface
class ClickHandler implements ClickEventHandler {
public void handleClick() {
System.out.println("Clicked");
}
}
//Step 3: Create event generator class
class Button {
public void onClick(ClickEventHandler clickHandler) {
clickHandler.handleClick();
}
}
public class Tester {
public static void main(String[] args) {
Button button = new Button();
ClickHandler clickHandler = new ClickHandler();
//pass the clickHandler to do the default operation
button.onClick(clickHandler);
Button button1 = new Button();
//pass the interface to implement own operation
button1.onClick(new ClickEventHandler() {
#Override
public void handleClick() {
System.out.println("Button Clicked");
}
});
}
}
Output is
```none
Clicked Button
Clicked.
I mean to invoke the function of passed objects we need to register it and call the functions. How does it work in case of listeners? It would be helpful if someone guide me in understanding this.
Well, you'd normally maintain a reference to ClickEventHandler (or even a list if you want to support multiple) and call the method when the button is clicked.
Example:
class Button {
private ClickEventHandler clickHandler;
public void onClick(ClickEventHandler clickHandler) {
this.clickHandler = clickHandler;
}
public void click() {
if( clickHandler != null ) {
clickHandler.handleClick();
}
}
Now when you invoke onClick() the listener is only registered and it will only be executed when the button is clicked (i.e. you call the click() method).
Its easy you just need to create interface
interface HandleClick {
void onItemClick(Boolean success);
}
There's some function to do some work and you need something to return
public static void someFunctions(String params, HandleClick handleClick) {
//some work to do here.
handleClick.onItemClick(true);
}
You can call it anywhere
class Main extends AppCompatActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
Callbacks.someFunctions("param", new HandleClick() {
#Override
public void onItemClick(Boolean success) {
}
});
}
}
I wrote a simple code to understand how we can do the same callback in 2 different ways.
interface InterestingEvent
{
public void interestingEvent ();
}
public class Test
{
private InterestingEvent ie;
public void EventNotifier (InterestingEvent event)
{
ie = event;
ie.interestingEvent();
}
public static void main(String[] args) {
Test test= new Test();
test.EventNotifier(new InterestingEvent() {
#Override
public void interestingEvent() {
System.out.println("I am callback code");
}
});
}
}
public class Test implements InterestingEvent{
#Override
public void interestingEvent() {
System.out.println("Hello i am callback code");
}
public void EventNotifier ()
{
this.interestingEvent();
}
public static void main(String[] args) {
Test test =new Test();
test.EventNotifier();
}
}

setOnUtteranceProgressListener not at all working for Text To Speech for API > 21

I want setOnUtteranceProgressListener should notify a Toast after the speech is completed.It seems not working.
I have used setOnUtteranceProgressListener and on the speak function i have mentioned the paramaters as follows..
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, MainActivity.this.getPackageName());
I have given a "UniqueId" while calling speak function as follows.
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,params,"UniqueId");
In My program after the text to speech engine finishes speaking it should run a Toast notifying that it has finished speaking.But the setOnUtteranceProgressListner seems not working.
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
Toast.makeText(MainActivity.this,"Finished speaking.",Toast.LENGTH_LONG).show();
}
#Override
public void onError(String utteranceId) {
}
});
The all Code is as follows..
public class MainActivity extends AppCompatActivity {
String message;
private TextToSpeech myTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(myTTS.getEngines().size() == 0){
Toast.makeText(MainActivity.this,"No Engines Installed",Toast.LENGTH_LONG).show();
}else{
myTTS.setLanguage(Locale.US);
if (status == TextToSpeech.SUCCESS){
//Toast.makeText(MainActivity.this,"Status working.",Toast.LENGTH_LONG).show();
message = "How may i help you.";
}
}
}
});
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
Toast.makeText(MainActivity.this,"onDone working.",Toast.LENGTH_LONG).show();
}
#Override
public void onError(String utteranceId) {
}
});
}
Please give a solution for this.
The main problems are:
1) Setting the progress listener before the tts is initialized.
2) Trying to make a Toast from a background thread.
I also have some other suggested changes but they are not required:
public class MainActivity extends AppCompatActivity {
String message = "How may I help you?";
String mostRecentUtteranceID;
private TextToSpeech myTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(myTTS.getEngines().size() == 0){
Toast.makeText(MainActivity.this,"No Engines Installed",Toast.LENGTH_LONG).show();
}else{
if (status == TextToSpeech.SUCCESS){
ttsInitialized();
}
}
}
});
}
private void ttsInitialized() {
// *** set UtteranceProgressListener AFTER tts is initialized ***
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
// this method will always called from a background thread.
public void onDone(String utteranceId) {
// only respond to the most recent utterance
if (!utteranceId.equals(mostRecentUtteranceID)) {
Log.i("XXX", "onDone() blocked: utterance ID mismatch.");
return;
} // else continue...
boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
Log.i("XXX", "was onDone() called on a background thread? : " + wasCalledFromBackgroundThread);
Log.i("XXX", "onDone working.");
// for demonstration only... avoid references to
// MainActivity (unless you use a WeakReference)
// inside the onDone() method, as it
// can cause a memory leak.
runOnUiThread(new Runnable() {
#Override
public void run() {
// *** toast will not work if called from a background thread ***
Toast.makeText(MainActivity.this,"onDone working.",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
// set Language
myTTS.setLanguage(Locale.US);
// set unique utterance ID for each utterance
mostRecentUtteranceID = (new Random().nextInt() % 9999999) + ""; // "" is String force
// set params
// *** this method will work for more devices: API 19+ ***
HashMap<String, String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mostRecentUtteranceID);
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,params);
}
}
If you want to add the call back OnUtteranceProgressListener you have to implement the speak method like this:
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH, null , TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID);
Then it will call the methods that you've already implemented (onStart, onDone, etc)

Create a Service that gets GPS coordinates and sends them to server

I am working on a prototype Android app that sends gps data to a server. I had something working when I called my class GetLocation directly from my MainActivity class. However, I would want this to really work as a background service. I tried using similar code, but for some reason the LocationListener's functions never get called (the only one I'm looking at is the onLocationChanged). Am I misunderstanding how this works? Thanks. Here's my code.
public class GetLocation {
...
public GetLocation(Context myContext, String hostParam)
{
this.context = myContext;
sendMessage = false;
sendData = new SendData(Constants.HOST_NAME);
locationManager = (LocationManager) context.getSystemService((Context.LOCATION_SERVICE));
this.host = hostParam;
locationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
String sentence = AssembleSentence.assembleNMEAURL(location);
//sendData.sendMessage(sentence);
int geozoneLocation = GeoZone.getGeozoneLocation(location);
switch(geozoneLocation)
{
case GeoZone.LEVEL_ONE:
sendMessage = false;
if(Constants.LEVEL_ONE_INTERVAL != currentInterval)
{
startLocationUpdates(Constants.LEVEL_ONE_INTERVAL, LocationManager.NETWORK_PROVIDER);
}
break;
case GeoZone.LEVEL_TWO:
sendMessage = false;
if(Constants.LEVEL_ONE_INTERVAL != currentInterval)
{
startLocationUpdates(Constants.LEVEL_TWO_INTERVAL, LocationManager.NETWORK_PROVIDER);
}
break;
case GeoZone.LEVEL_THREE:
sendMessage = false;
if(Constants.LEVEL_ONE_INTERVAL != currentInterval)
{
startLocationUpdates(Constants.LEVEL_THREE_INTERVAL, LocationManager.NETWORK_PROVIDER);
}
break;
case GeoZone.LEVEL_FOUR:
sendMessage = true;
if(Constants.LEVEL_ONE_INTERVAL != currentInterval)
{
startLocationUpdates(Constants.LEVEL_FOUR_INTERVAL, LocationManager.GPS_PROVIDER);
}
break;
}
if(sendMessage)
{
sendData.sendMessage(sentence);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
};
}
....
}
Which is called by my Service class below.
public class TelematicsIntent extends Service
{
public TelematicsIntent()
{
}
#Override
public IBinder onBind(Intent intent)
{
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate()
{
GetLocation location = new GetLocation(this, Constants.HOST_NAME);
}
#Override
public void onDestroy()
{
}
}
And this Service class is called by the MainActivity class. I know that the GetLocation class is being called correctly, as I set up a break point in the
this.host = hostParam and the code stopped there, but I put another break point in the statement int geozoneLocation = GeoZone.getGeozoneLocation(location); where GeoZone class is another class that just goes through the location data and returns whether the location is inside a particular area. Any ideas?
I figured out why it wasn't being called. I forgot to actually start the location services, as I had no way in the code for them to actually start. I should have seen this earlier, but I guess I didn't.

Got error 101, "invalid application id" at Android Facebook Logout

I have a class which extends ListFragment. MyloginToFacebook()method (see below) works. But once I want to logout and call logoutFromFacebook(), I receive the following error:
{"error_code":101,"error_msg":"Invalid application ID.","request_args":[{"key":"method","value":"auth.expireSession"},{"key":"format","value":"json"}]}
Here are my methods:
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
//---------------------------//
public void logoutFromFacebook() {
mAsyncRunner.logout(getActivity(), new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
btnLogout.setVisibility(View.INVISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
I just wonder if the cause of the problem is extends ListFragment, because when I tried with extends Activity, it runs well.
Would someone out there help me out to solve this problem? any helps would be appreciated.
Thank you

Categories

Resources