纬度和经度值未显示在 TextView 中

Posted

技术标签:

【中文标题】纬度和经度值未显示在 TextView 中【英文标题】:Latitude and Longitude values not displayng in TextView 【发布时间】:2013-01-11 18:24:03 【问题描述】:

我正在编写一个应用程序,用户可以在其中填写活动表单并将其同步到网络服务。应用程序的一部分涉及地理定位,因此,纬度和经度值。我希望我的应用程序自动定位一个人的智能手机的地理位置(它成功地做到了这一点),然后自动填写活动表单上的 TextView。我尝试了一些方法,但无济于事。谁能告诉我我哪里出错了?

这是 DataEntry 类:-

package application.prototype.mfb;

import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import application.prototype.mfb.MyLocation.LocationResult;

/**
 * Records a new data form entry for a favourite building
 * @author DanielD
 *
 */
public class DataEntry extends Activity implements OnClickListener 

Button btnClear;  
Button btnSync;
EditText txtBuildingName;
EditText txtDescription;
TextView txtLongitude;
TextView txtLatitude;
Spinner project;

public static Location loc;
private static double longitude;
private static double latitude;
private static String name;
private static String description; 
private static String projectString;
private static String lngString = String.valueOf(longitude);
private static String latString = String.valueOf(latitude);

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

    LocationResult locationResult = new LocationResult()
        @Override
        public void gotLocation(Location location)
            loc = location;
            latitude = loc.getLatitude();
            longitude = loc.getLongitude();
            System.out.println("Latitude: " + latitude);
            System.out.println("Longitude: " + longitude);
        
    ;
        MyLocation myLocation = new MyLocation();
        myLocation.getLocation(DataEntry.this, locationResult);

    txtBuildingName=(EditText)this.findViewById(R.id.nameContent);
    txtDescription=(EditText)this.findViewById(R.id.descriptionContent);

    project=(Spinner)findViewById(R.id.type_project);
    ArrayAdapter<CharSequence> adapterTwo = ArrayAdapter.createFromResource(this, R.array.type_project_array, android.R.layout.simple_spinner_item);
    project.setAdapter(adapterTwo);

    txtLatitude=(TextView)this.findViewById(R.id.TextViewLat);
    txtLongitude=(TextView)this.findViewById(R.id.TextViewLong);

    /*These checks will ensure that if a variable still has user data in it, it will refill the fields with that data preventing users entering
     * the same information multiple times
     */
    if(name != null)
        txtBuildingName.setText(name);
    

    if(description != null)
        txtDescription.setText(description);
    

    if(projectString != null)
        project.getItemAtPosition(project.getSelectedItemPosition()).toString();
    

    if(latString != null)
        txtLatitude.setText(latString);
    

    if(lngString != null)
        txtLongitude.setText(lngString);
    

    btnClear=(Button)findViewById(R.id.btnClear);
    btnClear.setOnClickListener(this);

    btnSync=(Button)findViewById(R.id.btnSync);
    btnSync.setOnClickListener(new OnClickListener()
        public void onClick(View v)                                        //NEW VERSION OF COMMIT DATA - WILL PRESERVE DATA OVER ACTIVITY
            if(txtBuildingName.getText().toString().length() > 0)
                name = txtBuildingName.getText().toString();
            if(txtDescription.getText().toString().length() > 0)
                description = txtDescription.getText().toString();
            if(project.getItemAtPosition(project.getSelectedItemPosition()).toString().length() > 0)
                projectString = project.getItemAtPosition(project.getSelectedItemPosition()).toString();
            Intent intent = new Intent(DataEntry.this, DataSummary.class);
            startActivity(intent);
        
    );    


public static String getName()
    return name;


public static String getDescription()
    return description;


public static String getLongitude()
    return lngString;


public static String getLatitude()
    return latString;


/*public Location getLongitude()
     LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
     Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
     longitude = location.getLongitude();
     return longitude;
 

public Location getLatitude()
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    latitude = location.getLatitude();
    latitudeString = String.valueOf(latitude);
    return latitudeString;

*/

public static String getProject()
    return projectString;


public void onSaveInstanceState(Bundle outState)
    super.onSaveInstanceState(outState);


public void onRestoredInstanceState(Bundle returnState)

    super.onRestoreInstanceState(returnState);


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    getMenuInflater().inflate(R.menu.activity_favourite_building, menu);
    return true;


public void onClick(View v)
    switch(v.getId())
    
    case R.id.btnClear : clearFields();
    break;  
    


/**
 * Switch statement governing the different options available on the Action Bar
 */
public boolean onOptionsItemSelected(MenuItem item)
    switch(item.getItemId())
    case R.id.app_camera:
        Intent intentZero = new Intent(this, CameraDemo.class);
        intentZero.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intentZero);
        return true;

    case R.id.app_dataentry:  
        Intent intent = new Intent(this, DataEntry.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        return true;

    case R.id.app_syncorsave:
        Intent intentOne = new Intent(this, DataSummary.class);
        intentOne.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intentOne);
        return true;

    case R.id.app_discard:  
        Intent intentTwo = new Intent(this, DeleteProjects.class);
        intentTwo.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intentTwo);
        return true;

    case R.id.app_homescreen:
        Intent intentThree = new Intent(this, ProjectGrid.class);
        intentThree.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intentThree);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    


 public void clearFields()
        Toast.makeText(DataEntry.this, "All fields Reset", Toast.LENGTH_LONG).show();
        txtBuildingName.getEditableText().clear();
        txtDescription.getEditableText().clear();
        name = "";              //must also set the static variables to blank otherwise previous data still assigned in variable.
        description = "";
        projectString = ""; 
    

这里是 MyLocation.java 类:-

package application.prototype.mfb;

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation 
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;

public boolean getLocation(Context context, LocationResult result)

    //I use LocationResult callback class to pass location value from MyLocation to user code.
    locationResult=result;
    if(lm==null)
        lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    //exceptions will be thrown if provider is not permitted.
    try
    
        gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    
    catch(Exception ex)
    
        ex.printStackTrace();
    
    try
    
        network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
    catch(Exception ex)
    
        ex.printStackTrace();
    

    //don't start listeners if no provider is enabled
    if(!gps_enabled && !network_enabled)
        return false;

    if(gps_enabled)
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
    if(network_enabled)
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
    timer1=new Timer();
    timer1.schedule(new GetLastLocation(), 20000);
    return true;


LocationListener locationListenerGps = new LocationListener() 

    public void onLocationChanged(Location location) 
    
        timer1.cancel();
        locationResult.gotLocation(location);



      //  lm.removeUpdates(this);
        //lm.removeUpdates(locationListenerNetwork);
    
    public void onProviderDisabled(String provider) 
    public void onProviderEnabled(String provider) 
    public void onStatusChanged(String provider, int status, Bundle extras) 
;

LocationListener locationListenerNetwork = new LocationListener()

    public void onLocationChanged(Location location) 
    
        timer1.cancel();
        locationResult.gotLocation(location);
       // lm.removeUpdates(this);
     //   lm.removeUpdates(locationListenerGps);
    
    public void onProviderDisabled(String provider) 
    public void onProviderEnabled(String provider) 
    public void onStatusChanged(String provider, int status, Bundle extras) 
;

class GetLastLocation extends TimerTask 

    @Override
    public void run() 
         //lm.removeUpdates(locationListenerGps);
         //lm.removeUpdates(locationListenerNetwork);

         Location net_loc=null, gps_loc=null;
         if(gps_enabled)
             gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
         if(network_enabled)
             net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

         //if there are both values use the latest one
         if(gps_loc!=null && net_loc!=null)
             if(gps_loc.getTime()>net_loc.getTime())
                 locationResult.gotLocation(gps_loc);
             else
                 locationResult.gotLocation(net_loc);
             return;
         

         if(gps_loc!=null)
             locationResult.gotLocation(gps_loc);
             return;
         
         if(net_loc!=null)
             locationResult.gotLocation(net_loc);
             return;
         
         locationResult.gotLocation(null);
    


public static abstract class LocationResult

    public abstract void gotLocation(Location location);


现在,我添加了 System.out.println 方法,以在 logcat 日志中识别是否找到了位置值并且它们已经找到(见下文)。那么如何获取这些值并将它们转换为合适的格式以显示在 TextView 中?

01-11 18:04:01.885: I/System.out(541): Latitude: -4.066498333333333

01-11 18:04:01.885: I/System.out(541): Longitude: 52.410999999999994

*从生成的 logcat 文件中提取。

【问题讨论】:

您只需使用坐标设置文本字段 合适的格式是什么意思?? 【参考方案1】:

那么我如何获取这些值并将它们转换为合适的格式以显示在 TextView 中?

显示它们很容易,您已经完成了 98% 的工作,只需添加:

LocationResult locationResult = new LocationResult()
    @Override
    public void gotLocation(Location location)
        loc = location;
        latitude = loc.getLatitude();
        longitude = loc.getLongitude();

        txtLatitude.setText(latitude + "");
        txtLongitude.setText(longitude + "");

        System.out.println("Latitude: " + latitude);
        System.out.println("Longitude: " + longitude);
    
;

但是“合适的格式”有点模糊……你想要什么格式?您可以使用Location.convert() 来使用更传统的hour:minute:second.fraction 格式。

【讨论】:

抱歉,对合适的格式含糊其辞,我只是指一种符合 TextView 的格式,因此本质上是一个字符串。感谢您的帮助,这是一种享受。正确答案。【参考方案2】:
TextView tvLongitude=(TextView)findViewById(R.id.textViewlongitude);         
TextView tvLatitude=(TextView)findViewById(R.id.textViewlatitude); 
tvLongitude.setText("Longitude is"+longitude );
tvLatitude.setText("Latitude is"+latitude );

这样你就可以在textview上设置值了

【讨论】:

【参考方案3】:

嗯,快速查看您的代码,您正在 System.out 中打印您在 Result 回调中收到的双精度值,但您永远不会填充您试图放在 TextViews 上的两个字符串变量。

你应该在 Location 回调中重新填充你的变量

  LocationResult locationResult = new LocationResult()
        @Override
        public void gotLocation(Location location)
            loc = location;
            latitude = loc.getLatitude();
            longitude = loc.getLongitude();
            lngString = String.valueOf(longitude);
            latString = String.valueOf(latitude);
            System.out.println("Latitude: " + latitude);
            System.out.println("Longitude: " + longitude);
        
    ;

【讨论】:

【参考方案4】:

在 textview 上显示

你的布局activity_data_entry.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_
android:layout_
android:orientation="vertical" >

<TextView
    android:id="@+id/textViewlatitude"
    android:layout_
    android:layout_ />

<TextView
    android:id="@+id/textViewlongitude"
    android:layout_
    android:layout_/>
</LinearLayout>

内部代码:

LocationResult locationResult = new LocationResult()
    @Override
    public void gotLocation(Location location)
        loc = location;
        latitude = loc.getLatitude();
        longitude = loc.getLongitude();

        TextView tvLongitude=(TextView)findViewById(R.id.textViewlongitude);
        TextView tvLatitude=(TextView)findViewById(R.id.textViewlatitude);

        tvLongitude.setText("Longitude is"+longitude );
        tvLatitude.setText("Latitude is"+latitude );
    
;

但是你说的合适的格式是什么意思??

【讨论】:

以上是关于纬度和经度值未显示在 TextView 中的主要内容,如果未能解决你的问题,请参考以下文章

一旦 LocationManger 得到它就显示纬度和经度

ANDROID:在其他类中获取纬度和经度,但值变为0.0

变量传递不起作用 - 值未定义

如何在android中使用纬度和经度获取城市名称

用于在地图上显示地址的纬度和经度[重复]

使用纬度和经度显示谷歌地图