无法将本地值分配给全局值

时间:2018-08-10 02:55:18

标签: java android

我只是Java / android中的初学者。我试图将位置的经度和纬度传递给firebase。因此,我敬酒消息以查看显示为0.0的值。我从client.getlastlocation将lat和long值传递给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);
}

}

1 个答案:

答案 0 :(得分:0)

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

解决此问题的一种方法是让您的成功侦听器回调显示敬酒信息,而不是主代码。所以代替这个:

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
    }
});