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
Related
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 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.
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();
}
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?
How i can refresh listfragment? no tutorials from net work :(
i have no idea, how reload this listfragment. I tried reload by transaktionmanager, but its colide with ActionBar.TabListener, this is not support.v4. how can i retrieve new data from loadermanager and update listfragment?
Activity:
package sk.test;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;
import sk.test.frags.TodoFragment;
import sk.test.prefs.EditPreferences;
import sk.test.task.DataListLoader;
import sk.test.xml.Item;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
private TodoFragment todoFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(getApplicationContext(), EditPreferences.class));
return true;
case R.id.refresh:
//HERE CODE FOR RELOAD todoFragment.reloadData() ????
return true;
default:
return true;
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private boolean wantDone = false;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
todoFragment = new TodoFragment();
this.wantDone = position == 0 ? false : true;
Bundle args = new Bundle();
args.putBoolean(TodoFragment.TASK_TYPE, this.wantDone);
todoFragment.setArguments(args);
return todoFragment;
}
#Override
public int getCount() {
return 2;
}
public boolean getWantDone(){
return this.wantDone;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.todotask_planned).toUpperCase(l);
case 1:
return getString(R.string.todotask_done).toUpperCase(l);
}
return null;
}
}
}
ListFragment:
package sk.test;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import java.util.List;
import sk.test.adapter.CustomArrayAdapter;
import sk.test.task.DataListLoader;
import sk.test.xml.Item;
/**
* Created by Peter on 29.7.2013.
*/
public class TodoFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<Item>> {
public static String TASK_TYPE = "taskType";
private static final String XML_SOURCE = "http://******/";
private boolean wantDone = false;
CustomArrayAdapter mAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("TODOLIST", "DataListFragment.onActivityCreated");
this.wantDone = getArguments().getBoolean(TASK_TYPE);
// Initially there is no data
setEmptyText("No Data Here");
// Create an empty adapter we will use to display the loaded data.
mAdapter = new CustomArrayAdapter(getActivity());
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
setHasOptionsMenu(true);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Insert desired behavior here.
Log.i("TODOLIST", "Item clicked: " + id);
}
#Override
public Loader<List<Item>> onCreateLoader(int i, Bundle bundle) {
Log.i("TODOLIST", "DataListFragment.onCreateLoader");
return new DataListLoader(getActivity(), this.wantDone);
}
#Override
public void onLoadFinished(Loader<List<Item>> listLoader, List<Item> items) {
mAdapter.setData(items);
Log.i("TODOLIST", "DataListFragment.onLoadFinished");
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
#Override
public void onLoaderReset(Loader<List<Item>> listLoader) {
}
public void reloadData(){
//UPDATE LIST.. HOW?
}
}
Loader:
package sk.test;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sk.test.commons.Commons;
import sk.test.xml.Item;
import sk.test.xml.Response;
/**
* Created by Peter Chovan on 29.7.2013.
*/
public class DataListLoader extends AsyncTaskLoader<List<Item>> {
private List<Item> todoTasks;
private boolean wantDone;
SharedPreferences prefs;
public DataListLoader(Context context, boolean wantDone) {
super(context);
this.wantDone = wantDone;
prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
}
#Override
public List<Item> loadInBackground() {
Log.i("TODOLIST", "DataListLoader.loadInBackground");
String xmlData = getXmlData(prefs.getString("service_url", "http://*****/"));
List<Item> entries = new ArrayList<Item>();
String state = wantDone ? "WANT DONE" : "WANT PLANNED";
if (xmlData != null) {
xmlData = xmlData.replaceAll("<([^/]+?)/>", "<$1> </$1>");
Serializer serializer = new Persister();
try {
Response res = serializer.read(Response.class, xmlData, false);
for (Item i : res.getItems().getItem()) {
if (i.isDone() == wantDone) {
entries.add(i);
}
}
} catch (Exception e) {
for (StackTraceElement s : e.getStackTrace()) {
Log.e("TEST serializer", s.toString());
}
}
} else {
Log.e("TODOLIST DATA", "NULL");
}
return entries;
}
public String getXmlData(String uri) {
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Accept", "application/xml");
Map<String, String> params = new HashMap<String, String>();
params.put("user", prefs.getString("service_login", "devel"));
params.put("pass", prefs.getString("service_password", "devel"));
params.put("class", "GetList");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(Commons.getRequestData(params)); //add request params
wr.flush();
String xmlData = readStream(con.getInputStream());
wr.close();
con.disconnect();
return xmlData;
} catch (Exception e) {
for (StackTraceElement s : e.getStackTrace()) {
Log.e("TODOLIST", "doInBackground" + s.toString());
}
}
return null;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
String result = "";
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result += line + "\n";
}
return result;
} catch (IOException e) {
for (StackTraceElement s : e.getStackTrace()) {
Log.e("TODOLIST", "ReadStream || " + s.toString());
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
for (StackTraceElement s : e.getStackTrace()) {
Log.e("TODOLIST", "ReadStream || " + "Error while closing Reader");
}
}
}
}
return null;
}
/**
* Called when there is new data to deliver to the client. The
* super class will take care of delivering it; the implementation
* here just adds a little more logic.
*/
#Override
public void deliverResult(List<Item> listOfData) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (listOfData != null) {
onReleaseResources(listOfData);
}
}
List<Item> oldApps = listOfData;
todoTasks = listOfData;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(listOfData);
}
// At this point we can release the resources associated with
// 'oldApps' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldApps != null) {
onReleaseResources(oldApps);
}
}
/**
* Handles a request to start the Loader.
*/
#Override
protected void onStartLoading() {
if (todoTasks != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(todoTasks);
}
if (takeContentChanged() || todoTasks == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Handles a request to cancel a load.
*/
#Override
public void onCanceled(List<Item> apps) {
super.onCanceled(apps);
// At this point we can release the resources associated with 'apps'
// if needed.
onReleaseResources(apps);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (todoTasks != null) {
onReleaseResources(todoTasks);
todoTasks = null;
}
}
/**
* Helper function to take care of releasing resources associated
* with an actively loaded data set.
*/
protected void onReleaseResources(List<Item> apps) {
}
}
Use this to restart the Loader: getLoaderManager().restartLoader(0, null, this);