0

I have created a chat application using android Firebase. Everything is working fine: I can see all users in my activity.

Now I want to display there statuses with there names in ListView. So I tried to build presence system for my application.

So far I searched a lot and found some code and information about it. But I didn't got fully functional presence system well explained.

Till now I understood user have to put HIS online status in db and onDisconnect should put offline.

Secondly reading other users status.

This is my activity where I fetch all users in listview :

public class Users extends AppCompatActivity {
    ListView usersList;
    TextView noUsersText;
    ArrayList<String> al = new ArrayList<>();
    int totalUsers = 0;
    ProgressDialog pd;
    private Firebase mRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_users);

        usersList = (ListView)findViewById(R.id.usersList);
        noUsersText = (TextView)findViewById(R.id.noUsersText);

        pd = new ProgressDialog(Users.this);
        pd.setMessage("Loading...");
        pd.show();

        String url = "https://your-app.firebaseio.com/users.json";

        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
            @Override
            public void onResponse(String s) {
                doOnSuccess(s);
            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("" + volleyError);
            }
        });

        RequestQueue rQueue = Volley.newRequestQueue(Users.this);
        rQueue.add(request);

        usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserDetails.chatWith = al.get(position);
                startActivity(new Intent(Users.this, Chat.class));
            }
        });
////////////////////////////////////till here user are displayed///////////////

///here i started presence system

        Firebase.getDefaultConfig().setLogLevel(Logger.Level.DEBUG);
        Firebase.setAndroidContext(this);
        mRef = new Firebase("https://yourapp.firebaseio.com/").child("users").child("presences").child("how would i set each user status url?");
        mRef.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if ((Boolean) dataSnapshot.getValue()) {
                    comeOnline();
                } else {
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });



    }//oncreate ends here



    private void comeOnline() {
        mRef.goOnline();
        mRef.onDisconnect().setValue(getOfflineValue(), new Firebase.CompletionListener() {
            @Override
            public void onComplete(FirebaseError firebaseError, Firebase firebase) {
                if (firebaseError == null) {
                    mRef.setValue(getOnlineValue());
                }
            }
        });
    }

    private void comeOffline() {
        mRef.goOffline();
    }

    private Map<String, Object> getOfflineValue() {
        Map<String, Object> map = new HashMap<>();
        map.put("status", "offline");
        map.put("lastSeen", ServerValue.TIMESTAMP);
        return map;
    }

    private Map<String, Object> getOnlineValue() {
        Map<String, Object> map = new HashMap<>();
        map.put("status", "online");
        map.put("lastSeen", ServerValue.TIMESTAMP);
        return map;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }







    public void doOnSuccess(String s){
        try {
            JSONObject obj = new JSONObject(s);

            Iterator i = obj.keys();
            String key = "";

            while(i.hasNext()){
                key = i.next().toString();

                if(!key.equals(UserDetails.username)) {
                    al.add(key);
                }

                totalUsers++;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(totalUsers <=1){
            noUsersText.setVisibility(View.VISIBLE);
            usersList.setVisibility(View.GONE);
        }
        else{
            noUsersText.setVisibility(View.GONE);
            usersList.setVisibility(View.VISIBLE);
            usersList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al));
        }

        pd.dismiss();
    }
}

Now I am confused how to give each user url for presence status and how could I add it with user listview.

Maxim
  • 52,561
  • 27
  • 155
  • 209
Addi.Star
  • 475
  • 2
  • 15
  • 36
  • 1
    I'm not sure why you're using the old 2.x Firebase SDK, but I recommend switching to the latest version. The documentation for that version for Android has a good example here: https://firebase.google.com/docs/database/android/offline-capabilities#section-sample. It's similar to the sample you used, but more up to date. – Frank van Puffelen Jan 15 '17 at 22:25
  • If you then want to show what users are online, you'd attach a child listener to the `/users` node. See https://firebase.google.com/docs/database/android/lists-of-data#child-events – Frank van Puffelen Jan 15 '17 at 22:26
  • i have studied it all , can you provide any working example to check user with their status i can see the methods but i am new to firebase any example would work great – Addi.Star Jan 15 '17 at 22:36
  • @FrankvanPuffelen check my code where i start for presence system, is it ok ? – Addi.Star Jan 15 '17 at 22:44

0 Answers0