Ok I'm not having trouble obtaining the coordinate with Network, however my professor asked us putting the location obtaining part of code into its own class (say NetworkLocation.java). Now things get interesting.
My code is:
//MainActivity.java
package com.example.maest.weather;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView t;
private LocationManager mLocationManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_scrolling);
t = (TextView) findViewById(R.id.textView);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
NetworkLocation mNetworkLocation = new NetworkLocation();
double mCoordinate[] = mNetworkLocation.getNetworkLocation(mLocationManager);
t.append("\n Longtitude: " + mCoordinate[0] + "\n Latitude: " + mCoordinate[1] + "\n");
}
}
and NetworkLocation.java
//NetworkLocation.java
package com.example.maest.weather;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class NetworkLocation {
private LocationListener mLocationListener;
private double mCoordinate[] = {0, 0};
public double[] getNetworkLocation (LocationManager mLocationManager) {
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location mLocation) {
mCoordinate[0] = mLocation.getLongitude();
mCoordinate[1] = mLocation.getLatitude();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
try{
mLocationManager.requestLocationUpdates(mLocationManager.NETWORK_PROVIDER, 5000, 0, mLocationListener);
mLocation[0] = 5; //see if it works.
}catch(SecurityException e){
// Need update here.
};
return mCoordinate;
}
}
And the result, the longitude shown in the interface is always 5, latitude is always 0. Meaning, the code: mLocationManager.requestLocationUpdates(mLocationManager.NETWORK_PROVIDER, 5000, 0, mLocationListener); is covered, however, onLocationChanged() is never called.
Well... there is no grammar error here, nor running time error. What should I do then?