referencing methods in other files - java

I am trying to use the getPermissiontoReadSMS and onRequestPermissionsResult methods in the permissionsSMSHelper class. When I reference them in the newMessagePage.java file and the onCreate method of the homePage.java file, it gives me the "cannot resolve method" error everytime. I cannot figure out what is wrong. If anyone can help, I'd appreciate it.
permisssionsSMSHelper.java
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
public class permissionsSMSHelper extends homePage {
public int READ_SMS_PERMISSIONS_REQUEST;
public permissionsSMSHelper(int req) {
READ_SMS_PERMISSIONS_REQUEST = req;
}
public void getPermissionToReadSMS(int reqVal) {
READ_SMS_PERMISSIONS_REQUEST = reqVal;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_SMS)) {
Toast.makeText(this, "Please allow permission", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.READ_SMS}, reqVal);
}
}
public RequestPermissionsResult(int req) {
READ_SMS_PERMISSIONS_REQUEST = req;
}
public void onRequestPermissionsResult(int requestCode,
int requestNum,
#NonNull String permissions[],
#NonNull int[] grantResults) {
READ_SMS_PERMISSIONS_REQUEST= requestNum;
if(requestCode == requestNum) {
if(grantResults.length == 1 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Read SMS permission granted", Toast.LENGTH_SHORT).show();
refreshSmsInbox();
}else {
Toast.makeText(this, "Read SMS permission denied", Toast.LENGTH_SHORT).show();
}
}else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
homePage.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
messages = (ListView) findViewById(R.id.messages);
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, smsMessagesList);
messages.setAdapter(arrayAdapter);
if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
permissionsSMSHelper SMScheck = new permissionsSMSHelper(1);
SMScheck.getPermissionToReadSMS(1);
SMScheck.onRequestPermissionsResult(1);
}else {
refreshSmsInbox();
}
addDrawerItems();
FABListener();
}
newMessagePage.java
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class newMessagePage extends homePage {
SmsManager smsManager = SmsManager.getDefault();
EditText input;
public void onSendClick(View view) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
permissionsSMSHelper SMScheck = new permissionsSMSHelper(1);
SMScheck.getPermissionToReadSMS(1);
SMScheck.onRequestPermissionsResult(1);
}else {
smsManager.sendTextMessage("17739965441", null, input.getText().toString(), null, null);
Toast.makeText(this, "Message sent!", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_message_page);
input = (EditText) findViewById(R.id.input);
}
}

You are doing it wrong. Your so called PermissionsSMSHelper class is extending HomePage and you are creating an instance of permissionsSMSHelper in HomePage and that and also in the case of NewMessagePage you are indirectly referencing an activity inside another class and that will result in a memory leak . Remove the extends homePage from PermissionsSMSHelper and pass a Context in the constructor or make the methods static inside PermissonsSMSHelper and pass Context in every method call. Your Naming convention is TOO BAD

Related

Waiting for the text optional module to be downloaded. Please wait. On Android Studio

I'm a new android developer and trying to make image to text app. I watched some tutorials and pretty sure that i don't make any mistakes. I'm using ML Kit for this project and got error when i tried to convert the image to text.
My main activity
package com.gorkemtand.textrecognition;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.latin.TextRecognizerOptions;
import java.io.IOException;
import java.security.Permission;
public class MainActivity extends AppCompatActivity {
private MaterialButton inputImageBtn;
private MaterialButton recognizeTextBtn;
private ShapeableImageView imageIv;
private EditText recognizedTextEt;
private static final String TAG = "MAIN_TAG";
private Uri imageUri = null;
//to handle the result of Camere/Gallery permissions
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
//arrays of permission required to pick image from Camera,gallery
private String[] cameraPermissions;
private String[] storagePermissions;
private ProgressDialog progressDialog;
private TextRecognizer textRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputImageBtn = findViewById(R.id.inputImageBtn);
recognizeTextBtn = findViewById(R.id.recognizeBtn);
imageIv = findViewById(R.id.imageIv);
recognizedTextEt = findViewById(R.id.recognizedTextEd);
cameraPermissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please Wait");
progressDialog.setCanceledOnTouchOutside(false);
textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
inputImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInputImageDialog();
}
});
recognizeTextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageUri == null){
Toast.makeText(MainActivity.this,"Pick image first...",Toast.LENGTH_SHORT).show();
}
else {
recognizeTextFromImage();
}
}
});
}
private void recognizeTextFromImage() {
Log.d(TAG, "recognizeTextFromImage: ");
progressDialog.setMessage("Preparing image...");
progressDialog.show();
try {
InputImage inputImage = InputImage.fromFilePath(this,imageUri);
progressDialog.setMessage("Recognizing text...");
Task<Text> textTaskResult = textRecognizer.process(inputImage).addOnSuccessListener(new OnSuccessListener<Text>() {
#Override
public void onSuccess(Text text) {
progressDialog.dismiss();
String recognizedText = text.getText();
Log.d(TAG, "onSuccess: recognizedText: "+recognizedText);
recognizedTextEt.setText(recognizedText);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Log.e(TAG, "onFailure: ",e);
Toast.makeText(MainActivity.this,"Failed recognizing text due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
progressDialog.dismiss();
Log.e(TAG, "recognizeTextFromImage: ",e);
Toast.makeText(MainActivity.this,"Failed preparing image due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
private void showInputImageDialog() {
PopupMenu popupMenu = new PopupMenu(this, inputImageBtn);
popupMenu.getMenu().add(Menu.NONE,1,1,"CAMERA");
popupMenu.getMenu().add(Menu.NONE,2,2,"GALLERY");
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if(id == 1){
Log.d(TAG, "onMenuItemClick: Camera Clicked...");
if(checkCameraPermissions()){
pickImageCamera();
}
else{
requestCameraPermissions();
}
}
else if(id == 2){
Log.d(TAG, "onMenuItemClick: Gallery Clicked...");
if(checkStoragePermision()){
pickImageGallery();
}
else{
requestStoragePermission();
}
}
return false;
}
});
}
private void pickImageGallery(){
Log.d(TAG, "pickImageGallery: ");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
galleryActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> galleryActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
//image picked
Intent data = result.getData();
imageUri = data.getData();
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
//set to imageview
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled...",Toast.LENGTH_SHORT).show();
}
}
}
);
private void pickImageCamera(){
Log.d(TAG, "pickImageCamera: ");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Sample Title");
values.put(MediaStore.Images.Media.DESCRIPTION, "Sample Description");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> cameraActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
);
private boolean checkStoragePermision(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this,storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermissions(){
boolean cameraResult = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean storafeResult = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return cameraResult && storafeResult;
}
private void requestCameraPermissions(){
ActivityCompat.requestPermissions(this,cameraPermissions, CAMERA_REQUEST_CODE);
}
//handle permission results
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && storageAccepted){
pickImageCamera();
}
else {
Toast.makeText(this, "Camera && Storage permissions are required", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
if(grantResults.length>0){
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted) {
pickImageGallery();
}
else {
Toast.makeText(this, "Storage permission is required", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
Also i implemented these two
implementation 'com.google.android.gms:play-services-mlkit-text-recognition:18.0.2'
implementation 'com.google.android.gms:play-services-mlkit-text-recognition-common:18.0.0'
And give the permissions to manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the error i got:
Error
I searched the google and cnat find a solution. If u can help me i will be very happy.
I searched google and can't find anything works.
I solved by implementing com.google.mlkit:text-recognition:16.0.0-beta6
Are you testing on device without play store services? For example on an emulator? In order to use com.google.android.gms:play-services-mlkit-text-recognition:18.0.2 it has to be on a device with play store services.

My GPS App Crashed After Setting Last Location

I'm currently doing a GPS App from FreeCodeCamp.Org Youtube Channel, "How to make A GPS Tracking App" https://www.youtube.com/watch?v=_xUcYfbtfsI&t=1774s . I did everything in the video, and the instructions, but every time I pressed the see way point list, it keep crashing. I need help to fix this. I dont know what's wrong with the code.
package com.example.gipies;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int DEFAULT_UPDATE_INTERVAL = 30;
public static final int FAST_UPDATE_INTERVAL = 5;
public static final int PERMISSION_FINE_LOCATION = 99;
//Refrensi Element UI
TextView tv_lat, tv_lon, tv_altitude, tv_accuracy, tv_speed, tv_sensor, tv_updates, tv_address,tv_wayPointCounts;
Button btn_newWP, btn_showWayPointList,btn_showMap;
#SuppressLint("UseSwitchCompatOrMaterialCode")
Switch sw_locationupdates, sw_gps;
//Variable to Remember to Track
boolean updateOn = false;
//Current Locaton
Location currentLocation;
//List of Saved
List<Location> savedLocations;
//Location Request configs of FusedLocationProviderClient
LocationRequest locationRequest;
LocationCallback locationCallBack;
//Google API for Location Services
private FusedLocationProviderClient fusedLocationProviderClient;
Object FusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Nilai Variable UI
tv_lat = findViewById(R.id.tv_lat);
tv_lon = findViewById(R.id.tv_lon);
tv_altitude = findViewById(R.id.tv_altitude);
tv_accuracy = findViewById(R.id.tv_accuracy);
tv_speed = findViewById(R.id.tv_speed);
tv_sensor = findViewById(R.id.tv_sensor);
tv_updates = findViewById(R.id.tv_updates);
tv_address = findViewById(R.id.tv_address);
sw_gps = findViewById(R.id.sw_gps);
sw_locationupdates = findViewById(R.id.sw_locationsupdates);
btn_newWP = findViewById(R.id.btn_newWP);
btn_showWayPointList= findViewById(R.id.btn_showWayPointList);
btn_showMap = findViewById(R.id.btn_showMap);
tv_wayPointCounts = findViewById(R.id.tv_CountOfPoints);
FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//Set all Properties of LR
locationRequest = new LocationRequest();
locationRequest.setInterval(1000 * DEFAULT_UPDATE_INTERVAL);
locationRequest.setFastestInterval(1000 * FAST_UPDATE_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationCallBack = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
//Save Location
Location location = locationResult.getLastLocation();
updateUIValues(location);
}
};
btn_newWP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//get GPS Location
// add New Location
MyApplication myApplication = (MyApplication)getApplicationContext();
savedLocations = myApplication.getMyLocations();
savedLocations.add(currentLocation);
}
});
btn_showWayPointList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, ShowSavedLocList.class);
startActivity(i);
}
});
btn_showMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,MapsActivity.class);
startActivity(i);
}
});
sw_gps.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if (sw_gps.isChecked()) {
//GPS Accurate
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
tv_sensor.setText("Using GPS Sensor");
} else {
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
tv_sensor.setText("Using WIFI");
}
}
});
sw_locationupdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (sw_locationupdates.isChecked()) {
//Turned On Location Tracking
startLocationUpdates();
} else {
//Turned Off Tracking
stopLocationUpdates();
}
}
});
updateGPS();
}//END onCreate
#SuppressLint("SetTextI18n")
private void stopLocationUpdates() {
tv_updates.setText("Location is NOT Being Tracked");
tv_lat.setText("Not tracking");
tv_lon.setText("Not Tracking");
tv_speed.setText("Not Tracking");
tv_address.setText("Not Tracking");
tv_accuracy.setText("Not Tracking");
tv_altitude.setText("Not Tracking");
tv_sensor.setText("Not Tracking");
LocationCallback.FusedLocationProviderClient.RemoveLocationUpdates(locationCallBack);
}
#SuppressLint("SetTextI18n")
private void startLocationUpdates() {
tv_updates.setText("Location is Being Tracked");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
FusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallBack, null);
updateGPS();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
updateGPS();
}
else{
Toast.makeText(this,"The APP Needs Permissions",Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void updateGPS(){
//Permissions, Current Location, Update UI
FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
FusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
updateUIValues(location);
Location currentLocation = location;
}
});
}
else {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
}
}
}
private void updateUIValues(Location location) {
//Update All Text with New Location
tv_lat.setText(String.valueOf(location.getLatitude()));
tv_lon.setText(String.valueOf(location.getLongitude()));
tv_accuracy.setText(String.valueOf(location.getAccuracy()));
if(location.hasAltitude()){
tv_altitude.setText(String.valueOf(location.getAltitude()));
}
else{
tv_altitude.setText("Not Available");
}
if (location.hasSpeed()){
tv_speed.setText(String.valueOf(location.getAltitude()));
}
else{
tv_speed.setText("Not Available");
}
Geocoder geocoder = new Geocoder(MainActivity.this);
try{
List<Address>addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
tv_address.setText(addresses.get(0).getAddressLine(0));
}
catch ( Exception e){
tv_address.setText("Unable to find");
}
MyApplication myApplication = (MyApplication)getApplicationContext();
savedLocations = myApplication.getMyLocations();
//Show Number of WPs
tv_wayPointCounts.setText(Integer.toString(savedLocations.size()));
}
}
in MainActivity.Java
it said
Cannot Resolve symbol 'FusedLocationProviderClient'
Cannot resolve method 'requestLocationUpdates' in 'Object'
Cannot resolve method 'getLastLocation' in 'Object'

Android: FusedLocationProvider, get location every few seconds

I'm making an app that tracks the user's location and ultimatly uploads it to a Firebase server.
I have created a simple app that displays the location when I press a button on screen. The problem is that it doesnt change the location when I press it again after I walked a few meters (I do get a new location when I re-enter the app though). What do I need to add in order for the app to update the location every X seconds? This is my activity:
package com.example.gpstest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
client = LocationServices.getFusedLocationProviderClient(this);
Button button = findViewById(R.id.getLocation);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
return;
}
client.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
TextView lat = findViewById(R.id.location1);
TextView lon = findViewById(R.id.location2);
TextView alt = findViewById(R.id.location3);
lat.setText(Double.toString(location.getLatitude()));
lon.setText(Double.toString(location.getLongitude()));
alt.setText(Double.toString(location.getAltitude()));
}
}
});
}
});
}
private void requestPermission(){
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
Because you get the location from getLastLocation. For that you have to implement LocationCallback.
consider this link for more information
// implement these interface in your class
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener.
//than use this code
public void onConnected(Bundle bundle) {
Location mLastLocation = null;
if (mGoogleApiClient.isConnected()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more precise.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
buildGoogleApiClient();
mGoogleApiClient.connect();
}
}

How to send location using sms? (fused location api)

I'm currently making an app for school.. my app functions specifically for sending users most accurate location via SMS. so I used fused location api ... but now I don't know how to incorporate the SMS manager on my current app ... at present I only built a simple app which shows the users current location by pressing a button
I just want help on how to incorporate SMS manager in my app.
I also want the message to be in a URL form plus the coordinates so that it will be easy for the receiver to track the user.
here is my code Main activity
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 2300;
TextView textView;
Button sosbtn;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE: {
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
sosbtn = (Button) findViewById(R.id.sosbtn);
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
} else {
buildLocationRequest();
buildLocationCallBack();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
sosbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
});
}
}
private void buildLocationCallBack() {
locationCallback= new LocationCallback()
{
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
for(Location location:locationResult.getLocations())
textView.setText(String.valueOf(location.getLatitude())+"/"+String.valueOf(location.getLongitude()));
}
};
}
private void buildLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(3000);
locationRequest.setSmallestDisplacement(5);
}
}
your help will be greatly appreciated.
Here's an example, declare the location object as a private field and on the click of your button:
SmsManager smsManager = SmsManager.getDefault ();
String message = "My location: https://www.google.com/maps/#?api=1&map_action=map&center=" + location.getLatitude () + "," + location.getLongitude ();
String phoneNumber = "+1....";
smsManager.sendTextMessage (phoneNumber, null, message, null, null);
The above link should redirect your recipient to google maps.
SmsManager.sendTextMessage
Don't forget to add this permission in your manifest:
<uses-permission android:name="android.permission.SEND_SMS"/>
and request the send sms permission in runtime.

App Crash in Moblile phone

I am trying to make a camera App for an android phone. The code is showing no error, but when I run it on my phone after launching the app, it crashes, giving this error:
"Unfortunately the app stopped"
package com.my.hp.myapp;
import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_CODE_SOME_FEATURES_PERMISSIONS = 1;
private static final int CAMERA_PIC_REQUEST = 2;
private ImageView img;
private Button btn1;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
img = findViewById(R.id.image);
btn1 = findViewById(R.id.butt);
btn1.setOnClickListener(this);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkpermission() {
int hasCameraPermission =
checkSelfPermission(Manifest.permission.CAMERA);
int hasStoragePermission =
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> permissions = new ArrayList<>();
if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.CAMERA);
}
if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!permissions.isEmpty()) {
requestPermissions(permissions.toArray(new String[permissions.size()]),
REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
}
}
#RequiresApi(api=Build.VERSION_CODES.M)
private boolean hasPermission() {
int hasCameraPermission =
checkSelfPermission(Manifest.permission.CAMERA);
int hasStoragePermission =
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
return (hasCameraPermission==PackageManager.PERMISSION_GRANTED && hasStoragePermission==PackageManager.PERMISSION_GRANTED);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.butt:
if(hasPermission())
{
openCamera();
}
else{
checkpermission();
}
break;
}
}
private void openCamera()
{
String timeStamp=new
SimpleDateFormat("yyyyMMdd_HHmms").format(new Date());
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"IMG_"+ timeStamp+".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri =
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode) {
case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED)
{
Log.d("Permissions", "Permission Denied: " + permissions[i]);
}
}
}
break;
default:{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
if(data != null){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
img.setImageBitmap(imageBitmap);
}
}
}
}
}
First check if you added camera and read storage permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Categories