I can't connect layouts .They are not displaying in Android Studio - java

I am new in Android Studio.I want to connect layouts.But when I execute the project and select the profile page it does't display in Android Studio .I am not taking any error or warning when I execute the project.
It is the layout that I want to connect
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/graylight"
android:orientation="vertical"
tools:context=".Profile">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/gradientbackground"
android:orientation="vertical">
<ImageView
android:id="#+id/profilePhoto"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_margin="25dp"
android:contentDescription="#string/todo"
android:onClick="chooseImage"
android:src="#drawable/ic_account_circle_black_24dp"
tools:ignore="OnClick" />
<EditText
android:id="#+id/nameText"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="#string/enter_your_name"
android:textColor="#fff"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="45dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="20dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:contentDescription="#string/todo"
android:src="#drawable/email" />
<EditText
android:id="#+id/emailText"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:hint="#string/enter_your_email"
android:inputType="textEmailAddress"
android:paddingStart="20dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="45dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="20dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:contentDescription="#string/todo"
android:src="#drawable/phone" />
<EditText
android:id="#+id/phoneText"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:hint="#string/enter_your_phone"
android:inputType="phone"
android:paddingStart="20dp" />
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#drawable/buttonstyle"
android:onClick="save"
android:text="#string/save"
tools:ignore="OnClick" />
public class profile_info extends ArrayAdapter<String> {
private final ArrayList<String> userName;
private final ArrayList<String> userEmail;
private final ArrayList<String> UserPhone;
private final ArrayList<String> userProfileImage;
private final Activity context;
public profile_info(ArrayList<String> userName, ArrayList<String> userEmail,
ArrayList<String> userPhone, ArrayList<String> userProfileImage, Activity
context) {
super(context,R.layout.custom_profileinfo,userEmail);
this.userName = userName;
this.userEmail = userEmail;
UserPhone = userPhone;
this.userProfileImage = userProfileImage;
this.context = context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
LayoutInflater layoutInflater =context.getLayoutInflater();
View profileinfo
=layoutInflater.inflate(R.layout.custom_profileinfo,null,true);
EditText userNametext =profileinfo.findViewById(R.id.nameText);
EditText userEmailtext =profileinfo.findViewById(R.id.emailText);
EditText userPhonetext =profileinfo.findViewById(R.id.phoneText);
ImageView userImage = profileinfo.findViewById(R.id.profilePhoto);
userNametext.setText(userName.get(position));
userEmailtext.setText(userEmail.get(position));
userPhonetext.setText(UserPhone.get(position));
Picasso.with(context).load(userProfileImage.get(position)).into(userImage);
return profileinfo;
}
}
I want to connect custom_profileinfo to activity_profile
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.cat.haberuygulamasi.Profile">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class Profile extends AppCompatActivity {
ArrayList<String> userEmailFromFB;
ArrayList<String> userImageFromFB;
ArrayList<String> userNameFromFB;
ArrayList<String> userPhoneFromFB;
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
private FirebaseAuth mAuth;
private StorageReference mStorageRef;
Uri selected;
profile_info adapter;
ListView listView;
EditText userName;
EditText userEmail;
EditText userPhone;
ImageView userImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
userName = findViewById(R.id.nameText);
userEmail = findViewById(R.id.emailText);
userPhone = findViewById(R.id.phoneText);
userImage = findViewById(R.id.profilePhoto);
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = firebaseDatabase.getReference();
mAuth= FirebaseAuth.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference();
userEmailFromFB = new ArrayList<>();
userImageFromFB = new ArrayList<>();
userNameFromFB = new ArrayList<>();
userPhoneFromFB = new ArrayList<>();
adapter = new profile_info(userImageFromFB,userNameFromFB,userEmailFromFB,userPhoneFromFB,this);
listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
getDataFromFirebase();
}
public void save (View view){
UUID uuidImage1 = UUID.randomUUID();
String imageName ="profilePhoto/"+uuidImage1+".jpg";
StorageReference storageReference1 = mStorageRef.child(imageName);
storageReference1.putFile(selected).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadURLL = taskSnapshot.getDownloadUrl().toString();
FirebaseUser user = mAuth.getCurrentUser();
String userEmail2 = user.getEmail().toString();
String userName2 = userName.getText().toString();
String userPhone2 = userPhone.getText().toString();
UUID uuid1=UUID.randomUUID();
String uudString1 =uuid1.toString();
myRef.child("Profile").child("useremail").setValue(userEmail2);
myRef.child("Profile").child("username").setValue(userName2);
myRef.child("Profile").child("phone").setValue(userPhone2);
myRef.child("Profile").child("downloadurl").setValue(downloadURLL);
Toast.makeText(Profile.this, "İnformation Saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void getDataFromFirebase() {
DatabaseReference newReference = firebaseDatabase.getReference("Profile");
newReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
HashMap<String,String> hashMap = (HashMap<String,String>) ds.getValue();
userImageFromFB.add(hashMap.get("downloadurl"));
userEmailFromFB.add(hashMap.get("useremail"));
userNameFromFB.add(hashMap.get("username"));
userPhoneFromFB.add(hashMap.get("phone"));
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void chooseImage(View view){
if(checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE},1);
}else{
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,2);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 1){
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,2);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

Related

Not able to send Image in chat Application

I tried to share the image in the chat app.But was not able to successfully share it.
It's selecting the image from the gallery but not appearing in the chat and not getting saved in the firebase also. Below is my Chat.xml file and UserChat.java file.
I am not able to find the solution for it.
//XML Code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity.UserChatActivity">
<LinearLayout
android:id="#+id/dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_margin="20sp"
android:src="#drawable/user"
app:civ_border_color="#D21CB4F5"
app:civ_border_width="2dp" />
<TextView
android:id="#+id/receivername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:gravity="center"
android:layout_margin="10sp"
android:textColor="#color/black"
android:textSize="20dp"
android:textStyle="bold"
android:fontFamily="sans-serif-medium"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/messageAdapter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/mesbox"
android:layout_below="#+id/dp" />
<LinearLayout
android:id="#+id/mesbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_margin="2dp">
<androidx.cardview.widget.CardView
android:id="#+id/attachment"
android:layout_width="35dp"
android:layout_height="35dp"
app:cardCornerRadius="540dp"
android:layout_margin="3dp"
app:cardBackgroundColor="#0381C5">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="center"
android:background="#drawable/clip"/>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="35dp"
app:cardCornerRadius="540dp"
android:layout_margin="3dp"
app:cardBackgroundColor="#431CB4F5">
<EditText
android:id="#+id/editmessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:fontFamily="sans-serif-light"
android:background="#null"
android:layout_gravity="center_vertical"/>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="#+id/sendbutton"
android:layout_width="35dp"
android:layout_height="35dp"
app:cardCornerRadius="540dp"
android:layout_margin="3dp"
app:cardBackgroundColor="#0381C5">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="center"
android:background="#drawable/send"/>
</androidx.cardview.widget.CardView>
</LinearLayout>
// JAVA code
package com.example.chatapp.Activity;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserChatActivity extends AppCompatActivity {
String ReceiverImage;
String ReceiverUID;
String ReceiverName;
String SenderUID;
String senderRoom;
String receiverRoom;
public static String sImage;
public static String rImage;
CircleImageView profile_image;
TextView receivername;
CardView attachment;
EditText editmessage;
CardView sendbutton;
FirebaseAuth fAuth;
FirebaseDatabase database;
RecyclerView messageAdapter;
ArrayList<Messages> messagesArrayList;
MessagesAdapter adapter;
private String checker = "", myURL = "";
private StorageTask uploadTask;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_user_chat);
fAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
ReceiverImage = getIntent().getStringExtra("ReceiverImage");
ReceiverName = getIntent().getStringExtra("name");
ReceiverUID = getIntent().getStringExtra("uid");
messagesArrayList = new ArrayList<>();
profile_image = findViewById(R.id.profile_image);
receivername = findViewById(R.id.receivername);
messageAdapter = findViewById(R.id.messageAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
messageAdapter.setLayoutManager(linearLayoutManager);
adapter = new MessagesAdapter(UserChatActivity.this, messagesArrayList);
messageAdapter.setAdapter(adapter);
attachment = findViewById(R.id.attachment);
editmessage = findViewById(R.id.editmessage);
sendbutton = findViewById(R.id.sendbutton);
Picasso.get().load(ReceiverImage).into(profile_image);
receivername.setText("" + ReceiverName);
SenderUID = fAuth.getUid();
senderRoom = SenderUID + ReceiverUID;
receiverRoom = ReceiverUID + SenderUID;
DatabaseReference reference = database.getReference().child("user").child(fAuth.getUid());
DatabaseReference chatReference = database.getReference().child("chats").child(senderRoom).child("messages");
chatReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messagesArrayList.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Messages messages = dataSnapshot.getValue(Messages.class);
messagesArrayList.add(messages);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
sImage = snapshot.child("imageUri").getValue().toString();
rImage = ReceiverImage;
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]
{
"Image", "Documents"
};
AlertDialog.Builder builder = new AlertDialog.Builder(UserChatActivity.this);
builder.setTitle("Select File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0)
{
checker = "image";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 438);
}
if (i == 1)
{
checker = "pdf";
}
}
});
builder.show();
}
});
sendbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = editmessage.getText().toString();
if (message.isEmpty()) {
Toast.makeText(UserChatActivity.this, "Insert Message", Toast.LENGTH_SHORT).show();
return;
}
editmessage.setText("");
Date date = new Date();
Messages messages = new Messages(message, SenderUID, date.getTime());
database.getReference().child("chats")
.child(senderRoom)
.child("messages")
.push()
.setValue(messages).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
database.getReference().child("chats")
.child(receiverRoom)
.child("messages")
.push()
.setValue(messages).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && requestCode == RESULT_OK && data != null && data.getData() != null)
{
fileUri = data.getData();
if (!checker.equals("image"))
{
}
else if (checker.equals("image"))
{
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files").child(fAuth.getUid());;
}
else
{
Toast.makeText(this, "Nothing Selected", Toast.LENGTH_SHORT).show();
}
}
}
}
Please someone help me to solve it.

Messages are not showing, Firebase Chat

After message sending it isn't showing. But I'm receiving the message in Firebase Database. What's wrong with it? Have you any suggestions?
MainActivity.class
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
FirebaseUser currentUser;
private FirebaseListAdapter<ChatMessage> adapter;
private final static String TAG = "LOG";
EditText input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
checkAuth();
input = (EditText)findViewById(R.id.input);
FloatingActionButton fab =
(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().equals(null) && input.getText().toString().equals("")) {
Log.i(TAG, "Mesage is empty");
} else {
// Read the input field and push a new instance
// of ChatMessage to the Firebase database
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance()
.getCurrentUser()
.getDisplayName())
);
displayChatMessages();
// Clear the input
input.setText("");
}
}
});
}
private void displayChatMessages() {
ListView listOfMessages = (ListView) findViewById(R.id.list_of_messages);
//Suppose you want to retrieve "chats" in your Firebase DB:
Query query = FirebaseDatabase.getInstance().getReference();
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions.Builder<ChatMessage>()
.setQuery(query, ChatMessage.class)
.setLayout(R.layout.message)
.build();
//Finally you pass them to the constructor here:
adapter = new FirebaseListAdapter<ChatMessage>(options){
#Override
protected void populateView(View v, ChatMessage model, int position) {
// Get references to the views of message.xml
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
TextView messageTime = (TextView) v.findViewById(R.id.message_time);
// Set their text
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
Log.i(TAG, model.getMessageUser() + ": " + model.getMessageText());
// Format the date before showing it
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)",
model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
public void checkAuth(){
// Check if user is signed in (non-null) and update UI accordingly.
currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
displayChatMessages();
///
} else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
}
#Override
public void onStart() {
super.onStart();
checkAuth();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#id/fab"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/fab">
<EditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:tint="#android:color/white"
app:fabSize="mini"
app:layout_constraintStart_toStartOf="#+id/textInputLayout"
/>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="16dp"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
message.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/message_user"
android:layout_alignParentEnd="true"
android:id="#+id/message_time" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/message_user"
android:layout_alignParentStart="true"
android:layout_marginTop="5dp"
android:id="#+id/message_text"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textSize="18sp" />
By the way, it's not a good solution to obey type more text.
It looks like your post is mostly code; please add some more details.

How to make messages appear on different sides?

I make a chat app using a video tutorial, but this tutorial does not show how to make messages from different people appear on different sides. The sender and receiver see all messages on the left. Could you please give some advices on this? Thanks in advance.
Now it looks like this
Main code
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_CODE=1;
private RelativeLayout activity_main;
private FirebaseListAdapter<Message> adapter;
private FloatingActionButton sendBtn;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SIGN_IN_CODE) {
if(requestCode == RESULT_OK) {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
} else {
Snackbar.make(activity_main, "You are not authorized", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main=findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.btnSend);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText textField = findViewById(R.id.messageField);
if(textField.getText().toString().equals(""))
return;
FirebaseDatabase.getInstance().getReference().push().setValue(
new Message(
FirebaseAuth.getInstance().getCurrentUser().getEmail(),
textField.getText().toString()));
textField.setText("");
}
});
//Пользователь ещё не авторизован
if (FirebaseAuth.getInstance().getCurrentUser()==null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
//Пользователь авторизован
else {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
private void displayAllMessages() {
ListView listOfMessages = findViewById(R.id.list_of_messages);
FirebaseListOptions<Message> options =
new FirebaseListOptions.Builder<Message>()
.setQuery(FirebaseDatabase.getInstance().getReference(), Message.class)
.setLayout(R.layout.list_item)
.build();
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Message Class
public class Message {
private String UserName;
private String TextMessage;
private long MessageTime;
public Message() {}
public Message (String UserName, String TextMessage){
this.UserName = UserName;
this.TextMessage = TextMessage;
this.MessageTime = new Date().getTime();
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getTextMessage() {
return TextMessage;
}
public void setTextMessage(String textMessage) {
TextMessage = textMessage;
}
public long getMessageTime() {
return MessageTime;
}
public void setMessageTime(long messageTime) {
MessageTime = messageTime;
}
}
Main XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/activity_main">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send_button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
app:fabSize="normal">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#id/btnSend"
>
<EditText
android:id="#+id/messageField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" Message..."
/>
</com.google.android.material.textfield.TextInputLayout>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/text_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
XML for the message bubbles
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Try adding layout_gravity attribute in your BubbleTextView when you need this like this:
android:layout_gravity="right"
Every user will have a unique email - Let say here in the example - d#mail.ru is your email. You need to add user logic to dynamically check to decide whether you want a bubble test layout to be LEFT or RIGHT.
Update the message bubble layout.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Adapter code:- you can update as you need either LEFT or RIGHT.
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
RelativeLayout Layout = v.findViewById(R.id.parentlayout);
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
if(!model.getUserName().equals("d#mail.ru")) {
mess_text.setGravity(Gravity.LEFT)
} else {
mess_text.setGravity(Gravity.RIGHT)
}
}
};
Check this link as a reference - https://github.com/rpadma/Trip-Planner/blob/master/app/src/main/java/com/etuloser/padma/rohit/homework09a/ChatAdapter.java

How to show the time when an item in a recyclerview was created?

I want to make this:
I have a RecyclerView, wherein for each item I create I want to show the time when the item was created. I want to display the time within this item.
My code:
public class VerIncidencia extends AppCompatActivity {
private FirebaseRecyclerAdapter mAdapter;
private DatabaseReference mDatabase;
String idIncidencia;
String idEmpresa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_incidencia);
String uid = FirebaseAuth.getInstance().getUid();
idIncidencia = getIntent().getStringExtra("INCIDENCIA_KEY");
idEmpresa = getIntent().getStringExtra("EMPRESA_KEY");
mDatabase = FirebaseDatabase.getInstance().getReference().child("incidencia").child(uid);
RecyclerView recyclerView = findViewById(R.id.list_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Query postsQuery = mDatabase;
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Incidencia>()
.setQuery(postsQuery, Incidencia.class)
.setLifecycleOwner(this)
.build();
mAdapter = new FirebaseRecyclerAdapter<Incidencia, IncidenciaViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull IncidenciaViewHolder holder, final int position, #NonNull final Incidencia empresa) {
holder.departamento.setText(empresa.departamento);
holder.prioridad.setText(empresa.prioridad);
holder.motivo.setText(empresa.motivo);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(VerIncidencia.this, VerIncidenciaCompleta.class);
intent.putExtra("INCIDENCIA_KEY", getRef(position).getKey());
startActivity(intent);
}
});
}
#Override
public IncidenciaViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_incidencia, parent, false);
return new IncidenciaViewHolder(view);
}
};
recyclerView.setAdapter(mAdapter);
}
}
ViewHolder:
public class IncidenciaViewHolder extends RecyclerView.ViewHolder{
TextView departamento;
TextView prioridad;
TextView motivo;
public IncidenciaViewHolder(View itemView) {
super(itemView);
departamento = itemView.findViewById(R.id.departamento);
prioridad = itemView.findViewById(R.id.prioridad);
motivo = itemView.findViewById(R.id.motivo);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/departamento"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="-40dp"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/prioridad"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="30dp"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/motivo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="85dp"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>

Attempt to invoke virtual method `MaterialEditText.getText()' on a null object reference

public class MainActivity extends AppCompatActivity {
MaterialEditText edtNewUser, edtNewPassword, edtNewEmail; //pentru Sign up
MaterialEditText edtUser, edtPassword, edtEmail; //pentru Sign in
Button btnSignUp, btnSignIn;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Firebase
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn = (Button)findViewById(R.id.btn_sign_in);
btnSignUp = (Button)findViewById(R.id.btn_sign_up);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user).exists()){
if(!user.isEmpty()){
User login = dataSnapshot.child(user).getValue(User.class);
if(login.getPassword().equals(pwd))
Toast.makeText(MainActivity.this, "Login ok!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Parola incorecta!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Va rog introduceti username!", Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(MainActivity.this, "Username-ul nu exista!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign up");
alertDialog.setMessage("Introduceti informatiile necesare");
LayoutInflater inflater = this.getLayoutInflater();
View sign_up_layout = inflater.inflate(R.layout.sign_up_layout,null);
edtNewUser = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewUserName);
edtNewEmail = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewEmail);
edtNewPassword = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewPassword);
alertDialog.setView(sign_up_layout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user = new User(edtNewUser.getText().toString(),
edtNewPassword.getText().toString(),
edtNewEmail.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getUserName()).exists())
Toast.makeText(MainActivity.this, "User-ul exista deja!",Toast.LENGTH_SHORT).show();
else{
users.child(user.getUserName()).setValue(user);
Toast.makeText(MainActivity.this, "Inregistrat cu success!",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
XML file
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/info_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardElevation="4dp"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewUserName"
android:hint="Username"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewPassword"
android:hint="Password"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_below="#id/info_login"
android:orientation="horizontal"
android:weightSum="2"
android:layout_margin="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#id/btn_sign_up"
android:text="Sign up"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="#id/btn_sign_in"
android:text="Sign in"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Please help me! I've tried anything I knew but nothing works
The program I work in is ANDROID STUDIO. I need to solve this to finish my app.
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
This is the line that gives me ERROR. If I comment this line the app works properly but I need it for the rest of the app.
Your edtUser MaterialEditText and edtPassword are not present in your xml file, you have to change the ids in xml file to match the Activity ids, or remplace
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
by :
edtUser = (MaterialEditText)findViewById(R.id.edtNewUserName);
edtPassword = (MaterialEditText)findViewById(R.id.edtNewPassword);

Categories