2016-10-05 4 views
0

Ich möchte Breitengrad und Längengrad des aktuellen Standorts anzeigen und den Namen des Standorts von diesem Längen- und Breitengrad dieses Ortes in drei Textansichten anzeigen. Der Längen- und Breitengrad wird jedoch nicht in tv_lat und tv_long angezeigt.Breiten- und Längengrad wird nicht angezeigt

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

Im Fall, wenn Sie Ihre Anwendung in Eibisch testen:

public class MainActivity extends AppCompatActivity implements NetworkCallback, LocationListener { 

private EditText empIdTxt; 
private EditText passwordTxt; 
private TextView tv_lat; 
private TextView tv_long; 
private TextView tv_place; 
private Button loginBtn; 
protected Location mLastLocation; 
LocationManager locationmanager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    empIdTxt = (EditText) findViewById(R.id.et_loginId); 
    passwordTxt = (EditText) findViewById(R.id.et_loginPass); 
    tv_lat = (TextView) findViewById(R.id.tv_lat); 
    tv_long = (TextView) findViewById(R.id.tv_long); 
    tv_place = (TextView) findViewById(R.id.tv_place); 
    loginBtn = (Button) findViewById(R.id.bt_login); 

    empIdTxt.addTextChangedListener(new MyTextWatcher(empIdTxt)); 
    passwordTxt.addTextChangedListener(new MyTextWatcher(passwordTxt)); 

    empIdTxt.setText("vinay"); 
    passwordTxt.setText("qwerty"); 

    locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    Criteria cri = new Criteria(); 
    String provider = locationmanager.getBestProvider(cri, false); 
    if (provider != null & !provider.equals("")) { 
     Location location = locationmanager.getLastKnownLocation(provider); 
     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; 
     } 
     locationmanager.requestLocationUpdates(provider, 2000, 1, this); 
     if(location!=null) { 
      onLocationChanged(location); 
     }else{ 
      Toast.makeText(getApplicationContext(),"location not found",Toast.LENGTH_LONG).show(); 
     } 
    }else{ 
     Toast.makeText(getApplicationContext(),"Provider is null",Toast.LENGTH_LONG).show(); 
    } 
} 

public void clickLogin(View v) { 
    if (!validateEmpID()) { 
     return; 
    } 
    if (!validatePassword()) { 
     return; 
    } 

    LoginApi api = new LoginApi(this, this); 
    api.processLogin(empIdTxt.getText().toString(), passwordTxt.getText().toString(), 
      mLastLocation.getLatitude()+"",mLastLocation.getLongitude()+"", 
      AlertDialogManager.todayDate(), new GPSTracker(MainActivity.this).getLocation()+""); 
} 

private void requestFocus(View view) { 
    if (view.requestFocus()) { 
     getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); 
    } 
} 
private boolean validateEmpID() { 
    if (empIdTxt.getText().toString().trim().isEmpty()) { 
     empIdTxt.setError(ErrorUtil.USERNAME_ERROR); 
     requestFocus(empIdTxt); 
     return false; 
    } 
    return true; 
} 

private boolean validatePassword() { 
    if (passwordTxt.getText().toString().trim().isEmpty()) { 
     passwordTxt.setError(ErrorUtil.PASSWORD_ERROR); 
     requestFocus(passwordTxt); 
     return false; 
    } 
    return true; 
} 

private class MyTextWatcher implements TextWatcher { 

    private View view; 

    private MyTextWatcher(View view) { 
     this.view = view; 
    } 

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { 
    } 

    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { 
    } 

    public void afterTextChanged(Editable editable) { 
     switch (view.getId()) { 
      case R.id.et_loginId: 
       validateEmpID(); 
       break; 
      case R.id.et_loginPass: 
       validatePassword(); 
       break; 
     } 
    } 
} 

@Override 
public void updateScreen(String data, String tag) { 

    if (tag.compareTo(ApiUtil.TAG_LOGIN) == 0) { 
     try { 
      System.out.println("Login Response"+data); 

      JSONObject mainObj = new JSONObject(data); 
      AppDelegate ctrl = AppDelegate.getInstance(); 

      if (!mainObj.isNull("username")) { 
       ctrl.username = mainObj.getString("username"); 
      } 
      if (!mainObj.isNull("password")) { 
       ctrl.password = mainObj.getString("password"); 
      } 

    /*   if (!mainObj.isNull("latitude")) { 
       ctrl.password = mainObj.getString("latitude"); 
      } 

      if (!mainObj.isNull("longitude")) { 
       ctrl.password = mainObj.getString("longitude"); 
      } 

      if (!mainObj.isNull("date_and_time")) { 
       ctrl.password = mainObj.getString("date_and_time"); 
      } 

      if (!mainObj.isNull("place")) { 
       ctrl.password = mainObj.getString("place"); 
      }*/ 

      if (!mainObj.isNull("error")) { 
       Toast.makeText(MainActivity.this,"Login Fails",Toast.LENGTH_SHORT).show(); 
      } else { 
       Toast.makeText(MainActivity.this,"Login Success",Toast.LENGTH_SHORT).show(); 
      } 


     } catch (Exception e) { 
      Toast.makeText(MainActivity.this,"Seems there is an issue please try again later",Toast.LENGTH_SHORT).show(); 

     } 
    } 

} 

@Override 

public void onLocationChanged(Location location) { 

    tv_lat.setText("Latitude"+location.getLatitude()); 
    tv_long.setText("Longitude"+ location.getLongitude()); 
} 

@Override 
public void onStatusChanged(String s, int i, Bundle bundle) { 
} 

@Override 
public void onProviderEnabled(String s) { 
} 

@Override 
public void onProviderDisabled(String s) { 
} 
} 

Antwort

0

Achten Sie darauf, diese Erlaubnis in manifest & GPS gegeben haben sollte eingeschaltet werden

Give Berechtigungen programmatisch.

Letzte Sache entfernen Sie diese Bedingung aus Ihrem Code und führen Sie es aus. Es wird auf jeden Fall funktionieren:

diese entfernen:

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; 
     } 

Wenn Sie es nicht funktioniert, ich meine eigene Klasse schreiben, die auf Lollipop überprüfen es perfekt funktioniert:

public class Google_Map_Current_Location extends FragmentActivity implements LocationListener { 
    GoogleMap googleMap; 
    Location location; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     //show error dialog if GoolglePlayServices not available 
     if (!isGooglePlayServicesAvailable()) { 
      finish(); 
     } 
     setContentView(R.layout.google_map_current_loction); 
     SupportMapFragment supportMapFragment = 
       (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap); 
     googleMap = supportMapFragment.getMap(); 
     try { 
      googleMap.setMyLocationEnabled(true); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
     if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
      showSettingsAlert(); 
     } 

     Criteria criteria = new Criteria(); 
     String bestProvider = locationManager.getBestProvider(criteria, true); 
     try { 
      location = locationManager.getLastKnownLocation(bestProvider); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     if (location != null) { 
      onLocationChanged(location); 
     } 
     try { 
      locationManager.requestLocationUpdates(bestProvider, 20000, 0, this); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     TextView locationTv = (TextView) findViewById(R.id.latlongLocation); 
     double latitude = location.getLatitude(); 
     double longitude = location.getLongitude(); 
     LatLng latLng = new LatLng(latitude, longitude); 
     googleMap.addMarker(new MarkerOptions().position(latLng)); 
     googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 
     locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude); 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 
    } 

    private boolean isGooglePlayServicesAvailable() { 
     int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
     if (ConnectionResult.SUCCESS == status) { 
      return true; 
     } else { 
      GooglePlayServicesUtil.getErrorDialog(status, this, 0).show(); 
      return false; 
     } 
    } 

    public void showSettingsAlert() { 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); 

     // Setting Dialog Title 
     alertDialog.setTitle("GPS is settings"); 

     // Setting Dialog Message 
     alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

     // On pressing Settings button 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       startActivity(intent); 
      } 
     }); 

     // on pressing cancel button 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 

     // Showing Alert Message 
     alertDialog.show(); 
    } 
+0

Falls Sie Ich weiß nicht, wie ich programmgesteuert Berechtigungen erteilen darf. Schreibe im Kommentar. Ich werde meine Antwort mit Berechtigungen aktualisieren. –

+0

Ich habe die Erlaubnis in Manifest-Datei hinzugefügt, GPS ist eingeschaltet und ich teste meine App in Lollipop.Ich habe die Bedingung entfernt.Aber nach dem Entfernen dieser bekomme ich den Fehler "Anruf erfordert eine Erlaubnis, die vom Benutzer abgelehnt werden kann, Code sollte explizit Überprüfen Sie, ob die Berechtigung verfügbar ist (mit Check-Berechtigung) oder behandeln Sie explizit ein potenzielles "SecurityException" " – anu208

+0

es gibt den gleichen Fehler ... bitte posten Sie Ihre Klasse ... – anu208

Verwandte Themen