如何在其他类中获取更新的双精度值

时间:2015-05-14 14:02:13

标签: java php android class

我正在使用谷歌地图。我想我正确地获得了Lat / Long对 - 即我试图在地图上显示的坐标 - 它们在我的SignIn类中正确更新。

我还有一个Map课程,我希望能够从SignIn课程中获取更新后的坐标。但是,当前获取GPS坐标的尝试始终返回我已经硬编码到SignIn类中的默认值。

如何从SignIn课程中的Map课程中获取更新后的值?

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;

import com.google.android.gms.maps.model.LatLng;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.OpenableColumns;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class SignIn extends Fragment {

    Context context_frag1;

    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse Response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    Intent intent;

    protected Context context;
    Button b;
    Button sendBtn;
    //String m_username,m_password;

    ProgressDialog dialog = null;
    public double latitude = 32.3234;// these values are getting my other class always but i update them down here y it getting these
    public double longitude = 72.456;

    EditText username,password;

    public SignIn() { }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fragment_layout_two,container, false);
        b = (Button)view.findViewById(R.id.button1); 

        username = (EditText)view.findViewById(R.id.username);
        password = (EditText)view.findViewById(R.id.password);

        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    public void run() {
                        login();    
                    }
                }).start(); 

            }
        });

        return view;
    }

    @SuppressWarnings("deprecation")
    void login(){

        while(true){

            try{            

                httpclient=new DefaultHttpClient();
                httppost= new HttpPost("my web adderss");

                nameValuePairs = new ArrayList<NameValuePair>(1);
                // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 

                nameValuePairs.add(new BasicNameValuePair("username",m_username.getText().toString().trim()));
                nameValuePairs.add(new BasicNameValuePair("password",m_password.getText().toString().trim()));
                //nameValuePairs.add(new BasicNameValuePair("id",m_id.getText().toString().trim()));  

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                Response=httpclient.execute(httppost);

                ResponseHandler<String> responseHandler = new BasicResponseHandler();

                final String response = httpclient.execute(httppost, responseHandler);
                System.out.println("Response : " + response); 
                 // delay to send loactions
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {

                        try{
                            String strn = response.replaceAll("[a-zA-Z//:]", "");       
                            String[] parts = strn.split(",");// this will separte lat lng where it get , 
                            String part1 = parts[0]; 
                            String part2 = parts[1]; 
                            latitude = Double.parseDouble(part1);  
                            longitude = Double.parseDouble(part2);
                            //here i get lat and lng  these are updating dynamically
                            Toast.makeText(getActivity().getApplicationContext(), ""+latitude +""+ longitude, Toast.LENGTH_LONG).show();
                        } catch (ArrayIndexOutOfBoundsException e) {
                            Toast.makeText(getActivity().getApplicationContext(), "ArrayIndexOutOfBoundsException", Toast.LENGTH_LONG).show();
                        }

                        try {
                            Response.getEntity().consumeContent();
                            httpclient.getConnectionManager().closeExpiredConnections();
                            httpclient.getConnectionManager().shutdown();
                        } catch (IOException e) {
                            Toast.makeText(getActivity().getApplicationContext(), "IOException", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }

                    }

                });

            }catch(Exception e){
                //dialog.dismiss();
                Log.i("catch", "i got exception here", e);
            }
        }
    }
}
  

现在我有其他地图类,我想要这些lat lng

> import com.google.android.gms.common.ConnectionResult;
>     import com.google.android.gms.common.GooglePlayServicesUtil; 
>     import com.google.android.gms.common.api.GoogleApiClient; 
>     import com.google.android.gms.location.FusedLocationProviderApi; 
>     import com.google.android.gms.location.LocationListener; 
>     import com.google.android.gms.location.LocationRequest; 
>     import com.google.android.gms.location.LocationServices; 
>     import com.google.android.gms.maps.CameraUpdate; 
>     import com.google.android.gms.maps.CameraUpdateFactory; 
>     import com.google.android.gms.maps.GoogleMap; 
>     import com.google.android.gms.maps.MapView; 
>     import com.google.android.gms.maps.SupportMapFragment; 
>     import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
>     import com.google.android.gms.maps.model.CameraPosition; 
>     import com.google.android.gms.maps.model.LatLng; 
>     import com.google.android.gms.maps.model.Marker; 
>     import com.google.android.gms.maps.model.MarkerOptions;
>     
>     import android.app.Dialog; import android.content.Intent;
>     import android.location.Location; import android.os.Bundle; 
>     import android.support.v4.app.FragmentActivity; 
>     import android.util.Log;
>     import android.view.Menu; import android.view.MenuItem; 
>     import android.widget.Toast;
>     
>      public class Map extends FragmentActivity implements 
>       GoogleApiClient.ConnectionCallbacks,
>       GoogleApiClient.OnConnectionFailedListener, LocationListener{
>     
>      private static final int GPS_ERRORDIALOG_REQUEST = 9001;     
>       GoogleMap mMap;     
>       //MapView vMap;     
>       Marker marker;
>       
>     
>        private LocationRequest mLocationRequest;
>           private GoogleApiClient mGoogleApiClient;
>        //private MarkerOptions option1;
>       
>                               private static final float Zoom =12;    public String TITLE = "Me";     private static final String TAG = "My map";
>      FusedLocationProviderApi mLocationClient;
>     
>               int zoom=13;
>               @Override   protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);
>                   if (servicesOK()) {
>                           setContentView(R.layout.activity_map);          //vMap = (MapView)findViewById(R.id.mapview);
>               //vMap.onCreate(savedInstanceState);
>                           if(initMap()){
>                   Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
>                   
>                   mGoogleApiClient = new GoogleApiClient.Builder(this)
>                     .addApi(LocationServices.API)
>                     .addConnectionCallbacks(this)
>                     .addOnConnectionFailedListener(this)
>                     .build();
>               
>                    mGoogleApiClient.connect();
>               
>                    new Thread(new Runnable() {
>                           public void run() {
>                               Vanlocation();  
>                           }
>     
>                         }).start();   
>                       
>                       }else{
>                   Toast.makeText(this, "Map not available !", Toast.LENGTH_SHORT).show();             }
>                       }       else{
>               
>                   setContentView(R.layout.activity_main);         }   }
>     
>           public boolean onCreateOptionsMenu(Menu menu) {         // Inflate the
>      menu; this adds items to the action bar if it is present.
>           getMenuInflater().inflate(R.menu.main, menu);
>                   return true;    }       public boolean servicesOK() {       int isAvailable =
>     GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
>                   if (isAvailable == ConnectionResult.SUCCESS) {          return true;        }       else if
>      (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
>               Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable,
>      this, GPS_ERRORDIALOG_REQUEST);          dialog.show();      }       else {
>               Toast.makeText(this, "Can't connect to Google Play services",
>      Toast.LENGTH_SHORT).show();      }       return false;
>               }   private void Vanlocation() {
>                   while(true){
>               try{            
>           
>                   runOnUiThread(new Runnable() {
>                                   
>                       public void run() {
>                           
>                       if(marker!=null){
>                               marker.remove();
>                           }
>                           // here i want those update value but i just get default values 
>                           signIn ll = new signIn();
>                           double lat=ll.lat;
>                           double lng=ll.lng; 
>                       gotoLocation(lat , lng , zoom);
>                           
>                           
>                   
>                   
>                       }
>                   });
>                   Thread.sleep(2500);
>                   
>               }catch(Exception e){
>                   
>                   System.out.println("Exception : " + e.getMessage());
>               }
>               
>               }
>               }   private boolean initMap() {         if(mMap == null){           SupportMapFragment mapFrag = 
>                       (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);        mMap =
>      mapFrag.getMap();        mMap.setMyLocationEnabled(true);                
>           mMap.getUiSettings().setZoomControlsEnabled(true);
>           mMap.getUiSettings().setMyLocationButtonEnabled(true);      //
>      gotoLocation(lat , lng , zoom);
>                   }
>                   return (mMap != null);  }       private void gotoLocation(double lat , double lng , float zoom){        LatLng ll = new LatLng(lat, lng);
>           CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
>           mMap.animateCamera(update);         String t="van";         setMarker(t,
>      ll.latitude, ll.longitude);  }       @Override   public boolean
>      onOptionsItemSelected(MenuItem item) {   
>                   return super.onOptionsItemSelected(item);   }
>       
>      
>       @Override
>         protected void onStart() {
>             super.onStart();
>             // Connect the client.
>             mGoogleApiClient.connect();
>          }
>     
>       @Override   protected void onStop() {       super.onStop();
>           MapStateManager mgr = new MapStateManager(this);
>           mgr.saveMapState(mMap, marker);
>           
>           if(mGoogleApiClient.isConnected()) {
>                 mGoogleApiClient.disconnect();
>            }
>               }
>               @Override   protected void onResume() {         super.onResume();       MapStateManager mgr = new MapStateManager(this);    CameraPosition
>      position =mgr.getSavedCameraPosition(mMap);      MarkerOptions m =
>     mgr.getmarker(mMap);
>       
>                   if(position !=null){        CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
>     mMap.moveCamera(update);      mMap.setMapType(mgr.getSavedMapType());
>           
>       setMarker(m.getTitle(),m.getPosition().latitude,m.getPosition().longitude);
>       //mMap.addMarker(m);
>                       }   }
>      private void setMarker(String locality, double lat, double lng) {
>       
>       
>           MarkerOptions options = new MarkerOptions()
>               .title(locality+lat+lng)            .position(new LatLng(lat, lng))
>       //.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mapmarker));
>               .icon(BitmapDescriptorFactory
>               .defaultMarker(BitmapDescriptorFactory.HUE_BLUE));      marker =
>      mMap.addMarker(options);         }
>               @Override   public void onConnectionFailed(ConnectionResult arg0) {
>           
>               }
>      
>       @Override   public void onConnected(Bundle arg0) {
>           
>                   mLocationRequest = LocationRequest.create();
>            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
>              mLocationRequest.setInterval(1000); // Update location every second
>     
>             LocationServices.FusedLocationApi.requestLocationUpdates(
>                     mGoogleApiClient, mLocationRequest, this);
>               }
>       @Override   public void onConnectionSuspended(int arg0) {       
>      Log.i(TAG, "GoogleApiClient connection has been suspend");
>               }
>     
>       @Override   public void onLocationChanged(Location location) {
>           //String msg ="Location: " + location.getLatitude() + "," +
>      location.getLongitude();         //Toast.makeText(getApplicationContext(),
>      msg, Toast.LENGTH_SHORT).show();         //LatLng ll = new
>      LatLng(location.getLatitude(),  location.getLongitude());
>           //CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
>           //mMap.animateCamera(update);       //String t="me";        //setMarker(t,
>      ll.latitude, ll.longitude);  }
>       
>      
>        }

2 个答案:

答案 0 :(得分:1)

我的错误是静态的 我应该在变量名称

之前使用word static

我做了什么,我创建了另一个类,它将保存所有类将获取它们的静态变量。

public class gpsLatLng {

public static double lat;
public static double lng;



}
  

但我得到的问题是,当循环运行时,我得到一次正确的值,我得到相同的值未更新,但值正在定期更新

答案 1 :(得分:1)

如果您想删除内存泄漏,还可以使用LocalBroadCast向其他活动发送消息。

<强> ReceiverActivity.java

此活动将等待任何名为your-custom-event-name的事件发生。

@Override
public void onCreate(Bundle savedInstanceState) {

    ...

    // Register to receive messages.
    // We are registering an observer (mMessageReceiver) to receive Intents
    // with actions named "custom-event-name".
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
    new IntentFilter("your-custom-event-name")); 
}

// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {@Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String lat = intent.getStringExtra("lat");
        String lng = intent.getStringExtra("lat");
        Log.d("receiver", "Got lat : " + lat + " lgn : "+lng);
    }
};

@Override
protected void onDestroy() {
    // Unregister since the activity is about to be closed.
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
    super.onDestroy();
}

<强> SenderActivity.java

使用以下简短代码将任何类型的数据发送到其他活动

Intent intent = new Intent("your-custom-event-name");
// You can also include some extra data.
intent.putExtra("lat", "1");
intent.putExtra("lng", "5");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);