【问题标题】:Cannot assign local value to global value无法将本地值分配给全局值
【发布时间】:2018-08-10 02:55:17
【问题描述】:

我只是 java/android 的初学者。我试图将位置纬度和经度传递给火力基地。因此,我敬酒以查看它显示的值 0.0。我将 lat 和 long 值从 client.getlastlocation 传递到 lat 和 lon 的全局值,但它显示默认值 0.0,为什么会这样?

public class shopaction extends Fragment implements CompoundButton.OnCheckedChangeListener{

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Location location;
GoogleApiClient googleApiClient;
FusedLocationProviderClient client;
private String mParam1;
private String mParam2;
String s;
Switch action;
public double lat,lon;
private OnFragmentInteractionListener mListener;

public shopaction() {
}
public static shopaction newInstance(String param1, String param2) {
    shopaction fragment = new shopaction();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_shopaction, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    action = (Switch) view.findViewById(R.id.action);
    action.setOnCheckedChangeListener(this);
    client = LocationServices.getFusedLocationProviderClient(getActivity());
    Button button=(Button)view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);

            }
            client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    lat=location.getLatitude();
                    lon=location.getLongitude();
                }
            });


        }
    });
    client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            lat=location.getLatitude();
            lon=location.getLongitude();
        }
    });
    Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();

    FirebaseDatabase  firebaseDatabase=FirebaseDatabase.getInstance();
    DatabaseReference databaseReference=firebaseDatabase.getReference();
    databaseReference.child("shop").child("location").setValue(lat);
}
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if(action.isChecked())
    {
        Toast.makeText(getActivity(),"Your shop is open",Toast.LENGTH_LONG).show();
        action.setText("open");
        s="open";
    }
    else
    {
        Toast.makeText(getActivity(),"Your shop is closed",Toast.LENGTH_LONG).show();
        action.setText("close");
        s="close";
    }

}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

【问题讨论】:

  • 在使用location.getLatitude();之前,你在哪里给位置赋值?

标签: java android


【解决方案1】:

问题是 getLastLocation() 返回一个 Task 然后异步操作。在实际调用成功侦听器回调之前,位置数据不可用。同时,您的代码继续使用latlon 的当前(默认)值0 来显示Toast

解决此问题的一种方法是让您的成功侦听器回调显示 toast,而不是您的主代码。所以不要这样:

client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
    @Override
    public void onSuccess(Location location) {
        lat=location.getLatitude();
        lon=location.getLongitude();
    }
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();

// Firebase update code that depends on location data

使用这个:

client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
    @Override
    public void onSuccess(Location location) {
        lat=location.getLatitude();
        lon=location.getLongitude();
        Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();

        // Firebase update code that depends on location data
    }
});

【讨论】:

  • 这显示了正确的纬度和经度,但为什么它没有传递给全局变量
  • @Akishere - 是的。它只是异步执行。这是使用异步工具(如 Android 的定位服务)的困难之一:您必须组织您的代码,以便它的某些部分在它们所依赖的数据可用之前不会运行。因此,对于您的情况,您可能希望将所有 Firebase 更新代码移动到成功侦听器中,就像我对 Toast 所做的那样。 (或者将其全部移到一个单独的方法中,该方法从成功侦听器中调用。)
猜你喜欢
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 2021-06-21
  • 1970-01-01
  • 2017-01-16
相关资源
最近更新 更多