【问题标题】:Fused location Returns NULL融合位置返回 NULL
【发布时间】:2017-10-05 10:43:58
【问题描述】:

我在两个移动设备之间使用 firebase 制作了一个聊天应用程序,然后我创建了一个按钮来使用 Google API 客户端发送设备的位置,但它一直返回 null,尽管我在另一个活动中尝试过它并且效果很好。 聊天室 ::

public class Chat_room extends Activity implements ConnectionCallbacks,OnConnectionFailedListener, LocationListener {

    Button btnsend, btnGps;
    TextView recievedmsg, txtgps;
    EditText editmsg;

    DatabaseReference rootRoomName;

    String roomname;
    String username;
    private String chatusername;
    private String chatmessage;
    String Response;
    private GoogleApiClient GAC;
    LocationRequest LR;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        build_GAC();
        setContentView(R.layout.activity_chat_room);
        btnsend = (Button) findViewById(R.id.btnsend);
        btnGps = (Button) findViewById(R.id.btnGps);
        recievedmsg = (TextView) findViewById(R.id.recievedmsg);
        editmsg = (EditText) findViewById(R.id.editmsg);
        txtgps = (TextView) findViewById(R.id.txtgps);



        roomname = getIntent().getExtras().get("Room_Name").toString();
        username = getIntent().getExtras().get("UserName").toString();

        setTitle(roomname);
        rootRoomName = FirebaseDatabase.getInstance().getReference().getRoot().child(roomname);
        btnsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatabaseReference childRoot = rootRoomName.push();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("Name", username);
                map.put("message",Response);
                childRoot.updateChildren(map);


//                }
            }
        });

        rootRoomName.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                update_message(dataSnapshot);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                update_message(dataSnapshot);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void update_message(DataSnapshot dataSnapshot) {
        chatusername = (String) dataSnapshot.child("Name").getValue();
        chatmessage = (String) dataSnapshot.child("message").getValue();

        recievedmsg.append(chatusername + ":" + chatmessage + "\n\n");
    }

    protected void build_GAC(){
        GAC =new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (GAC != null) {
            GAC.connect();
        }
    }

    @Override

    protected void onStop() {
        GAC.disconnect();
        super.onStop();
    }


    @Override
    public void onConnected(Bundle connectionHint) {
        createLocationRequest();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location Location = LocationServices.FusedLocationApi.getLastLocation(GAC);
        if (Location != null) {
            Double Lat = Location.getLatitude();
            Double lon = Location.getLongitude();
            Response=("Ltitude is " + String.valueOf(Lat) + "\n" + "Longitude is " + String.valueOf(lon));

        }
    }
    protected void createLocationRequest() {
        LR = new LocationRequest();
        LR.setInterval(2000);
        LR.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }


    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this, "the connection suspended", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this, "the connection failed", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLocationChanged(Location location) {
        Response=("Ltitude is " + String.valueOf(location.getLatitude()) + "\n \n" + "Longitude is " + String.valueOf(location.getLongitude()));

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }


}

主要活动::

public class MainActivity extends AppCompatActivity {
    EditText roomname;
    Button join;
    ListView roomlist;
    ArrayList<String> roomarraylist; // to store rooms list
    ArrayAdapter<String>  roomadapter;

    DatabaseReference databaseReference;
    public String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        roomname=(EditText)findViewById(R.id.editText);
        join=(Button)findViewById(R.id.button2);

        roomlist=(ListView)findViewById(R.id.roomlistview);
        roomarraylist=new ArrayList<String>();
        roomadapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,roomarraylist);

        roomlist.setAdapter(roomadapter);

        databaseReference= FirebaseDatabase.getInstance().getReference().getRoot();

        request_username();
        join.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,Object> map=new HashMap<String, Object>();
                map.put(roomname.getText().toString(),"");
                databaseReference.updateChildren(map);
            }
        });
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Iterator iterator =dataSnapshot.getChildren().iterator();
                Set<String> set=new HashSet<String>();

                while (iterator.hasNext()){
                    // GET NAMES OF ALL ROOMS ONE BY ONE FROM  DATABASE
                    set.add((String) ( (DataSnapshot)iterator.next()).getKey());
                }
                roomarraylist.clear();
                roomarraylist.addAll(set);

                roomadapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        roomlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(MainActivity.this,Chat_room.class);
                intent.putExtra("Room_Name",((TextView)view).getText().toString());
                intent.putExtra("UserName",username);
                startActivity(intent);
            }
        });
    }

    private void request_username() {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("Please Enter your Name");
        final EditText edittext=new EditText(this);
        builder.setView(edittext);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                username=edittext.getText().toString();
                if(!TextUtils.isEmpty(username)){

                }
                else{
                    request_username();
                }
            }
        }).setNegativeButton("Quit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                request_username();
            }
        });

        builder.show();
    }
}

【问题讨论】:

  • 请详细点,我找不到您用来发送位置的点击。!
  • @IbrahimAli 在聊天室课程中发送按钮
  • i created a button to send the location of the device我找不到这部分代码。
  • @IbrahimAli 在聊天室中称为发送的按钮会发送包含位置的可变响应
  • 您发送的是map.put("Name", username); map.put("message",Response);response 值(如果您要引用它,请不要包含任何初始值。

标签: android firebase google-api firebase-realtime-database android-fusedlocation


【解决方案1】:

如果您使用的设备的目标超过 6.0,那么您没有提及您正在使用的设备,那么它不会工作考虑以下代码

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

如果在您的应用中授予权限,我在这里看不到发出位置请求的代码,那么它将直接返回而不发出位置请求。

考虑以下链接 http://javapapers.com/android/android-location-fused-provider/

【讨论】:

  • 好的,但我在你的代码“requestLocationUpdates”中看不到位置监听器注册
  • 我添加了“请求位置更新”,但仍然返回 null
【解决方案2】:

首先,连接到播放服务是一个异步过程。根据您的代码,您的“发送”按钮不知道此过程。所以这是接收 null 的最可能原因。

即使这一步也不是问题(碰巧,onConnected 回调在您按下发送之前被触发)还有权限检查。你对此一无所知

而且,从提供者那里获取最后一个已知位置往往是空的。您必须请求新的位置。您只需调用此createLocationRequest();,但它没有发出位置请求。

以上所有内容都是您获得 null 的原因。只需考虑所有这些。

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多