2015-09-28 46 views
2

这是我的变量:如何在Java(Android Studio)中的类之间传递变量值?

public class List extends Activity { 

double lat; 
double lon; 

public class MyLocationListener implements LocationListener{ 
    @Override 
    public void onLocationChanged(Location loc){ 
    lat = loc.getLatitude(); 
    lon = loc.getLongitude(); 
    } 
....... 
} 

我想在这里得到了纬度和经度值:

public class AmbilData extends AsyncTask<String, String, String> { 
    ..... 

    protected String doInBackground(String... arg0) { 
    // TODO Auto-generated method stub 

    String url; 

    url = "http://anjayanjay.esy.es?lat="+lat+"&lon="+lon; //here i need the variable value 
....................... 
} 

我采用了android工作室是新,该代码具有LAT = 0,LON = 0当我跑它。有人能告诉我如何解决这个问题吗?

+0

不知道你的问题是什么以及你打电话给你的AsysncTask。 –

回答

2

您可以通过构造函数传递:

public class List extends Activity { 

double lat; 
double lon; 

public class MyLocationListener implements LocationListener{ 
    @Override 
    public void onLocationChanged(Location loc){ 
    lat = loc.getLatitude(); 
    lon = loc.getLongitude(); 
    new AmbilData(loc).execute(); 
    } 
....... 
} 

public class AmbilData extends AsyncTask<String, String, String> { 
    private Location mLoc; 
    ..... 

    public AmbilData(Location loc) { 
     mLoc = loc; 
    } 

    protected String doInBackground(String... arg0) { 
    // TODO Auto-generated method stub 

    String url; 

    url = "http://anjayanjay.esy.es?lat="+mLoc.getLatitude()+"&lon="+mLoc.getLongitude(); //here i need the variable value 
....................... 
} 

或通过AsyncTaskParam,这就需要改变你的AsyncTask的第一个泛型类型:

public class List extends Activity { 

double lat; 
double lon; 

public class MyLocationListener implements LocationListener{ 
    @Override 
    public void onLocationChanged(Location loc){ 
    lat = loc.getLatitude(); 
    lon = loc.getLongitude(); 
    new AmbilData().execute(loc); 
    } 
....... 
} 

public class AmbilData extends AsyncTask<Location, String, String> { 
    ..... 

    protected String doInBackground(Location... arg0) { 
    // TODO Auto-generated method stub 

    String url; 

    url = "http://anjayanjay.esy.es?lat="+arg0[0].getLatitude()+"&lon="+arg0[0].getLongitude(); //here i need the variable value 
....................... 
} 
0

依我之见,你从一个数据AsynTask。在您的AsyncTask中重写onPostExcute()。数据(字符串)doInbackground()完成后可用。举个简单的例子:

@Override 
protected void onPostExecute(String string) { 
    // Call back Data and Display the current string data in the UI 
    activity.callBackDataFromAsyncTask(string); 
} 

希望这个帮助!