2017-02-13 116 views
0

我使用this課程製作了一個聊天應用程序。我測試:當退出並重新打開應用程序時,不顯示聊天消息

screenshot

然後我關閉應用程序,一段時間後,打開了它。令人奇怪的是所有的消息都消失了:

screenshot

他們只出現回來時,我註銷並重新登錄。 如何解決該錯誤?

我的代碼:

MainActivity.java:

import android.content.Intent; 
import android.support.annotation.NonNull; 
import android.support.design.widget.FloatingActionButton; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.ListView; 
import android.widget.Toast; 

import com.firebase.ui.auth.AuthUI; 
import com.firebase.ui.database.FirebaseListAdapter; 
import com.google.android.gms.tasks.OnCompleteListener; 
import com.google.android.gms.tasks.Task; 
import com.google.firebase.auth.FirebaseAuth; 
import com.google.firebase.database.FirebaseDatabase; 

public class MainActivity extends AppCompatActivity { 
    private static final int SIGN_IN_REQUEST_CODE = 111; 
    private FirebaseListAdapter<ChatMessage> adapter; 
    private ListView listView; 
    private String loggedInUserName = ""; 

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

     //find views by Ids 
     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     final EditText input = (EditText) findViewById(R.id.input); 
     listView = (ListView) findViewById(R.id.list); 

     if (FirebaseAuth.getInstance().getCurrentUser() == null) { 
      // Start sign in/sign up activity 
      startActivityForResult(AuthUI.getInstance() 
        .createSignInIntentBuilder() 
        .build(), SIGN_IN_REQUEST_CODE); 
     } else { 
      // User is already signed in, show list of messages 
      showAllOldMessages(); 
     } 

     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       if (input.getText().toString().trim().equals("")) { 
        Toast.makeText(MainActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show(); 
       } else { 
        FirebaseDatabase.getInstance() 
          .getReference() 
          .push() 
          .setValue(new ChatMessage(input.getText().toString(), 
            FirebaseAuth.getInstance().getCurrentUser().getDisplayName(), 
            FirebaseAuth.getInstance().getCurrentUser().getUid()) 
          ); 
        input.setText(""); 
       } 
      } 
     }); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     if (item.getItemId() == R.id.menu_sign_out) { 
      AuthUI.getInstance().signOut(this) 
        .addOnCompleteListener(new OnCompleteListener<Void>() { 
         @Override 
         public void onComplete(@NonNull Task<Void> task) { 
          Toast.makeText(MainActivity.this, "You have logged out!", Toast.LENGTH_SHORT).show(); 
          finish(); 
         } 
        }); 
     } 
     return true; 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     if (requestCode == SIGN_IN_REQUEST_CODE) { 
      if (resultCode == RESULT_OK) { 
       Toast.makeText(this, "Signed in successful!", Toast.LENGTH_LONG).show(); 
       showAllOldMessages(); 
      } else { 
       Toast.makeText(this, "Sign in failed, please try again later", Toast.LENGTH_LONG).show(); 

       // Close the app 
       finish(); 
      } 
     } 
    } 

    private void showAllOldMessages() { 
     loggedInUserName = FirebaseAuth.getInstance().getCurrentUser().getUid(); 
     Log.d("Main", "user id: " + loggedInUserName); 

     adapter = new MessageAdapter(this, ChatMessage.class, R.layout.item_in_message, 
       FirebaseDatabase.getInstance().getReference()); 
     listView.setAdapter(adapter); 
    } 

    public String getLoggedInUserName() { 
     return loggedInUserName; 
    } 
} 

ChatMessage.java:

public class ChatMessage { 
    private String messageText; 
    private String messageUser; 
    private String messageUserId; 

    public ChatMessage(String messageText, String messageUser, String messageUserId) { 
     this.messageText = messageText; 
     this.messageUser = messageUser; 
     this.messageUserId = messageUserId; 
    } 

    public ChatMessage(){ 

    } 

    public String getMessageUserId() { 
     return messageUserId; 
    } 

    public void setMessageUserId(String messageUserId) { 
     this.messageUserId = messageUserId; 
    } 

    public String getMessageText() { 
     return messageText; 
    } 

    public void setMessageText(String messageText) { 
     this.messageText = messageText; 
    } 

    public String getMessageUser() { 
     return messageUser; 
    } 

    public void setMessageUser(String messageUser) { 
     this.messageUser = messageUser; 
    } 
} 

ChatAdapter.java:

import android.text.format.DateFormat; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 

import com.firebase.ui.database.FirebaseListAdapter; 
import com.google.firebase.database.DatabaseReference; 

public class MessageAdapter extends FirebaseListAdapter<ChatMessage> { 

    private MainActivity activity; 

    public MessageAdapter(MainActivity activity, Class<ChatMessage> modelClass, int modelLayout, DatabaseReference ref) { 
     super(activity, modelClass, modelLayout, ref); 
     this.activity = activity; 
    } 

    @Override 
    protected void populateView(View v, ChatMessage model, int position) { 
     TextView messageText = (TextView) v.findViewById(R.id.message_text); 
     TextView messageUser = (TextView) v.findViewById(R.id.message_user); 

     messageText.setText(model.getMessageText()); 
     messageUser.setText(model.getMessageUser()); 
} 

    @Override 
    public View getView(int position, View view, ViewGroup viewGroup) { 
     ChatMessage chatMessage = getItem(position); 
     if (chatMessage.getMessageUserId().equals(activity.getLoggedInUserName())) 
      view = activity.getLayoutInflater().inflate(R.layout.item_out_message, viewGroup, false); 
     else 
      view = activity.getLayoutInflater().inflate(R.layout.item_in_message, viewGroup, false); 

     //generating view 
     populateView(view, chatMessage, position); 

     return view; 
    } 

    @Override 
    public int getViewTypeCount() { 
     // return the total number of view types. this value should never change 
     // at runtime 
     return 2; 
    } 

    @Override 
    public int getItemViewType(int position) { 
     // return a value between 0 and (getViewTypeCount - 1) 
     return position % 2; 
    } 
} 

PS我試圖粘貼代碼如下到onResume方法的MainActivity,但沒有什麼好事發生。

if (FirebaseAuth.getInstance().getCurrentUser() == null) { 
     // Start sign in/sign up activity 
     startActivityForResult(AuthUI.getInstance() 
       .createSignInIntentBuilder() 
       .build(), SIGN_IN_REQUEST_CODE); 
    } else { 
     // User is already signed in, show list of messages 
     showAllOldMessages(); 
    } 

P.P.S當我嘗試在聊天中發送新消息,發現錯誤時,我會看到它們。但是當我註銷並重新登錄時,這些消息不存在。

回答

相關問題