0

我使用 android Firebase 创建了一个聊天应用程序。一切正常:我可以看到我活动中的所有用户。

现在我想在那里显示带有名称的状态ListView。所以我尝试为我的应用程序构建存在系统。

到目前为止,我进行了很多搜索,并找到了一些有关它的代码和信息。但是我没有很好地解释功能齐全的存在系统。

直到现在我明白用户必须把他的在线状态放在数据库中并且onDisconnect应该离线。

其次阅读其他用户的状态。

这是我在 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();
    }
}

现在我很困惑如何为每个用户提供存在状态的 url,以及如何将它添加到用户列表视图中。

4

0 回答 0