gpt4 book ai didi

java - 在类(而不是 Activity )之间传递数据会导致空指针异常

转载 作者:行者123 更新时间:2023-12-01 23:54:01 27 4
gpt4 key购买 nike

我有一个 Activity ShowList,其中有一些edittext字段和按钮。我有一个按钮获取位置”,它通过GPS获取当前位置

ShowList Activity (工作正常,我可以获得位置):

  public class ShowList extends Activity implements OnClickListener{


GPSTracker gps; //i use GPSTracker to get the location (it is not an activity)
.........

case R.id.getlocation:
// create class object
gps = new GPSTracker(ShowList.this);

// check if GPS enabled
if(gps.canGetLocation()){

double latitude = gps.getLatitude();
double longitude = gps.getLongitude();

Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
...
}

我有一个自定义适配器:

    public class myAdapter extends BaseAdapter{   
ShowList locationclass=new ShowList();
.....
TextView Location = (TextView) convertView.findViewById(R.id.text_location);

String lat=Double.toString(locationclass.gps.getLatitude());
String lo=Double.toString(locationclass.gps.getLongitude());
String coordinates="Lat: " + lat + " Long: " + lo;
Location.setText(coordinates);

我在“String lat...”中收到nullpointer

那么,如何将 locationShowList Activity 传递到 adapter

最佳答案

您无法通过new实例化Activity。否则,你应该传递上下文;构造函数中 Adapter 的纬度和经度:

public class myAdapter extends BaseAdapter{   
private String latitude;
private String longitude;
private ArrayList<Item> items;
private Context context; // TODO: use it for layoutInflater

//the constructor
public myAdapter(Context context, ArrayList<myItems> list, String latitude, String longitude) {
this.items = list;
this.latitude = latitude;
this.longitude = longitude;
this.context = context;
}
.....
TextView Location = (TextView) convertView.findViewById(R.id.text_location);
String coordinates="Lat: " + this.latitude + " Long: " + this.longitude;
Location.setText(coordinates);

关于java - 在类(而不是 Activity )之间传递数据会导致空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15877629/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com