I am making a geocoder-reverse geocoder.
The coordinates are generated in a textview which I want to further use in reverse geocoding.
The problem is that the app suddenly stops working when I try to save the contents of textview into the variable. LATITUDE = Double.parseDouble(t.getText().toString());
LATITUDE being the variable, t is the textView in which the coordinates are generated.
Is there any other way to save a double value from textView into a variable so that it can be used further.
If not, can this problem be solved.
Thanks in Advance :)
Here is my java code:
public class MainActivity extends Activity {
private Button b;
public TextView t;
public TextView u;
public TextView add;
private LocationManager locationManager;
private LocationListener listener;
public Button b2;
private EditText e;
double LATITUDE;
double LONGITUDE;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.textView);
u = (TextView) findViewById(R.id.textView3);
add = (TextView) findViewById(R.id.textView4);
b = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
e = (EditText) findViewById(R.id.editText);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = e.getText().toString();
String loc = t.getText().toString();
String loc1 = u.getText().toString();
String loc2 = add.getText().toString();
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"+number));
sendIntent.putExtra("sms_body",loc+loc1+loc2);
try {
startActivity(sendIntent);
finish();
Log.i("Finished sending SMS...", "");
}
catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"SMS failed, please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
t.append("\n " + location.getLatitude());
u.append("\n " + location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button(){
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
return;
}
// this code won't execute IF permissions are not allowed, because in the line above there is return statement.
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps",15000,0, listener);
}
});
}
public void phone(View view) {
Intent i = new Intent(this,Main2Activity.class);
startActivity(i);
}
public void address(View view) {
LATITUDE = Double.parseDouble(t.getText().toString());
LONGITUDE = Double.parseDouble(u.getText().toString());
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String result;
try {
List<Address> addressList = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i));
}
sb.append("\n" + address.getLocality());
sb.append("\n" + address.getPostalCode());
sb.append("\n" + address.getCountryName());
result = sb.toString();
add.append(result);
}
}
catch (IOException e) {
}
}
}
You are appending new coordinated to the textView by the following line.
t.append("\n " + location.getLatitude())
So now when you read the textView t you get all the values separated by \n. Try to split this first so you will get an array of string. Then run a loop converting all the strings to double.
Here is an example of how you can split strings
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
Why dont you put in a class level string array during appending in the textview. So clean and safe code.No risk of null pointer during spliting.
Related
It's a location tracking application.
I test it in home, so location doesn't change. To do that I change them manually by incrementing the latitude and longitude by 2 everytime. I see the location change in my phone everytime, but the speed is still always 0! I don't know if it's working because I haven't tried this method before. If someone did I would appreciate the help.
public class MainActivity extends AppCompatActivity {
private Button b;
private TextView t;
private LocationManager locationManager;
private LocationListener listener;
private static int a=2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.textView);
b = (Button) findViewById(R.id.button);
t.setText(""); t.setTextSize(16);
b.setText("Demarer");
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//to change location manually
location.setLatitude(location.getLatitude()+a);
location.setLongitude(location.getLongitude()+a);
a=a+10;
System.out.println("\n\nlocation changed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");
//
Long id = new Long(1);
String rs = null;
String json = null;
//post
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
PostLocation pl = new PostLocation();
json = pl.bowlingJson(location.getLongitude(), location.getLatitude(),id);
//System.out.println(json);
rs = pl.post("http://192.168.1.50:8080/api/v1/locations", json);
}catch (IOException EX){ EX.printStackTrace();
}finally {
if (rs == null)
t.setText("\nID : " +id+"\nLongitude : "+ location.getLongitude() + "\nLatitude : " + location.getLatitude() +"\nVitesse : "+(location.getSpeed()*3600/1000)+"km/h\n\nnon envoyée" );
//t.setText(location.getLatitude()+" : "+location.getLongitude()+"\n"+oldLocation.getLatitude()+" : "+oldLocation.getLongitude());
else
{
t.setText("\nID : " +id+"\nLongitude : "+ location.getLongitude() + "\nLatitude : " + location.getLatitude() +"\nVitesse : "+(location.getSpeed()*3600/1000)+"km/h\n\nbien envoyée" );
}
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) { }
#Override
public void onProviderEnabled(String s) { }
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button(){
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
return;
}
// va pas executer si n y a pas de privilege un return existe avant
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
//noinspection MissingPermission
try{
locationManager.requestLocationUpdates(locationProvider, 1000, 0, listener);
}catch (SecurityException e){
}
}
});
}
}
I try to get current location when the app running in background, so I use service. However, the data does not change in background, the service does not work. I want to know the problem. Here is the code of the app.
MainActivity as follow:
public class MainActivity extends Activity {
Button btn_start;
private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude,longitude;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
tv_address = (TextView) findViewById(R.id.tv_address);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_area = (TextView)findViewById(R.id.tv_area);
tv_locality = (TextView)findViewById(R.id.tv_locality);
geocoder = new Geocoder(this, Locale.getDefault());
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
medit = mPref.edit();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_permission) {
if (mPref.getString("service", "").matches("")) {
medit.putString("service", "service").commit();
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
});
fn_permission();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = Double.valueOf(intent.getStringExtra("latitude"));
longitude = Double.valueOf(intent.getStringExtra("longitude"));
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
tv_area.setText(addresses.get(0).getAdminArea());
tv_locality.setText(stateName);
tv_address.setText(countryName);
} catch (IOException e1) {
e1.printStackTrace();
}
tv_latitude.setText(latitude+"");
tv_longitude.setText(longitude+"");
tv_address.getText();
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Service as follow:
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver =
"com.findmyelderly.findmyelderly.receiver";
Intent intent;
public GoogleService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
// fn_getlocation();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable) {
} else {
if (isNetworkEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
if (isGPSEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
build.gradle as follow
.........
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.android.support:multidex:1.0.0'
AndroidManifest as follow
..........
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
.........
<service android:name=".GoogleService" android:exported="false" android:enabled="true"/>
</application>
</manifest>
I am very puzzled.
One thing you could try is to check the permissions of the app on the phone itself. I've found with my device (Android version 6.0.1) it's not enough to just add "uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> and
"uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />"
in the manifest, you have to grant permissions to the app manually on the device.
To do this, go to Settings > Apps > 'yourApp' > Permissions and slide across the bar to turn on Location for that app.
I'm new enough to Android apps myself so there may be a bigger problem in your case I'm not sure but worth a try anyway!
Note:- Sorry for my bad English because English is not my native language i have used google translator for this.
I am working on an android Map app in which a user can find their friends' current location and for storing the current location I am using FireBase realtime database. So when a user clicks on the find button, their friends' current location will be on the Map with their user name.
But I am unable to solve one problem when I am trying to fetch the user data from firebase. It is not reflecting in the correct way. The data is reflecting in 2 different lines in the log:
line 1:- Latitude & Longitude is 0.0 but email is showing and in
line 2:- Latitude & Longitude is reflecting correctly but Email is null
I don't know how to get both in one line. I have searched a lot on google but failed. Kindly help me understand how it can be done in the correct way.
Below is my code and android studio screen shot.
MainActivity.java
findfriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, MapsActivity.class));
}
});
final TextView tname;
tname = (TextView) findViewById(R.id.textview);
ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://ffinder-b4617.firebaseio.com/Email");
mReferece2 = ref.child("email");
mReferece2 = ref.child("location");
proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
UserInformation details = dataSnapshot1.getValue(UserInformation.class);
String email = details.email;
Double lat = details.latitude;
Double lon = details.longitude;
tname.setText(lat+" "+'\n'+lon+'\n'+email);
System.out.println("-->"+ lat+" " + lon+" "+ email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
MapsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Firebase.setAndroidContext(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
} else {
Log.d("onCreate", "Google Play Services available.");
}
auth = FirebaseAuth.getInstance();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FirebaseDatabase.getInstance().getReference().child("Location");
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date();
mLastUpdateTime = ((dateFormat.format(date).toString()));
saveToFirebase();
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
}
public void saveToFirebase() {
Firebase firebase = new Firebase("https://ffinder-b4617.firebaseio.com").child("Email").child("location");
Map mLoactions = new HashMap();
mLoactions.put("timestamp",mLastUpdateTime);
mLoactions.put("latitude", mLastLocation.getLatitude());
mLoactions.put("longitude", mLastLocation.getLongitude());
firebase.setValue(mLoactions);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public boolean onMarkerClick(Marker marker) {
marker.setDraggable(true);
return false;
}
#Override
public void onMarkerDragStart(Marker marker) {}
#Override
public void onMarkerDrag(Marker marker) {}
#Override
public void onMarkerDragEnd(Marker marker) {
end_latitude = marker.getPosition().latitude;
end_longitude = marker.getPosition().longitude;
Log.d("end_lat",""+end_latitude);
Log.d("end_lng",""+end_longitude);
}
}
Login.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Firebase.setAndroidContext(this);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
public void userLoginInfo(){
String email = inputEmail.getText().toString();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Email").push();
String userId = mDatabase.child("email").getKey();
mDatabase.child(userId).setValue(email);
}
}
UserInformation.class
public class UserInformation {
public String email;
public double latitude;
public double longitude;
public UserInformation() {
}
public UserInformation(String email, double latitude, double longitude) {
this.email = email;
this.latitude = latitude;
this.longitude = longitude;
}
public String getEmail() {
return email;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
Firebase Database screenshot
Android Studio log screenshot
Your userLoginInfo() method uses push() to create a unique key within the database to store the email address, and your saveToFirebase() method stores the latitude/longitude values differently, which means the data ends up in different places.
It would be beneficial to make use of your UserInformation object to standardise your database and use DatabaseReference#setValue(Object)
and DataSnapshot#getValue(Class<CT>) to store and retrieve the data. So when you want to store a user's location you do:
public void saveToFirebase() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Email").push();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
UserInformation userInformation = new UserInformation(email, mLastLocation.getLatitude(), mLastLocation.getLongitude());
ref.setValue(userInformation);
}
Then, to retrieve these details later, you can use your existing ValueEventListener with a couple of adjustments:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Email");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()){
UserInformation details = child.getValue(UserInformation.class);
System.out.println("-->" + details.getLatitude() +" " + details.getLongitude() +" "+ details.getEmail());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
I hope I've understood your requirements correctly, please let me know if I've missed anything.
I am able to send the location (String address) + messages to my server; however, my app crashed after sending data to server. I used Volley library to make a POST request. Can someone help me fix this issue?
First I get the location and the list of the address.
public class MainActivity extends AppCompatActivity {
//Declare LocationManager and LocationListener
LocationManager locationManager;
LocationListener locationListener;
String address = "Unable to get the address!";
EditText Message;
AlertDialog.Builder builder;
String server_url ="https://schoolserver-tand089.c9users.io/Report.php";
//Process when users give the permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Start the location service
startListening();
}
}
//Checking permission granted method
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
//Update location method. 1 variable location
public void updatedLocationInfo(Location location) {
Log.i ("Location", location.toString());
//Cast the textViews
TextView latTextView = (TextView) findViewById(R.id.txtLat);
TextView lonTextView = (TextView) findViewById(R.id.txtLong);
TextView altTextView = (TextView) findViewById(R.id.txtAltitude);
TextView accTextView = (TextView) findViewById(R.id.txtAccuracy);
//get the string from location
latTextView.setText("Latitude: " + location.getLatitude());
lonTextView.setText("Longitude: " + location.getLongitude());
altTextView.setText("Altitude: " + location.getAltitude());
accTextView.setText("Accuracy: " + location.getAccuracy());
//Create Geocoder object to Get the address
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
//Using try/catch to prevent the app from crashing when failing to get Addresses
try {
//Declare the error string
//String address = "Unable to get the address!";
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
//Check if the address is valid
if (listAddresses != null && listAddresses.size() > 0) {
//Set address to empty string again when we know it is working
address = "Address: \n";
// Log.i("Address", listAddresses.get(0).toString());
//check for every item in the list Addresses is valid
if (listAddresses.get(0).getSubThoroughfare() != null) {
address += listAddresses.get(0).getSubThoroughfare() + " ";
}
//Street name
if (listAddresses.get(0).getThoroughfare() != null) {
address += listAddresses.get(0).getThoroughfare() + "\n";
}
//City name
if (listAddresses.get(0).getLocality() != null) {
address += listAddresses.get(0).getLocality() + "\n";
}
//Zip code
if (listAddresses.get(0).getPostalCode() != null) {
address += listAddresses.get(0).getPostalCode() + "\n";
}
//Country name
if (listAddresses.get(0).getCountryName() != null) {
address += listAddresses.get(0).getCountryName() + "\n";
}
TextView addressTextView = (TextView) findViewById(R.id.txtAddress);
//set the address into the text View
addressTextView.setText(address);
//Log.i("Address", address.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up locationManager and locationListener above and cast them into their type
//Using built-in location service
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
//Get the location when it changes
#Override
public void onLocationChanged(Location location) {
//call the updated location above
updatedLocationInfo(location);
}
//
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Check for the version of SDK
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
// above 23 we need to check for permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//ask for permission. Number 1 is just a request queue.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
//we have permission
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//Get the last location from the built-in GPS
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//In case location does not have lastknownlocation, we call the updatedLocation method above
if (location != null) {
updatedLocationInfo(location);
}
}
}
}
Next, I used the onClick method to send the Address and a message to server when user clicks the button.
// using onClick
public void bntTap (View bnt) {
Message = (EditText) findViewById(R.id.message);
//Hide virtual keyboard after click the button
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
final String message;
message = Message.getText().toString();
if (message.equals("")) {
builder.setTitle("Unable to report");
//Creating a AlertDialog to display errors
AlertDialog alertDialog = builder.create();
alertDialog.setMessage("Please Enter All Required Fields*");
alertDialog.show();
} else {
//Post request
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//get response form server to check if it is successfully submitted
builder.setTitle("Server Response");
builder.setMessage("Congratulation" + " " + response);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Message.setText("");
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error!!!", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//send data to mySQL server
//the keys must be same as field names in mySQL server
// get the list of the address
params.put("LOCATION", address);
params.put("MESSAGES", message);
return params;
}
};
MySingleton.getInstance(MainActivity.this).addTorequestqueue(stringRequest);
//Log.i("Address", address.toString());
}
}
All the data successfully sent to the server, but the app crashed.
Updated: logcat when crashing
logcat when crashing
You are getting an NPE, as you forgot to define builder. You have only declared it in your code as
AlertDialog.Builder builder;
Please define the builder as
builder = new AlertDialog.Builder(MainActivity.this);
in your onCreate().
I'm new to android and I cannot figure out why my onCreate() in my activity is being called over and over.
In my MainActivity I have this function search, that is called when a button is pressed.
private void search(View v){
//Get input fields if null then dont restrict search
...
...
Intent i = new Intent(getApplicationContext(), PersonActivity.class);
i.putExtra("miles",numMiles);
i.putExtra("min",numMin);
startActivity(i);
}
Then in my PersonActivity Class I have this onCreate Method.
public class PersonActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
public ArrayList<PersonInfo> people;
private LayoutInflater inflater;
private Context _context;
public PersonInfoListAdapter _adapter;
public static ListView _list;
public int _position;
private static final String APP_ID = "4cae6e4d7d89bc4b02196b352ae91650";
// Find this in your developer console
private static final String API_KEY = "4A3243EECEA842F7B1FC6E7A4B00DA7A";
public PersonActivity() {}
#Override
protected void onCreate(Bundle savedInstanceState) {;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person);
View listV = findViewById(R.id.friendList);
_list = (ListView) listV;
CMApiCredentials.initialize(APP_ID, API_KEY, getApplicationContext());
try {
people = new ArrayList<PersonInfo>();
Context context = _list.getContext();
_adapter = new PersonInfoListAdapter(context, people);
_list.setAdapter(_adapter);
} catch (Exception e) {
e.printStackTrace();
}
_list.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
View parentRow = (View) view.getParent();
return true;
}
});
Integer numMin = -1;
Integer numMiles = -1;
Bundle extras = getIntent().getExtras();
if (extras != null) {
numMin = extras.getInt("min");
numMiles = extras.getInt("miles");
Log.d("Person Activity", "Miles" + numMiles.toString());
}
queryForPeople(numMiles, numMin);
}
private void queryForPeople(Integer numMiles, Integer numMin){
//Get users location
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
Location lastKnownLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = lastKnownLoc.getLatitude();
double lon = lastKnownLoc.getLongitude();
Intent myIntent = new Intent(this, PersonActivity.class);
startActivity(myIntent);
//search for friends
PersonInfo.searchObjects(this, SearchQuery.filter("location").near(lon, lat).within(numMiles, DistanceUnits.mi).searchQuery(),
new Response.Listener<CMObjectResponse>() {
#Override
public void onResponse(CMObjectResponse response) {
List<CMObject> objectList = response.getObjects();
for (CMObject o : objectList) {
PersonInfo p = (PersonInfo) o;
people.add(p);
Log.d(TAG, "Person was found: " + p.getName());
}
}
});
_adapter.notifyDataSetChanged();
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
The problem is this onCreate() in my personActivity is being called over an over. And I cannot figure out why. queryForPeople makes a call to and API that returns information that I use to populate the people ArrayList that is used in the adapter.
Any Ideas?
Your queryForPeople method calls startActivity on the activity you're already running from. So this will end up being infinitely recursive. I don't see why you would want to start yourself from anywhere in your activity, it just doesn't make sense. Unless you intended something else with those two lines, simply remove them.