Fragments MediaPlayer and moving back - android-fragments

I've got an app with Navigation Drawer using fragments. From One of the fragments that lists all tracks, I try to run a media player and show it's associated lyrics. But I'm unable to handle the back button of this fragment.
What I have done here only navigates back to the previous fragment. But I'm unable to click the ListView items after coming back and I'm also unable to click on my nav drawer in the mediaplayer or once I move back from the mediaplayer fragment. Anyone with any ideas?
Here's my code:
package com.myapp.slidingmenu;
import java.io.IOException;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.Toast;
import com.myapp.myplayer.R;
public class PlayTrackFragment extends Fragment implements MediaPlayerControl {
protected static final Fragment PlayTrackFragment = null;
public PlayTrackFragment(){}
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
private Handler mHandler = new Handler();
AssetFileDescriptor fd = null;
int iDispatchCounter = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_playtrack, container, false);
Bundle args = getArguments();
if (args != null && args.containsKey("id_User"))
{
String userId = args.getString("id_User");
Toast.makeText(rootView.getContext(),userId,Toast.LENGTH_SHORT).show();
}
WebView wv;
wv = (WebView) rootView.findViewById(R.id.webViewPlayTrack);
wv.loadUrl("file:///android_asset/traditions.html");
wv.setBackgroundColor(0x00000000);
wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
//AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor(mytracks[trackTitle].toString()+".mp3");
AssetFileDescriptor fd = null;
try {
fd = getActivity().getAssets().openFd("aa01.mp3");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (fd == null)
{
Toast.makeText(rootView.getContext(), "Expansion File Not Loaded", Toast.LENGTH_SHORT).show();
//return;
}
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(rootView.getContext()){
#Override
public void hide() {
this.show(0);
}
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && iDispatchCounter == 1)
{
iDispatchCounter++;
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
if(mMediaPlayer.isPlaying()){ mMediaPlayer.pause();}
//mMediaPlayer = null;
//mMediaController.hide();
mMediaController.setVisibility(View.GONE);
mMediaController = null;
HomeFragment homefragment = new HomeFragment();
PlayTrackFragment playtrackfragment = new PlayTrackFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, homefragment).commit();
fragmentTransaction2.remove(playtrackfragment).commit();
//fragmentTransaction.commit();
//mMediaPlayer.stop();
//mMediaPlayer = null;
//mMediaController = null;
//getActivity().finish();
//getActivity().onBackPressed();
//Todo: make finish work
//return true;
//Toast.makeText(rootView.getContext(),"Inside onDispatchKey",Toast.LENGTH_SHORT).show();
Log.i((String) getTag(), "onDispatch keyCode: " + event);
//getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
getFragmentManager().popBackStackImmediate();
return false;
}
return false;
}
};
//Original Lines
//mMediaController.setMediaPlayer(PlayTrack.this);
mMediaController.setBackgroundColor(Color.rgb(40, 40, 80));
mMediaController.setMediaPlayer(PlayTrackFragment.this);
mMediaController.setAnchorView(rootView.findViewById(R.id.layoutPlayTrack));
mMediaPlayer.setVolume(1f, 1f);
try {
mMediaPlayer.setDataSource( fd.getFileDescriptor(), fd.getStartOffset(),fd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
getActivity().setVolumeControlStream(AudioManager.STREAM_SYSTEM);
mMediaPlayer.start();
mMediaController.show(0);
}
});
}
});
/*rootView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_MOVE){
//mMediaController.show();
//do something
}
return true;
}
});*/
/*rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
rootView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Toast.makeText(rootView.getContext(),"Inside onKey",Toast.LENGTH_SHORT).show();
Log.i(getTag(), "onKey keyCode: " + keyCode);
if( keyCode == KeyEvent.KEYCODE_BACK ) {
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
return true;
} else {
return false;
}
}
});*/
return rootView;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100) / mMediaPlayer.getDuration();
return percentage;
}
#Override
public int getCurrentPosition() {
if (mMediaPlayer != null){return mMediaPlayer.getCurrentPosition();}
return 0;
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
}

I found a solution. I can hide the MediaController in the onDetach of the fragment.
#Override
public void onDetach() {
// TODO Auto-generated method stub
mMediaController.hide();
super.onDetach();
}
But there is still one problem. Although I can pull out my sliding drawer menu, I cannot click it. The MediaController seems to be on top of everything. How can I fix this please?

Related

SignalR Java Client not working in Android 12

I implemented SignalR Java Client in my Android Project. It works well on Android Versions 6 to 11 but fails on Android 12, I'm getting this error only on Android 12 java.net.SocketException: Socket closed [Ljava.lang.StackTraceElement;#e95116d, here is my code:
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.microsoft.signalr.OnClosedCallback;
import org.json.JSONObject;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import timber.log.Timber;
public class SignalRChatService {
Timer timer = new Timer();
public void startTimer()
{
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Your code here
Timer_Elapsed();
}
}, 1000, 2000);
}
private void Timer_Elapsed()
{
try
{
module.checkNetwork(context);
if(!Connected)
{
Init();
}
}
catch (Exception e)
{
Connected = false;
}
}
private HubConnection _connection;
public boolean Connected;
public String instanceName;
public int instanceProfileId;
private boolean connecting;
private SignalRMessageReceivedEvents signalRMessageReceivedEvents;
private final Gson gson;
private final Context context;
public SignalRChatService(Context context, String instanceName, int instanceProfileId, SignalRMessageReceivedEvents signalRMessageReceivedEvents) {
this.instanceName = instanceName;
this.instanceProfileId = instanceProfileId;
this.connecting = false;
this.context = context;
this.signalRMessageReceivedEvents = signalRMessageReceivedEvents;
gson = new GsonBuilder().setPrettyPrinting().create();
}
public void Stop()
{
try
{
_connection.stop();
}
catch(Exception ignored)
{}
}
public void Init()
{
if (connecting)
{
return;
}
try
{
connecting = true;
_connection = HubConnectionBuilder.create("https://" + instanceName.trim().toLowerCase() + ".com").build();
try
{
_connection.start();
Connected = true;
}
catch (Exception e)
{
Connected = false;
Timber.e("SignalR Push connect: %s", e.getLocalizedMessage());
return;
}
_connection.on("Message", (message) ->
{
try
{
// Separate this code affterwads
JSONObject messageObject = new JSONObject(message);
String Messagetype = (String) messageObject.get("messageType");
HandleWebSocketMessage(Messagetype, message);
}
catch (Exception ignored)
{
}
}, String.class);
_connection.onClosed(new OnClosedCallback() {
#Override
public void invoke(Exception exception) {
handleClosed();
}
});
}
catch (Exception ignored)
{
}
finally
{
connecting = false;
startTimer();
}
}
private void handleClosed()
{
try
{
TimeUnit.MILLISECONDS.sleep(100);
}
catch (Exception ignored)
{
}
Init();
}
}
I've tried upgrading to the latest version of SignalR Java Client
implementation "com.microsoft.signalr:signalr:6.0.3"
and it is still not working. It just wont receive any Signal.

I want to use GeoQuery for a selected branch from Firebase database

i am creating an app like Uber. I want the customer to be able to select from different types of cars as in Uber. To get the nearest driver available I am using GeoQuery with a radius but I don't know how to use GeoQuery for a special folder Like I Have a folder for Drivers with Sedan Car or SUV or Normal car. GeoQuery that I am using shows all the drivers near that location. I don't Know how to make it query only a selected folder.
This is the code I am using for customer side app.
package com.matt.dumate;
import com.directions.route.AbstractRouting;
import com.directions.route.Route;
import com.directions.route.RouteException;
import com.directions.route.Routing;
import com.directions.route.RoutingListener;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryEventListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Welcome extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, RoutingListener{
SupportMapFragment mapFragment;
private Button btnBooking;
private Location lastLocation;
private GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener;
private LocationRequest locationRequest;
private LocationListener locationListener;
private LocationManager locationManager;
private Marker marker, driverMarker;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private final int RequestCode = 10;
private final int ResourceCode = 11;
private DatabaseReference userLastLocation, customersUnderServiceRef, userRequest, driversOnDuty,workingDrivers, driverRef1, driverWorkingRef ;
GeoFire location, request, onDuty, customersUnderService;
private Boolean clicked = false;
private String driverID = "";
private ValueEventListener driverListener;
private GeoQuery geoQuery;
private String myId = "";
private Double driverLat, driverLng;
#Override
protected void onCreate(Bundle savedInstanceState)
{
checkLocationPermission();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
userLastLocation = FirebaseDatabase.getInstance().getReference("User LastLocation");
location = new GeoFire(userLastLocation);
setupLocation();
userRequest = FirebaseDatabase.getInstance().getReference("User Request");
request = new GeoFire(userRequest);
driversOnDuty = FirebaseDatabase.getInstance().getReference("DriversOnDuty");
onDuty = new GeoFire(driversOnDuty);
driverRef1 = FirebaseDatabase.getInstance().getReference().child("Driver").child(driverID);
driverWorkingRef = FirebaseDatabase.getInstance().getReference().child("DriversWorking");
customersUnderServiceRef = FirebaseDatabase.getInstance().getReference().child("CustomersUnderService");
customersUnderService = new GeoFire(customersUnderServiceRef);
workingDrivers = FirebaseDatabase.getInstance().getReference().child("DriversWorking").child(driverID);
}
#Override
public void onMapReady(GoogleMap googleMap)
{
myId = FirebaseAuth.getInstance().getCurrentUser().getUid();
setupUiViews();
mMap = googleMap;
displayLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode) {
case RequestCode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
break;
}
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
locationRequest = LocationRequest
.create()
.setInterval(1000)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
startLocationUpdates();
displayLocation();
}else {
checkLocationPermission();
}
}
#Override
public void onConnectionSuspended(int i)
{
googleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
displayLocation2();
}
public void checkLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
}
} else {
Toast.makeText(this, "Location Permissions Granted", Toast.LENGTH_SHORT).show();
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
private void setupUiViews()
{
btnBooking = findViewById(R.id.bookingButton);
btnBooking.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
startLocationUpdates();
displayLocation2();
getNearestDriver();
Toast.makeText(Welcome.this, "Getting Cab", Toast.LENGTH_SHORT).show();
btnBooking.setText("Getting Your Cab..");
clicked = true;
} else
{
disconnection();
try{
driverRef1.child("customerRideId").removeValue();
}catch (Exception a){
return;
}
stopLocationUpdates();
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Customer Request");
GeoFire geoFire1 = new GeoFire(databaseReference1);
geoFire1.removeLocation(userId);
Toast.makeText(Welcome.this, "Canceling Cab", Toast.LENGTH_SHORT).show();
btnBooking.setText("Get Cab");
if(driverMarker!=null){
driverMarker.remove();
}
clicked = false;
}
}
});
}
private void displayLocation()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null ){
final Double lat = lastLocation.getLatitude();
final Double lng = lastLocation.getLongitude();
location.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener()
{
#Override
public void onComplete(String key, DatabaseError error) {
if (marker != null) {
marker.remove();
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
}else{
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
}
}
});
}else{
Log.d("Error", "Cannot Get Your Location");
}
}
private void displayLocation2()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null ){
if(clicked == true){
final Double lat = lastLocation.getLatitude();
final Double lng = lastLocation.getLongitude();
request.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener()
{
#Override
public void onComplete(String key, DatabaseError error) {
if (marker != null) {
marker.remove();
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You"));
}else{
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You"));
}
}
});
}
}else{
Log.d("Error", "Cannot Get Your Location");
}
}
private void setupLocation()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
}
}else{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
}
}
}
private void createLocationRequest()
{
locationRequest = LocationRequest.create()
.setInterval(1500)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(0);
}
private boolean checkPlayServices()
{
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
{
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode, this, ResourceCode).show();
else {
Toast.makeText(this, "This Device Is Not Supported", Toast.LENGTH_SHORT).show();
finish();
}return false;
}
return true;
}
private void stopLocationUpdates()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void startLocationUpdates()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
private int radius = 1;
private Boolean driverFound = false;
private void getNearestDriver()
{
geoQuery = location.queryAtLocation(new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()), radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
String driverId = key;
if(!driverFound){
driverFound = true;
driverID = key;
DatabaseReference driverRef = FirebaseDatabase.getInstance().getReference().child("Driver").child(driverId);
String customerId = FirebaseAuth.getInstance().getCurrentUser().getUid();
HashMap map = new HashMap();
map.put("customerRideId", customerId);
driverRef.updateChildren(map);
driverID = key;
btnBooking.setText("Getting Driver Location");
customersUnderService.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()));
getDriverLocation();
}
}
#Override
public void onKeyExited(String key) {
disconnection();
}
#Override
public void onKeyMoved(String key, GeoLocation location) { }
#Override
public void onGeoQueryReady() {
if(!driverFound){
radius++;
getNearestDriver();
}
}
#Override
public void onGeoQueryError(DatabaseError error) {
disconnection();
Toast.makeText(Welcome.this, "GeoQuery Error", Toast.LENGTH_SHORT);
}
});
}
private void getDriverLocation()
{
driverWorkingRef = driverWorkingRef.child(driverID).child("l");
driverListener = driverWorkingRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLng = 0;
btnBooking.setText("Driver Found");
if (map.get(0) != null)
{
locationLat = Double.parseDouble(map.get(0).toString());
driverLat = locationLat;
}
if (map.get(1) != null)
{
locationLng = Double.parseDouble(map.get(1).toString());
driverLng = locationLng;
}
LatLng driverLatLng = new LatLng(locationLat, locationLng);
if (driverMarker != null) {
driverMarker.remove();
}
driverMarker = mMap.addMarker(new MarkerOptions().position(driverLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.carmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 15.0f));
Location myLoc = new Location("");
Location driverLoc = new Location("");
myLoc.setLatitude(lastLocation.getLatitude());
myLoc.setLongitude(lastLocation.getLongitude());
driverLoc.setLatitude(locationLat);
driverLoc.setLongitude(locationLng);
float distance = myLoc.distanceTo(driverLoc);
;
if (distance<100){
btnBooking.setText("Driver Reached");
}else{
btnBooking.setText("Driver at " + distance);
}
}getDriverLocation();
}
#Override
public void onCancelled(DatabaseError databaseError) {
disconnection();
}
});
}
#Override
public void onRoutingFailure(RouteException e)
{}
#Override
public void onRoutingStart()
{}
#Override
public void onRoutingSuccess(ArrayList<Route> arrayList, int i)
{}
#Override
public void onRoutingCancelled()
{}
private void disconnection(){
try {
customersUnderService.removeLocation(myId);
}catch(Exception b){ }
try {
driverWorkingRef.removeEventListener(driverListener);
}catch(Exception c){
}
try {
onDuty.setLocation(driverID,new GeoLocation(driverLat, driverLng));
}catch(Exception d){ }
try {
geoQuery.removeAllListeners();
}catch(Exception f){ }
try {
request.removeLocation(myId);
}catch(Exception g){ }
try
{
driverRef1.child("customerRideId").removeValue();
} catch(Exception h) { }
try
{
onDuty.setLocation(driverID,new GeoLocation(driverLat, driverLng));
} catch(Exception h) { }
driverFound = false;
if (driverMarker != null){
driverMarker.remove();
}
btnBooking.setText("Get Cab");
clicked = false;
}
#Override
protected void onStop()
{
super.onStop();
//disconnection();
}
private void getDirection(LatLng latLng)
{
Routing routing = new Routing.Builder()
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(true)
.waypoints(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), latLng)
.build();
routing.execute();
}
#Override
protected void onPause() {
super.onPause();
}
}
My database structure is given in this link https://drive.google.com/file/d/1MTde8DRZACFq5Q5l1rqp9AHygwgncyWN/view?usp=sharing. I tried to replace the code with my previous code that was running well but it crashed with the same error. I think the error is due to some other file which got created when I tried to replace Hashmap with List and Map. I don't know.

Music service Not Working with Album songs

I developing music app.so i create Music service that play in song background so that work perfectly good in when i play song.
But my question is we need different different service for all.
so when i use music Service for album for playing album song that not working.
i don'i know what to do
thanks in advance
that my code
package com.musicbox.google.musicboxlive.Musiclibrary;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import com.musicbox.google.musicboxlive.Musiclibrary.Song.Songpojo;
import com.musicbox.google.musicboxlive.R;
import java.util.ArrayList;
/**
* Created by Jiagr Fumakiya on 2/1/18.
*/
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
//media player
private MediaPlayer player;
//song list
private ArrayList<Songpojo> songpojos;
//current position
private int songPosn;
private final IBinder musicBind = new MusicBinder();
String songtitile;
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public void onCreate() {
super.onCreate();
songPosn = 0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Songpojo> theSongpojos) {
songpojos = theSongpojos;
}
public class MusicBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public void playSong() {
player.reset();
//get song
Songpojo playSongpojo = songpojos.get(songPosn);
songtitile = playSongpojo.getTitle();
//get id
long currSong = playSongpojo.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId
(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
//player.start();
}
public void nextsong() {
if (songPosn < (songpojos.size() - 1)) {
// play(currentSongIndex - 1);
songPosn = songPosn + 1;
} else {
songPosn = 0;
}
}
public void previousong() {
if (songPosn > 0) {
// play(currentSongIndex - 1);
songPosn = songPosn - 1;
} else {
songPosn = songpojos.size() - 1;
}
}
public void pause() {
if (player.isPlaying()) {
player.pause();
}
}
public void resume() {
int seek = player.getCurrentPosition();
if (!player.isPlaying()) {
player.seekTo(seek);
player.start();
}
}
public void isplaying() {
if (player.isPlaying()) {
player.reset();
}
}
#Override
public void onStart(Intent intent, int startId) {
Log.d("musicid", String.valueOf(startId));
super.onStart(intent, startId);
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
/* if (mp.isPlaying()) {
mp.reset();
} else {
mp.start();
}*/
mp.start();
Intent notIntent = new Intent(this, MusiclibraryHome.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songtitile)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(songtitile);
Notification not = builder.build();
startForeground(1, not);
}
public void setSong(int songIndex) {
songPosn = songIndex;
}
}
Yes..
After finding lot of online now i get that you need different method to handle each event in Music player (like album,song ,genres) all different.
that is method from playing song album wise in android.
public void playAlbum() {
player.reset();
//get Album song
AlbumPojo albumPojo = albumPojos.get(albumPosn);
id = albumPojo.getId();
songName = albumPojo.getTitle();
albumArt = albumPojo.getAlbumArt();
albumName = albumPojo.getAlbum();
artistName = albumPojo.getAlbum_artist();
Intent intent = new Intent("MusicServiceInfo");
intent.putExtra("songid", id);
intent.putExtra("songtitile", songName);
intent.putExtra("songimage", albumArt);
intent.putExtra("albumname", albumName);
intent.putExtra("artist", artistName);
sendBroadcast(intent);
Log.w("Albumart", "" + albumArt);
//set uri
Uri trackUri = ContentUris.withAppendedId
(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}

Java Android code in WinDev

I'm new in WinDev and I'm trying to create an Android application on a honeywell device with a barcode scanner.
I tried 2 different ways in Android Studio and they work.
One is the following:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.honeywell.scanintent.ScanIntent;
public class MainActivity extends Activity {
TextView barcodeData = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barcodeData = (TextView) findViewById(R.id.textView);
}
public void onSendButtonClick(View v) {
Intent intentScan = new Intent(ScanIntent.SCAN_ACTION);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
int loadmode = 0;
intentScan.putExtra("scan_mode",ScanIntent.SCAN_MODE_RESULT_AS_URI);
this.startActivityForResult(intentScan, 5);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == ScanIntent.SCAN_RESULT_SUCCESSED) {
String data = intent.getStringExtra(ScanIntent.EXTRA_RESULT_BARCODE_DATA);
int format = intent.getIntExtra(ScanIntent.EXTRA_RESULT_BARCODE_FORMAT, 0);
barcodeData.setText(data);
}
else{
barcodeData.setText("FALLITO");
}
}
}
And the other way is this:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import com.honeywell.decodemanager.DecodeManager;
import com.honeywell.decodemanager.SymbologyConfigs;
import com.honeywell.decodemanager.barcode.DecodeResult;
import com.honeywell.decodemanager.symbologyconfig.SymbologyConfigCode39;
public final class MainActivity extends Activity {
private final int ID_SCANSETTING = 0x12;
private final int ID_CLEAR_SCREEN = 0x13;
private final int SCANKEY = 0x94;
private DecodeManager mDecodeManager = null;
private TextView mDecodeResultEdit = null;
private final int SCANTIMEOUT = 2000;
long mScanAccount = 0;
private boolean mbKeyDown = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
mDecodeResultEdit = (TextView) findViewById(R.id.textView);
button.setOnTouchListener(new Button.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
try {
if (mbKeyDown) {
DoScan();
mbKeyDown = false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case MotionEvent.ACTION_UP:
try {
mbKeyDown = true;
cancleScan();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
return true;
}
});
}
private void DoScan() throws Exception {
try {
mDecodeManager.doDecode(SCANTIMEOUT);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if (mDecodeManager == null) {
mDecodeManager = new DecodeManager(this ,ScanResultHandler);
}
}
#Override
protected void onPause() {
super.onPause();
if (mDecodeManager != null) {
try {
mDecodeManager.release();
mDecodeManager = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private Handler ScanResultHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case DecodeManager.MESSAGE_DECODER_COMPLETE:
String strDecodeResult = "";
DecodeResult decodeResult = (DecodeResult) msg.obj;
strDecodeResult = "Decode Result::"+ decodeResult.barcodeData;
mDecodeResultEdit.setText(strDecodeResult);
break;
case DecodeManager.MESSAGE_DECODER_FAIL:
mDecodeResultEdit.setText("FAILED");
break;
case DecodeManager.MESSAGE_DECODER_READY:
{
try {
SymbologyConfigCode39 code39 = new SymbologyConfigCode39();
code39.enableCheckEnable(false);
code39.enableSymbology(false);
code39.setMaxLength(48);
code39.setMinLength(2);
SymbologyConfigs symconfig = new SymbologyConfigs();
symconfig.addSymbologyConfig(code39);
mDecodeManager.setSymbologyConfigs(symconfig);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
default:
super.handleMessage(msg);
break;
}
}
};
private void cancleScan() throws Exception {
mDecodeManager.cancelDecode();
}
}
On WinDev I created a GLOBAL JAVA PROCEDURE and I generated the application, importing the honeywell library, but I don't understand how to implement the android native functions. How can I do this?
Thank you so much!
First add a Global Procedure set to your project and then in this set create an empty Global procedure.
Once the procedure is created on its header bar click on the letters WL and it will convert to JAVA code mode. Now paste you JAVA code!
HTH
Yogi Yang

Trying to implement swipe movement

public class CoursesActivity extends SherlockFragmentActivity {
ArrayList<CourseData> mCoursesList = new ArrayList<CourseData>();
public CoursesListAdapter coursesListAdapter;
public ListView mList;
public AlertDialog.Builder dlgAlert;
public Dialog loginDialog;
public Dialog loginDialogOverflow;
LinearLayout progressBar;
static SQLiteWebcourse dbHelper;
private GestureDetectorCompat mDetector;
public final static String EXTRA_MESSAGE = "com.technion.coolie.webcourse.MESSAGE";
public CoursesActivity() {
dbHelper = new SQLiteWebcourse(this, "WebcoureDB", null, 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create list of courses
mCoursesList = new ArrayList<CourseData>();
setContentView(R.layout.web_activity_courses);
mList = (ListView) findViewById(R.id.courses_list);
dlgAlert = new AlertDialog.Builder(getApplicationContext());
if (!CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
loginDialog = CoolieAccount.WEBCOURSE.openSigninDialog(this);
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// Check if connection success
if (CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
// Connection SUCCESS
progressBar = (LinearLayout) findViewById(R.id.progressBarLayout_courses);
progressBar.setVisibility(View.VISIBLE);
asyncParse<CourseData> a = new asyncParse<CourseData>() {
#Override
protected List<CourseData> doInBackground(
String... params) {
// TODO Auto-generated method stub
try {
courseList crL = new courseList(
getApplicationContext());
crL.getCourses(CoolieAccount.WEBCOURSE
.getUsername(),
CoolieAccount.WEBCOURSE
.getPassword());
mCoursesList = dbHelper
.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doInBackground(params);
}
#Override
protected void onPostExecute(List<CourseData> result) {
// TODO Auto-generated method stub
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
progressBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
};
a.execute("");
} else {
// Connection FAILED
Log.v("dbAss", "Second Time");
}
}
};
loginDialog.setOnDismissListener(dismissListener);
} else {
mCoursesList = dbHelper.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
}
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
// OnItemClickListener itemClicked = new OnItemClickListener() {
//
// #Override
// public void onItemClick(AdapterView<?> list, View view,
// int position, long id) {
// // TODO Auto-generated method stub
// loadCourseInformationActivity(((CourseData) mList
// .getItemAtPosition(position)).CourseDescription);
// }
// };
// mList.setOnItemClickListener(itemClicked);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
this.mDetector.onTouchEvent(event);
// Be sure to call the superclass implementation
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.v(DEBUG_TAG,
"onFling: " + event1.toString() + event2.toString());
Toast.makeText(getApplicationContext(), "SWIPED", Toast.LENGTH_LONG)
.show();
if (event2.getX() - event1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
Toast.makeText(getApplicationContext(), "SWIPED",
Toast.LENGTH_LONG).show();
// if (showDeleteButton(e1))
// return true;
return super.onFling(event1, event2, velocityX, velocityY);
}
}
}
Hey fellas, i'm trying to implement swipe detection I went through android lesson and did exactly what is written there: http://developer.android.com/training/gestures/detector.html
For some reason when I touch the screen it doesnt go to onTouchEvent. What seems to be the problem?
You haven't set the touch listener to your ListView.
listView.setOnTouchListener(this);

Resources