package com.example.pinkconnect;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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;
public class HomeActivity extends AppCompatActivity {
private SensorManager sm;
private float acelVal, acelLast, shake;
private static int counter = 0;
int PERMISSION_ID = 44;
FusedLocationProviderClient mFusedLocationClient;
String latitude, longitude;
DatabaseReference pne;
Button btnLogout;
DatabaseReference pinn;
String pin;
String pin1;
String phoneu;
int i=0;
EditText t5;
final Handler handler=new Handler();
ArrayList<String> phoneNo = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
t5=findViewById(R.id.t5);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(sensorListener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
acelVal = SensorManager.GRAVITY_EARTH;
acelLast = SensorManager.GRAVITY_EARTH;
shake = 0.00f;
btnLogout = findViewById(R.id.logout);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intToMain = new Intent(HomeActivity.this, MainActivity.class);
startActivity(intToMain);
}
});
Bundle bundle = getIntent().getExtras();
//Extract the data…
String ids = bundle.getString("ids");
pinn= FirebaseDatabase.getInstance().getReference(String.valueOf(ids)).child("pin");
pinn.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
pin= (String) dataSnapshot.getValue();
// String t=temp+"°C";
// tv2.setText(t);
Toast.makeText(HomeActivity.this,"pin is "+pin,Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
do {
pne = FirebaseDatabase.getInstance().getReference(String.valueOf(ids)).child("phone").child(String.valueOf(i));
pne.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
phoneu = (String) dataSnapshot.getValue();
// String t=temp+"%";
// tv4.setText(t);
// Toast.makeText(HomeActivity.this, "phone numbers are " + phoneu, Toast.LENGTH_LONG).show();
//for(int i=0;i<5;i++){
phoneNo.add(phoneu);
// }
//Toast.makeText(HomeActivity.this, "nos" + phoneu.length(), Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
i++;}while(i<5);
// Toast.makeText(HomeActivity.this, "phone numbers are " + phoneNo, Toast.LENGTH_LONG).show();
// Toast.makeText(HomeActivity.this, "nos" + phoneu.length(), Toast.LENGTH_LONG).show();
}
private final SensorEventListener sensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
acelLast = acelVal;
acelVal = (float) Math.sqrt((double) (x * x) + (y * y) + (z * z));
float delta = acelVal - acelLast;
shake = shake * 0.9f + delta;
if (shake > 12) {
counter++;
}
if (counter >= 3) {
counter = 0;
final SmsManager smsManager = SmsManager.getDefault();
//String phoneNumbers[] = {"8220029986", "8431639251","7892096912"};
// String phoneNumbers=phoneu[];
//phoneNumbers[]=//get from DB;
//get Geolocation and set the custom text
/* do{//send sms
//enable the user to enter the pin
//get the pin from the EditText;
}while(pin.equals(Firebase pin));
*/
// for (String phone : phoneNumbers) {
do{
/* for(int m=0;m<5;m++){
//smsManager.sendTextMessage(phone, null, "sms message from pink connect" + latitude + longitude, null, null);
//https://www.latlong.net/c/?lat=0.000000&long=0.000000
//smsManager.sendTextMessage(phone, null, "Hey It's an emergency at this location"+"https://www.latlong.net/c/?lat="+latitude.toString()+"&long="+longitude.toString(), null, null);
//http://maps.google.com/maps?q=24.197611,120.780512
smsManager.sendTextMessage(phoneNo.get(m), null, "Hey It's an emergency at this location"+"http://maps.google.com/maps?q="+latitude.toString()+","+longitude.toString(), null, null);
}
*/
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 2 mins
for(int m=0;m<5;m++){
smsManager.sendTextMessage(phoneNo.get(m), null, "Hey It's an emergency at this location"+"http://maps.google.com/maps?q="+latitude.toString()+","+longitude.toString(), null, null);
}
}
}, 120000);
}while ((pin1.equals(pin.toString())));
Toast t3 = Toast.makeText(getApplicationContext(), "Your Location has been sent to Your loved ones!!! Don't panic, Help will arrive soon", Toast.LENGTH_LONG);
t3.show();
// t1.setText(latitude);
// t.setText(longitude);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@SuppressLint("MissingPermission")
private void getLastLocation(){
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.getLastLocation().addOnCompleteListener(
new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
latitude= location.getLatitude()+"";
longitude = location.getLongitude()+"";
}
}
}
);
} else {
Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
}
@SuppressLint("MissingPermission")
private void requestNewLocationData(){
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(0);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.requestLocationUpdates(
mLocationRequest, mLocationCallback,
Looper.myLooper()
);
}
private LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
latitude = mLastLocation.getLatitude()+"";
longitude = mLastLocation.getLongitude()+"";
}
};
private boolean checkPermissions() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_ID
);
}
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_ID) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
}
@Override
public void onResume(){
super.onResume();
if (checkPermissions()) {
getLastLocation();
}
}
//get pin
public void stop(View view){
pin1=t5.getText().toString();
}
}
/*final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);*/
в вышеприведенной кодировке я получаю ошибку как java .lang.NullPointerException: попытка вызвать виртуальный метод 'логический java .lang.String.equals (java .lang. Object) 'для пустой ссылки на объект com.example.pinkconnect.HomeActivity $ 4.onSensorChanged (HomeActivity. java: 174), my for l oop должен продолжать отправлять сообщения каждые 2 минуты при встряхивании устройства в течение 3 время, пока не будет выполнено условие while, в то время как l oop встречается, (Если я правильно введу пин-код в тексте редактирования "t5. Пожалуйста, помогите мне с этой ошибкой ...)