How to pass onReceived data between classes Android - java

I have 2 different class, first class Tracking.java and second class ReportingService.java. how to passing location address on ReportingService.java to Tracking.java?
private void doLogout(){
Log.i(TAG, "loginOnClick: ");
//ReportingService rs = new ReportingService();
//rs.sendUpdateLocation(boolean isUpdate, Location);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(NetHelper.getDomainAddress(this))
.addConverterFactory(ScalarsConverterFactory.create())
.build();
ToyotaService toyotaService = retrofit.create(ToyotaService.class);
// caller
Call<ResponseBody> caller = toyotaService.logout("0,0",
AppConfig.getUserName(this),
"null");
// async task
caller.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i(TAG, "onResponse: "+response.body().string());
}catch (IOException e){}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "onFailure: ", t);
}
});
AppConfig.saveLoginStatus(this, AppConfig.LOGOUT);
AppConfig.storeAccount(this, "", "");
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
finish();
}
This code for location address
Call<ResponseBody> caller = toyotaService.logout("0,0",
AppConfig.getUserName(this),
"null");
And this is class ReportingService.java location of code get longtitude, latitude and location address from googlemap
private void sendUpdateLocation(boolean isUpdate, Location location) {
Log.i(TAG, "onLocationChanged "+location.getLongitude());
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
String street = "Unknown";
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knowName = addresses.get(0).getFeatureName();
street = address + " " + city + " " + state + " " + country + " " + postalCode + " " + knowName;
Log.i(TAG, "street "+street);
}
} catch (IOException e) {
e.printStackTrace();
}
if (isUpdate)
NetHelper.report(this, AppConfig.getUserName(this), location.getLatitude(),
location.getLongitude(), street, new PostWebTask.HttpConnectionEvent() {
#Override
public void preEvent() {
}
#Override
public void postEvent(String... result) {
try {
int nextUpdate = NetHelper.getNextUpdateSchedule(result[0]); // in second
Log.i(TAG, "next is in " + nextUpdate + " seconds");
if (nextUpdate > 60) {
dismissNotification();
isRunning = false;
} else if (!isRunning){
showNotification();
isRunning = true;
}
handler.postDelayed(location_updater, nextUpdate * 1000 /*millisecond*/);
}catch (JSONException e){
Log.i(TAG, "postEvent error update");
e.printStackTrace();
handler.postDelayed(location_updater, getResources().getInteger(R.integer.interval) * 1000 /*millisecond*/);
}
}
});
else
NetHelper.logout(this, AppConfig.getUserName(this), location.getLatitude(),
location.getLongitude(), street, new PostWebTask.HttpConnectionEvent() {
#Override
public void preEvent() {
}
#Override
public void postEvent(String... result) {
Log.i(TAG, "postEvent logout "+result);
}
});
}
Thanks

Use this library and follow the provided example inside it.
Its for passing anything you wish to anywhere you wish.

i think just using an interface will solve your problem.
pseudo code
ReportingException.java
add this
public interface myLocationListner{
onRecievedLocation(String location);
}
private myLocationListner mylocation;
//add below line where you get street address
mylocation.onRecievedLocation(street);
then implement myLocationListner in Tracking.java
there you go :)

You can use an intent:
The intent will fire the 2nd Receiver and will pass the data into that
If BroadcastReceiver:
Intent intent = new Intent();
intent.setAction("com.example.2ndReceiverFilter");
intent.putExtra("key" , ); //put the data you want to pass on
getApplicationContext().sendBroadcast(intent);
If Service:
Intent intent = new Intent();`
intent.putExtra("key" , value ); //put the data you want to pass on
startService( ReportingService.this , Tracking.class);
in Tracking.java, to retrieve the Data you passed on:
inside onReceive, put this code first
intent.getExtras().getString("key");//if int use getInt("key")

Related

How to restrict to particular city results using Places API android

I had a requirement that if suppose the city is Hyderabad then using places search API I need to get only Hyderabad places while searching. But I am getting only a few places in search. how to get all the places related to Hyderabad city. Please anyone can help me out.
I have tried the code:
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), "apikey");
}
final AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autofill);
autocompleteFragment.setCountry("IN");
final Button closeBtn = dialog.findViewById(R.id.close_btn);
dialog.show();
autocompleteFragment.setLocationRestriction(RectangularBounds.newInstance(
new LatLng(17.387140, 78.491684),
new LatLng(17.440081, 78.348915)));
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG));
autocompleteFragment.setTypeFilter(TypeFilter.ADDRESS);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
if (place.getAddress() != null) {
Log.e("Place", "Place: " + place.getName() + ", " + place.getId() + " , " + place.getAddress() + " , " + place.getLatLng());
// progressDialog.show();
// progressDialog.setCancelable(false);
double latitude = Objects.requireNonNull(place.getLatLng()).latitude;
Log.d("lat:", String.valueOf(latitude));
double longitude = place.getLatLng().longitude;
Log.d("lng:", String.valueOf(longitude));
String name = place.getName();
Geocoder geocoder = new Geocoder(PlacesSearch.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
String aa = addresses.get(0).getAddressLine(0);
Log.e("aa:", aa);
String[] ad = aa.split(",");
String street = ad[0] + "," + ad[1] + "," + ad[2];
String city1 = addresses.get(0).getLocality();
String state1 = addresses.get(0).getAdminArea();
String zip1 = addresses.get(0).getPostalCode();
String country1 = addresses.get(0).getCountryName();
String countryCode = addresses.get(0).getCountryCode();
System.out.println("countryCode"+countryCode);
placesearch.setText(aa);
// progressDialog.dismiss();
dialog.dismiss();
}
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.e("Place", "An error occurred: " + status);
}
});

How to print on a Canon LBP2900 or any printer using USB OTG?

Trying this...
public class MainActivity extends Activity {
PendingIntent mPermissionIntent;
Button btnCheck;
TextView textInfo;
UsbDevice device;
UsbManager manager;
private static final String ACTION_USB_PERMISSION = "com.mobilemerit.usbhost.USB_PERMISSION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCheck = (Button) findViewById(R.id.check);
textInfo = (TextView) findViewById(R.id.info);
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
textInfo.setText("");
checkInfo();
}
});
}
public void startPrinting(final UsbDevice printerDevice) {
new Handler().post(new Runnable() {
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run() {
try {
Log.e("Info", "Bulk transfer started");
usbInterface = printerDevice.getInterface(0);
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = manager.openDevice(device);
conn.claimInterface(usbInterface, true);
String myStringData = "\nThis \nis \nmy \nsample \ntext";
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request) {
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
// handler.sendMessage(m);
output_buffer.clear();
} else {
Log.e("Info", "No request recieved");
}
// int transfered = conn.bulkTransfer(endPoint,
// myStringData.getBytes(),
// myStringData.getBytes().length, 5000);
// Log.i("Info", "Amount of data transferred : " +
// transfered);
} catch (Exception e) {
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally {
try {
conn.releaseInterface(usbInterface);
Log.e("Info", "Interface released");
conn.close();
Log.e("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.e("Info", "Brodcast reciever unregistered");
} catch (Exception e) {
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
private void checkInfo() {
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
/*
* this block required if you need to communicate to USB devices it's
* take permission to device
* if you want than you can set this to which device you want to communicate
*/
// ------------------------------------------------------------------
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
// -------------------------------------------------------------------
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
String i = "";
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
manager.requestPermission(device, mPermissionIntent);
i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
+ "DeviceName: " + device.getDeviceName() + "\n"
+ "DeviceClass: " + device.getDeviceClass() + " - "
+ "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
+ "VendorID: " + device.getVendorId() + "\n"
+ "ProductID: " + device.getProductId() + "\n";
}
textInfo.setText(i);
if(!(i.equalsIgnoreCase("")))
{
startPrinting(device);
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
}
} else {
Log.d("ERROR", "permission denied for device " + device);
}
}
}
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
}
}
This code shows the device connected with OTG but Not Accepted as printer device to canon 2900b
Printer going in idle mode.
or phone got hanged

Reverse GeoCoding Android Issue

I'm having trouble converting coordinates to an actual address.
I have two variables that pull coordinates but I'm getting many errors when I tweak the code. The first error is "unreported exception IOException; must be caught or declared to be thrown" and then I add the try catch then another error pops up, "yourAddresses might not have been initialized.
I'm just trying to get the address, street, and city so I can append it into a textView.
#Override
public void onLocationChanged(Location location)
{
double latitude = location.getLongitude();
double longitude = location.getLatitude();
//t.append("\n " + location.getLongitude() + " " + location.getLatitude());
Geocoder geocoder;
List<Address> yourAddresses;
geocoder = new Geocoder(context, Locale.getDefault());
yourAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if (yourAddresses.size() > 0) {
String yourAddress = yourAddresses.get(0).getAddressLine(0);
String yourCity = yourAddresses.get(0).getAddressLine(1);
String yourCountry = yourAddresses.get(0).getAddressLine(2);
}
}
Thanks!
I used this code and its works for me....
public void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler)
{
Thread thread = new Thread()
{
#Override
public void run()
{
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
Address address = null;
try
{
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
if (addressList != null && addressList.size() > 0)
{
address = addressList.get(0);
}
}
catch (Exception e)
{
Log.e(TAG, "getAddressFromLocation:run: exception while getting address from location");
e.printStackTrace();
}
finally
{
Message message = Message.obtain();
message.setTarget(handler);
if (address != null)
{
message.what = 1;
Bundle bundle = new Bundle();
bundle.putString("thoroughFare", address.getThoroughfare());
bundle.putString("subThoroughFare", address.getSubThoroughfare());
bundle.putString("city", address.getLocality());
bundle.putString("state", address.getAdminArea());
bundle.putString("country", address.getCountryName());
bundle.putString("postalCode", address.getPostalCode());
bundle.putString("subAdminArea", address.getSubAdminArea());
bundle.putString("subLocality", address.getSubLocality());
message.setData(bundle);
}
else
{
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + "Longitude: " + longitude +
"\n Unable to get address for this location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
This is my GeoCoderHandler class....
private class GeoCoderHandler extends Handler
{
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 1:
String address = "";
Bundle bundle = msg.getData();
if (bundle.getString("subThoroughFare") != null)
{
if (!bundle.getString("subThoroughFare").equalsIgnoreCase("null"))
{
address = bundle.getString("subThoroughFare") + ", " +
bundle.getString("thoroughFare");
}
}
else
{
address = bundle.getString("thoroughFare");
}
tvAddress1.setText("");
tvAddress1.setText(address);
tvAddress2.setText("");
tvAddress2.setText(bundle.getString("subLocality"));
tvAddress3.setText("");
tvAddress3.setText(bundle.getString("subAdminArea"));
edtPinCode.setText("");
edtPinCode.setText(bundle.getString("postalCode"));
tvCity.setText("");
tvCity.setText(bundle.getString("city"));
tvState.setText("");
tvState.setText(bundle.getString("state"));
tvCountry.setText("");
tvCountry.setText(bundle.getString("country"));
break;
default:
tvAddress1.setText(getResources().getString(R.string.address_not_found));
tvAddress2.setText("");
tvAddress3.setText("");
edtPinCode.setText("");
tvCity.setText("");
tvState.setText("");
tvCountry.setText("");
break;
}
}
}
your need some initialized for yourAddress
List<Address> yourAddresses = new ArrayList();

Java Android modifies member variables from Callback thread

Basically, I am trying to get some value from the Api callback response, then assign those value to some of my member variables, but It seems like the program has to run over my getPatientRecord() method each time before it could go to my call, which I have never encountered before.
The Log output result is :
viewPatient: paitient method
viewPatient: secondHello worldnullnull
100SN9 - David Hello H M H 1971-08-09
This is my code:
public class ViewPatientRecord extends AppCompatActivity{
TextView tvName, tvGender, tvBirthDate, tvAddress;
String pGender, pAddress, pBirthdate;
String pName = "Hello world";
Patient myPatient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_patient_record);
tvName = findViewById(R.id.tvFullName);
tvGender = findViewById(R.id.tvGender);
tvBirthDate = findViewById(R.id.tvDb);
tvAddress = findViewById(R.id.tvAddress);
myPatient= new Patient();
try {
getPatientRecord();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void getPatientRecord() throws InterruptedException {
SharedPreferences myPre = getSharedPreferences("PatientRecord", MODE_PRIVATE);
if(myPre.getString("uuid",null)!=null){
retrievePatientByUuid(myPre.getString("uuid",null));
Log.d("viewPatient", "second"+pName+pGender+pBirthdate);
tvName.setText(pName);
tvGender.setText(pGender);
tvBirthDate.setText(pBirthdate);
tvAddress.setText(pAddress);
}else{
Toast.makeText(ViewPatientRecord.this, "Something went wrong, please contact the administrator for help!", Toast.LENGTH_SHORT).show();
}
}
private void retrievePatientByUuid(String uuid) throws InterruptedException {
RestApi api = RetrofitInstance.getRetrofitInstance().create(RestApi.class);
Log.d("viewPatient", "paitient method");
Call<Patient> call = api.getPatientByUUID(uuid, null);
call.enqueue(new Callback<Patient>() {
private volatile Patient obj = new Patient();
#Override
public void onResponse(Call<Patient> call, Response<Patient> response) {
if (response.body() != null) {
Patient patient = response.body();
if (patient != null) {
if (!patient.getDisplay().isEmpty()) {
pName = patient.getDisplay();
pGender = patient.getPerson().getGender();
pBirthdate = patient.getPerson().getBirthdate();
Log.d("viewPatient", pName.toString() + " H " + pGender.toString() + " H " + pBirthdate.toString() + " ?? ");
pAddress = "";
} else {
Log.d("viewPatient", "no results");
}
} else {
Toast.makeText(ViewPatientRecord.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(ViewPatientRecord.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Patient> call, Throwable t) {
t.printStackTrace();
}
});
}
}
I don't see the problem. The call is done in retrievePatientByUuid which is called by getPatientRecord. So yes, you have to go through getPatientRecord. The call is async. It's in the callback that you should set your TextViews :
tvName.setText(pName);
tvGender.setText(pGender);
tvBirthDate.setText(pBirthdate);
tvAddress.setText(pAddress);

Geocoder is not working in android above kitkat version

I was working with geocoder in my android app to get country name using latitude and longitude. I found that it was working good in kitkat version and below. But when i test my app in above versions it was giving null. So my question is simple that how to use geocoder above kitkat versions.
If there is any other better option instead of geocoder then please suggest me!
Thanks in advance!
I post my code for Geocoder. Follow it
//Keep this GeocodingLocation.java in a separate file.
public class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public static void getAddressFromLocation( final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
String latitude = null;
String longitude = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Log.e("GeocodingLocation --> getAddressFromLocation ==>" +
addressList.toString());
Address address = (Address) addressList.get(0);
StringBuilder sb = new StringBuilder();
latitude = String.valueOf(address.getLatitude());
longitude = String.valueOf(address.getLongitude());
Logger.infoLog("GeocodingLocation --> Lat & Lang ==>" + latitude +" "+longitude);
//sb.append(address.getLatitude()).append("\n");
//sb.append(address.getLongitude()).append("\n");
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (latitude != null && longitude != null) {
message.what = 1;
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
call the class from your fragment.
private void getAddressLatitudeLongitude(String branchAddress) {
Log.e("getAddressLatitudeLongitude ==>" + branchAddress);
GeocodingLocation.getAddressFromLocation(branchAddress, thisActivity, new GeocoderHandler());
}
Keep this class as inner class in same fragment
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
try {
Bundle bundle = message.getData();
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
Log.e("CreateBranch --> GeocoderHandler ==>" + latitude + " " + longitude);
}catch (Exception e){
e.printStackTrace();
}
break;
default:
latitude = null;
longitude = null;
}
latitudeList.add(latitude);
longitudeList.add(longitude);
if(latitude==null || longitude==null){
showAlertDialog("Please enter correct address", Constants.APP_NAME);
}
Log.e("Latitude list =>" + latitudeList);
Log.e("Longitude list =>" + longitudeList);
}
}
Output will get latitude and longitude. Hope this answer helps.

Categories

Resources