簡體   English   中英

使用Java Firebase的android studio中的IF語句count ++

[英]IF statement count++ in android studio using java firebase

我如何在Java android fire-base上放置與此相關的功能。 我正在創建一個聊天應用程序,並且具有這樣的現有火基結構。請說我發送一條消息“ Hello ”。

Chat:
    Author:"name"
    Chat:"Hello"

我想推入一個函數,它將計算每個用戶中消息的數量。 因此會是這樣。 假設我發送一條消息打招呼? 馬上回來

Chat:
    Author:"name"
    Chat:"hi?"
    numMessages: 1

Chat:
    Author:"name"
    Chat:"Be right back"
    numMessages: 2

我認為是如果語句計數++? 但我會盡一切努力與此。 Java和Android大師希望您能給我一些建議,先生。

全局int變量: int counter = 0;
在您的onClick中添加: counter++; 隨時將計數器設置為0,否則將一直計數-僅在重新創建活動時才將其設置為0。

如果您要將其發送到firebase,則需要在其中添加計數器,然后將其隨消息一起發送,請使用名為“ counter”(與字符串“ author”和“消息”,發送后將發送並顯示在您的聊天中。

這回答了你的問題了嗎?

更新:

首先,進入Message.class並添加:

int counter;

public int getCounter(){
    return counter;
}

public void setCounter(int counter){
    this.counter = counter;
}

如果要在視圖中顯示計數器,則只需在fragment_message.xml添加另一個TextView,或者以編程方式將其添加到消息中,即可在MessageAdapter.java添加populateView:

//if you added an extra TextView in your fragment_message.xml
TextView counter = (TextView) view.findViewById(R.id.yourcounterid);

counter.setText(message.getCounter());

//if you want to add the number in your messageView:
messageView.setText(message.getMessage() + " " + message.getCounter());

所以到您的MainActivity.java

public class MainActivity extends AppCompatActivity{


private EditText editText;
private ListView listView;


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

    counter = 0;
    Firebase.setAndroidContext(this);
    final Firebase firebase = new Firebase("https://samp-is.firebaseio.com/");


    editText = (EditText) findViewById(R.id.editText);
    listView = (ListView) findViewById(R.id.listView);

    listView.setAdapter(new MessageAdapter(this, Message.class, R.layout.fragment_message, firebase.child("chat")));

    Button button = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            counter++;

            Message message = new Message();

            message.setMessage(editText.getText().toString());
            editText.setText("");
            message.setAuthor("Name");
            message.setCounter(counter);
            firebase.child("chat").push().setValue(message);


        }
        });
    }
}

如果我沒記錯的話,Firebase應該在其數據庫中添加一個子級“計數器”,並用您的計數器值對其進行更新。 它行得通嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM