2014-04-04 29 views
0

我正在創建一個Android應用程序,它可以獲取XML數據。我希望能夠使用經度和緯度值發佈到網頁鏈接,以獲取用戶當前位置的特定XML數據。獲取經度和緯度值發佈到url - Android

這是到目前爲止我的代碼,它不工作:

public class GeoSplashActivity extends Activity { 
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    double longitude = location.getLongitude(); 
    double latitude = location.getLatitude(); 
    private String GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20"; 
    GeoRSSFeed feed3; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.splash2); 
     ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     if (conMgr.getActiveNetworkInfo() == null 
       && !conMgr.getActiveNetworkInfo().isConnected() 
       && !conMgr.getActiveNetworkInfo().isAvailable()) { 
      // No connectivity - Show alert 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setMessage(
        "Unable to reach server, \nPlease check your connectivity.") 
        .setTitle("TD RSS Reader") 
        .setCancelable(false) 
        .setPositiveButton("Exit", 
          new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface dialog, 
                int id) { 
            finish(); 
           } 
          }); 
      AlertDialog alert = builder.create(); 
      alert.show(); 
     } else { 
      // Connected - Start parsing 
      new AsyncLoadXMLFeed().execute(); 
     } 
    } 

    private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected Void doInBackground(Void... params) { 
      // Obtain feed 
      GeoDOMParser myParser = new GeoDOMParser(); 
      feed3 = myParser.parseXml(GEORSSFEEDURL); 
      return null; 
     } 
     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 

      Bundle bundle = new Bundle(); 
      bundle.putSerializable("feed", feed3); 

      // launch List activity 
      Intent intent = new Intent(GeoSplashActivity.this, GeoListActivity.class); 
      intent.putExtras(bundle); 
      startActivity(intent); 

      // kill this activity 
      finish(); 
     } 

    } 

} 

我從來沒有使用過位置的東西,所以我不完全知道我在做什麼在這裏。如果有人可以提供一些建議,我會很感激!

+0

查看以下鏈接http://www.androidsourcehelp.com/2014/03/get-location-and-its-changes-in-android.html – Yuvaraja

回答

0

希望你是不是在你的清單文件遺忘

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

This tutorial可以幫助你更好地理解。

編輯

谷歌已經提供Training獲取當前位置。

+0

沒有,我已經添加:) – user3356872

0
//Get coordinates if available: 
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
Location loc; 
double latitude=0,longitude=0; 
if ( (loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER))!=null ){ 
     latitude = loc.getLatitude(); 
    longitude = loc.getLongitude(); 
}else if((loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER))!=null ){ 
    latitude = loc.getLatitude(); 
    longitude = loc.getLongitude(); 
} 
//If any coordinate value is recieved, use it. 
if(latitude!=0 || longitude!=0){ 
    String latitude = String.valueOf(latitude); 
     String longitude = String.valueOf(longitude); 
     //TODO post into url 
}  
0

您應該將位置變量的初始化移動到onCreate方法。另外你還應該檢查是否location != null

lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
if (location != null) { 
    longitude = location.getLongitude(); 
    latitude = location.getLatitude(); 
    GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20"; 
} else { 
    ... 
} 
+0

感謝您的回覆,我試過這個,它會導致應用程序崩潰。對於else語句,我將GEORSSFEELURL更改爲拉取所有xml數據的url。 – user3356872

+0

@ user3356872如果發生崩潰,請發帖logcat – nikis

0

我做同樣的事情,這對我的作品! 但是,我需要的服務器是一個node.js服務器,並且數據是JSON。

public class GetWeatherDataRest extends AsyncTask<Void, Void, String> { 
private static final String TAG = "GetWeatherDataRest"; 

// get lat and long from main activity 
double lat = MyActivity.lat; 
double lng = MyActivity.lng; 

// the url 
String url = "http://ThisIsTheAddress/weather/5days?lat="+lat+"&lng="+lng; 
public MyActivity context; 
private List<Weather> posts; 

public GetWeatherDataRest(MyActivity activity){ 
    this.context = activity; 
} 

@Override 
protected String doInBackground(Void... params) { 

    try { 
     //Create an HTTP client 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet get = new HttpGet(url); 

     //Perform the request and check the status code 
     HttpResponse response = client.execute(get); 
     StatusLine statusLine = response.getStatusLine(); 
     if(statusLine.getStatusCode() == 200) { 
      HttpEntity entity = response.getEntity(); 
      InputStream content = entity.getContent(); 

      try { 
       //Read the server response and attempt to parse it as JSON 
       Reader reader = new InputStreamReader(content); 
       GsonBuilder gsonBuilder = new GsonBuilder(); 
       gsonBuilder.setDateFormat("M/d/yy hh:mm a"); 
       Gson gson = gsonBuilder.create(); 
       posts = new ArrayList<Weather>(); 
       posts = Arrays.asList(gson.fromJson(reader, Weather[].class)); 
       content.close(); 
      } catch (Exception ex) { 
       Log.e(TAG, "Failed to parse JSON due to: " + ex); 
      } 
     } else { 
      Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode()); 
     } 
    } catch(Exception ex) { 
     Log.e(TAG, "Failed to send HTTP POST request due to: " + ex); 
    } 
    return null; 
} 

@Override 
protected void onPostExecute(String result) { 

    context.updateFields(posts); 

} 

}

歐凱!這是我的GpsFragment,我得到了lng和lat! 我沒有這個尚未完成的,所以它可能貌不驚人,但它的工作原理,還給出了它從LNG &地址LAT利用地理編碼

您應該實現LocationListener的。

public class GpsFragment extends Fragment implements LocationListener{ 

public Location location; 
LocationManager locationManager; 
String provider; 

List<Address> mAddresses; 

TextView mAddress1; 
TextView mAddress2; 

public static double lat; 
public static double lng; 

private static final String TAG = "MyGps"; 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View myInflatedView = inflater.inflate(R.layout.gps_fragment, container,false); 

    mAddress1 = (TextView) myInflatedView.findViewById(R.id.address_text); 
    mAddress2 = (TextView) myInflatedView.findViewById(R.id.address_text2); 

    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    provider = locationManager.getBestProvider(criteria, false); 
    Location location = locationManager.getLastKnownLocation(provider); 
    locationManager.requestLocationUpdates(provider, 100, 1, this); 

    if(location != null){ 
     onLocationChanged(location); 
     Log.v(TAG, "Location available!"); 
    } 
    else{ 
     mAddress1.setText("No location"); 
     Log.e(TAG, "Location not available!"); 
    } 

    return myInflatedView; 

} 

// So i think this is what you need! the 'onLocationChanged' 
@Override 
public void onLocationChanged(Location location) { 
    this.location = location; 
    lat = location.getLatitude(); 
    lng = location.getLongitude(); 

    Geocoder mLocation = new Geocoder(getActivity().getApplicationContext(), Locale.getDefault()); 
    try { 
     mAddresses = mLocation.getFromLocation(lat, lng, 1); 

     if(mAddresses != null) { 
      Address returnedAddress = mAddresses.get(0); 
      StringBuilder strReturnedAddress = new StringBuilder("Address:\n"); 
      for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) { 
       strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); 
      } 
      // mAddress.setText(strReturnedAddress.toString()); 

      //mAddress1.setText("lat"+lat); 
      //mAddress2.setText("lng"+lng); 

      mAddress1.setText("Address: "+returnedAddress.getAddressLine(0).toString()); 
      mAddress2.setText("City: "+returnedAddress.getAddressLine(1).toString()); 
     } 
     else{ 
      // mAddress.setText("No Address returned!"); 
     } 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     //mAddress.setText("Cannot get Address!"); 
    } 

    ((MyActivity)getActivity()).fetchData(); 
} 


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

} 

@Override 
public void onProviderEnabled(String s) { 

} 

@Override 
public void onProviderDisabled(String s) { 

} 

}

+0

您的代碼不能解釋您是如何得到經度和緯度的? – user3356872

+0

難道你沒有那樣做嗎? 'location.getLatitude',以及我想我誤解了,我會盡快編輯 – user3486059