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.
Related
I have a problem that when I press the Fab button the app instant close and I don't know how to fix it, my goal was when pressing the fab button and inserting the data it will send the data to the MainActivity.xml and make a list of item
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Income"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expenses"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Balance"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
<ListView
android:id="#+id/listView"
app:layout_anchor="#id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp">
</ListView>
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:fabCradleMargin="10dp"
app:fabCradleVerticalOffset="10dp"
app:fabCradleRoundedCornerRadius="20dp"
android:layout_gravity="bottom">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottomNavigationView"
app:menu="#menu/bottom_nav_menu"
android:layout_marginEnd="10dp"/>
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fab"
android:src="#drawable/add_button"
app:layout_anchor="#id/bottomAppBar"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
activity_input_data.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".InputDataActivity">
<LinearLayout
android:layout_marginTop="200dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="200dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textAlignment="center"
android:textSize="50dp"
android:textStyle="bold"
android:text="Input Data"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtTitle"
android:hint="Title..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtAmount"
android:hint="Amount..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtDate"
android:hint="Date..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/addButton"
android:text="Add"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20dp">
<ImageView
android:src="#drawable/profile_button"
android:layout_width="50dp"
android:layout_height="50dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:layout_gravity="end"
android:textSize="16dp"
android:textStyle="bold"
android:text="Main Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/amount"
android:layout_gravity="end"
android:textSize="14dp"
android:textStyle="bold"
android:text="Rp. 20.000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/date"
android:layout_gravity="end"
android:textSize="12dp"
android:textStyle="bold"
android:text="23-06-2021"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/spinner"
android:layout_gravity="end"
android:textSize="14dp"
android:textStyle="bold"
android:text="Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
MyHelper myHelper;
BottomNavigationView bottomNavigationView;
FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
floatingActionButton = findViewById(R.id.fab);
//ListView Adapter
ListViewAdapter adapter = new ListViewAdapter(this, myHelper.justRefresh());
listView.setAdapter(adapter);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, InputDataActivity.class);
startActivity(intent);
}
});
//Bottom Nav
bottomNavigationView.setBackground(null);
bottomNavigationView.getMenu().getItem(2).setEnabled(false);
}
}
InputDataActivity.java
public class InputDataActivity extends AppCompatActivity {
EditText txtTitle, txtAmount,txtDate;
Button button;
Realm realm;
ListView listView;
MyHelper myHelper;
RealmChangeListener realmChangeListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_data);
realm = Realm.getDefaultInstance();
txtTitle = findViewById(R.id.txtTitle);
txtAmount = findViewById(R.id.txtAmount);
txtDate = findViewById(R.id.txtDate);
button = findViewById(R.id.addButton);
listView = findViewById(R.id.listView);
//MyHelper
myHelper = new MyHelper(realm);
myHelper.selectFromDB();
//ListView Adapter
ListViewAdapter adapter = new ListViewAdapter(this, myHelper.justRefresh());
listView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
Refresh();
}
private void saveData(){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Number maxId = realm.where(User.class).max("title_id");
int newKey = (maxId == null) ? 1 : maxId.intValue()+1;
User user = realm.createObject(User.class, newKey);
user.setTitle_name(txtTitle.getText().toString());
user.setAmount(txtAmount.getText().toString());
user.setDate(txtDate.getText().toString());
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(InputDataActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Toast.makeText(InputDataActivity.this, "Fail", Toast.LENGTH_SHORT).show();
}
});
}
private void Refresh(){
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange(Object o) {
ListViewAdapter adapter = new ListViewAdapter(InputDataActivity.this, myHelper.justRefresh());
listView.setAdapter(adapter);
}
};
realm.addChangeListener(realmChangeListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
MyHelper.java
public class MyHelper {
Realm realm;
RealmResults<User> users;
public MyHelper(Realm realm) {
this.realm = realm;
}
public void selectFromDB(){
users = realm.where(User.class).findAll();
}
public ArrayList<User> justRefresh(){
ArrayList<User> listItem = new ArrayList<>();
for(User user: users){
listItem.add(user);
}
return listItem;
}
}
User.java
public class User extends RealmObject {
#PrimaryKey
private int title_id;
private String title_name;
private String amount;
private String date;
private String spinner;
public int getTitle_id() {
return title_id;
}
public void setTitle_id(int title_id) {
this.title_id = title_id;
}
public String getTitle_name() {
return title_name;
}
public void setTitle_name(String title_name) {
this.title_name = title_name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSpinner() {
return spinner;
}
public void setSpinner(String spinner) {
this.spinner = spinner;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
Context context;
ArrayList<User> users;
public ListViewAdapter(Context context, ArrayList<User> users) {
this.context = context;
this.users = users;
}
#Override
public int getCount() {
return users.size();
}
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater =(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view =inflater.inflate(R.layout.list_item, parent,false);
TextView title,amount,date,spinner;
title =view.findViewById(R.id.title);
amount = view.findViewById(R.id.amount);
date = view.findViewById(R.id.date);
spinner = view.findViewById(R.id.spinner);
User u = (User)this.getItem(position);
title.setText(u.getTitle_name());
amount.setText(u.getAmount());
date.setText(u.getDate());
spinner.setText(u.getSpinner());
int numPosition = u.getTitle_id();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// for update
}
});
return view;
}
}
if someone can help, Thank you because I'm stuck here. my goal is to make Money Management
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
I have a search form on a fragment which works perfectly. At the moment I have a RecyclerView at the bottom of the form but I want it to load the search result on a new activity. Please help
layout.xml:
<LinearLayout 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:layout_marginTop="55dp"
android:orientation="vertical"
tools:context="com.ranake.rana.Search">
<!-- TODO: Update blank fragment layout -->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/linearLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical">
<EditText
android:id="#+id/search_field"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline2"
android:drawableLeft="#drawable/ic_make"
android:drawablePadding="10dp"
android:gravity="center_vertical"
android:hint="Make"
android:inputType="textPersonName"
android:padding="10dp"
android:textColorHint="#7f8c8d"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="7dp"
android:orientation="vertical">
<EditText
android:id="#+id/className"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline2"
android:drawableLeft="#drawable/ic_model"
android:drawablePadding="10dp"
android:gravity="center_vertical"
android:hint="Model"
android:inputType="text"
android:padding="10dp"
android:textColorHint="#7f8c8d"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/button_red_border"
android:text="Clear"
android:textColor="#color/colorPrimary" />
<Button
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="20dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/button_red"
android:text="Search"
android:textColor="#android:color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:layout_width="match_parent"
android:id="#+id/progressBar"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"></android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
Search.java:
public class Search extends Fragment {
private EditText mSearchField;
private Button mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cars");
mSearchField = (EditText) view.findViewById(R.id.search_field);
mSearchBtn = (Button) view.findViewById(R.id.search_btn);
mResultList = (RecyclerView) view.findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setNestedScrollingEnabled(false);
mResultList.setLayoutManager(new LinearLayoutManager(getContext()));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
return view;
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(getActivity(), "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Cars, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cars, UsersViewHolder>(
Cars.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Cars model, int position) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getDesc(), model.getImage(), model.getMileage(), model.getTrans(), model.getFuel(), model.getPrice(), model.getLocation());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userTitle, String userDesc, String userImage, String userMileage, String userTrans, String userFuel, String userPrice, String userLocation){
TextView user_title = (TextView) mView.findViewById(R.id.name_text);
TextView user_desc = (TextView) mView.findViewById(R.id.status_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
TextView user_mileage = (TextView) mView.findViewById(R.id.post_mileage);
TextView user_trans = (TextView) mView.findViewById(R.id.post_trans);
TextView user_fuel = (TextView) mView.findViewById(R.id.post_fuel);
TextView user_price = (TextView) mView.findViewById(R.id.post_price);
TextView user_location = (TextView) mView.findViewById(R.id.post_location);
user_title.setText(userTitle);
user_desc.setText(userDesc);
user_mileage.setText(userMileage);
user_trans.setText(userTrans);
user_fuel.setText(userFuel);
user_price.setText(userPrice);
user_location.setText(userLocation);
Glide.with(ctx).load(userImage).into(user_image);
}
}
When the search Button is clicked, I want it to open the new activity and load the results there.
You can pass this searchText to the next Activity (I'm calling it ResultsActivity) by passing it as an extra on the Intent:
private void firebaseUserSearch(String searchText) {
Intent intent = new Intent(getActivity(), ResultsActivity.class);
intent.putExtra("searchText",searchText);
startActivity(intent);
}
Then receive it on the other Activity using Intent.getExtras():
String searchText = getIntent().getExtras().getString("searchText");
And finally populate the RecyclerView from that Activity:
Query firebaseSearchQuery = mUserDatabase.orderByChild("title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Cars, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cars, UsersViewHolder>(
Cars.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Cars model, int position) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getDesc(), model.getImage(), model.getMileage(), model.getTrans(), model.getFuel(), model.getPrice(), model.getLocation());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
Error:
android.support.v7.widget.AppCompatEditText{8701551bVFED..CL.
.......484,0-747,118 #7f0b006c app:id/name_text
I am trying to set user's name information to FirebaseUser "DisplayName" during the registration. I am new to android, java and firebase. But couldn't find any solution despite my all researchs. id/name_text is the edit text which takes name from the user in registation. I thought it's a string issue, but couldn't fix.
Help. Thanks.
Here are the codes.
public class RegisterActivity extends AppCompatActivity {
#BindView(R.id.register_button) Button mRegisterButton;
#BindView(R.id.surname_edittext) EditText mSurnameEditText;
#BindView(R.id.name_text) EditText mNameEditText;
#BindView(R.id.password_edittext) EditText mPasswordEditText;
#BindView(R.id.mail_edittext) EditText mMailEditText;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ButterKnife.bind(this);
mAuth = FirebaseAuth.getInstance();
}
#OnClick(R.id.register_button)
public void register_button(View view){
RegisterUser();
}
private void RegisterUser() {
String surname = mSurnameEditText.getText().toString().trim();
String name = mNameEditText.getText().toString().trim();
String password = mPasswordEditText.getText().toString().trim();
String mail = mMailEditText.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
Toast.makeText(this, "enter the name", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(surname)) {
Toast.makeText(this, "enter the surname", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "enter the password", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(mail)) {
Toast.makeText(this, "enter the mail", Toast.LENGTH_SHORT).show();
return;
}
mAuth.createUserWithEmailAndPassword(mail,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterActivity.this,"Successfully",Toast.LENGTH_SHORT).show();
savetheinfo();
}
else{
Toast.makeText(RegisterActivity.this,"Could not registered , please try again...",Toast.LENGTH_SHORT).show();
}
}
});
}
private void savetheinfo() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(String.valueOf(mNameEditText)).build();
user.updateProfile(profileUpdates);
}
}
public class ProfileActivity extends AppCompatActivity {
#BindView(R.id.user_name) TextView mUserName;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ButterKnife.bind(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
setDataToView(user);
}
private void setDataToView(FirebaseUser user) {
mUserName.setText(user.getDisplayName());
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:text="REGISTER"
android:layout_marginBottom="50dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "/>
<EditText
android:id="#+id/name_text"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Surname: "/>
<EditText
android:id="#+id/surname_edittext"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mail: "/>
<EditText
android:id="#+id/mail_edittext"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password: "/>
<EditText
android:id="#+id/password_edittext"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:id="#+id/register_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register"
android:layout_marginTop="50dp"/>
</LinearLayout>
String.valueOf(mNameEditText) is equivalent to mNameEditText.toString() if the view is not null. You're probably looking for mNameEditText.getText().toString() which gives you the content of the EditText element.
I was able to resolve the issue as follows:
I simply used mNameEditText.getText().toString(). I forgot the .getText() in between.
I'm having a problem with integrating Facebook in my project.
I added the dependency to my build.gradle file and the imports and stuff are fine, but when I call the setReadPermissions method of the LoginButton class, I'm getting null pointer.
Here's the code I developed:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
// lang selection
lang = getIntent().getIntExtra("lang", 0);
AssetManager am = getApplicationContext().getAssets();
tf = Typeface.createFromAsset(am, "fonts/Biko_Regular.ttf");
lblNombreApp = (TextView) findViewById(R.id.lblTurismoMain);
lblNombreApp.setTypeface(tf);
btnLoginOptions = (Button) findViewById(R.id.btnOpenLoginOptions);
btnLoginOptions.setTypeface(tf);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if (AccessToken.getCurrentAccessToken() != null)
// facebook
Constantes.tipoLogin = 2;
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
// espanol
if (lang == 1) {
lblNombreApp.setText(R.string.lblTurismo);
btnLoginOptions.setText(R.string.lblLoginPopUp);
}
// ingles
else if (lang == 2) {
lblNombreApp.setText(R.string.lblTurismoEN);
btnLoginOptions.setText(R.string.lblLoginPopUpEN);
}
if (!isNetworkConnected()) {
if (lang == 1)
Toast.makeText(getApplicationContext(),
R.string.err_no_connection, Toast.LENGTH_LONG).show();
else if (lang == 2)
Toast.makeText(getApplicationContext(),
R.string.err_no_connectionEN, Toast.LENGTH_LONG).show();
finish();
}
}
I have no idea of what's going on.. Thanks in advance.
EDIT
Here is the layout.. It's a pop up, that's being shown in the main activity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/llPopUp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
tools:context=".UI.MainActivity" >
<TextView
android:id="#+id/lblLoginPopUp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/lblNoRegistradoPopUp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="7dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/btnPopupExistente"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="15dp"
android:onClick="existingUser" />
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="15dp" />
<Button
android:id="#+id/btnNewPopUp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="15dp"
android:onClick="newUser" />
</LinearLayout>
Thanks in advance.
If this is the troubling line:
loginButton = (LoginButton) findViewById(R.id.login_button);
make sure the id R.id.login_button exists in your R.layout.activity_main, e.g.:
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
Also when setting Read Permissions you'd probably want to pass a List<String> (see docs)