0

I made a chat application using firebase between two mobile devices then i created a button to send the location of the device using Google API client but it keeps returning null though i tried it in another activity and it worked fine . ChatRoom ::

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) {

    }


}

Main Activity::

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();
    }
}
KENdi
  • 7,576
  • 2
  • 16
  • 31
  • please be more specific , i can't find the click you used to send the location.! –  May 07 '17 at 10:52
  • @IbrahimAli the button send at the chat room class – Sondos Ahmed May 07 '17 at 10:53
  • `i created a button to send the location of the device` i can't find this part of code . –  May 07 '17 at 11:16
  • @IbrahimAli the button called send in the chat room it sends variable response which holds the location – Sondos Ahmed May 07 '17 at 11:29
  • you are sending `map.put("Name", username); map.put("message",Response);` and the `response` value (if you are reffering to it, dosen't contain any initial value. –  May 07 '17 at 11:38
  • @IbrahimAli that is the problem it returns null when it has to return latitude and magnitude – Sondos Ahmed May 07 '17 at 11:42

2 Answers2

0

You have not mention which device you are using if device you are using is having target more then 6.0 then its not going to work consider following code

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

Here i cant see code for making location request if permission is granted in your app then it will directly return without making location request.

Consider following link http://javapapers.com/android/android-location-fused-provider/

Jaykishan Sewak
  • 822
  • 6
  • 13
0

First of all, connecting to the play services is a async process. Based on your code, your "sending" button is not aware of this process. So this is the most possible reason receiving null.

And even this step is not a problem(by chance, the onConnected callback is fired before you press send) there is also permission check. You didn't anything about this

And also, getting the last known location from providers is tend to null. You have to request for fresh location. You just call this createLocationRequest(); but it didn't make location request.

The all above is the reasons of why you getting null. Just consider all of them.

blackkara
  • 4,900
  • 4
  • 28
  • 58