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
Related
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.
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
The program is supposed to run getCurrentLocation and then set the textView "coordinates" to the value of the coordinates called. That text view is part of a pager view that draws from a separate .xml file than the main layout "activity_main".
public class MainActivity extends AppCompatActivity
{
CardAdapter CardAdapter;
String coordinatesFinal;
FusedLocationProviderClient fusedLocationProviderClient;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
getCurrentLocation();
}else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);
}
setupCardItems();
ViewPager2 CardViewPager = findViewById(R.id.cardViewPager);
CardViewPager.setAdapter(CardAdapter);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
if (requestCode == 100 & grantResults.length > 0 && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED)
{
getCurrentLocation();
}else
{
Toast.makeText(getApplicationContext(), "Permission denied.",Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("MissingPermission")
public void getCurrentLocation()
{
coordinates = findViewById(R.id.coordinates);
LocationManager locationManager = (LocationManager) getSystemService
(
Context.LOCATION_SERVICE
);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(task ->
{
Location location = task.getResult();
if (location != null)
{
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
}else
{
LocationRequest locationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10000).setFastestInterval(1000).setNumUpdates(1);
LocationCallback locationCallback = new LocationCallback()
{
#Override
public void onLocationResult(LocationResult locationResult)
{
Location location1 = locationResult.getLastLocation();
coordinatesFinal = location1.getLatitude()+", "+location1.getLongitude();
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
}
});
}else
{
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
//card view
private void setupCardItems()
{
List<CardItem> CardItems = new ArrayList<>();
CardItem itemPageOne = new CardItem();
itemPageOne.setLocation("Home");
itemPageOne.setTemp("60°f");
itemPageOne.setWeatherDesc("Cloudy");
itemPageOne.setWeatherIcon(R.drawable.cloud);
itemPageOne.setHum("75%");
itemPageOne.setVis("10");
itemPageOne.setPrecip("50%");
itemPageOne.setDew("40°f");
itemPageOne.setCloud("80%");
itemPageOne.setFog("75%");
CardItem itemPageTwo = new CardItem();
itemPageTwo.setLocation("Madison");
itemPageTwo.setTemp("60°f");
itemPageTwo.setWeatherDesc("Sunny");
itemPageTwo.setWeatherIcon(R.drawable.sun);
itemPageTwo.setHum("75%");
itemPageTwo.setVis("10");
itemPageTwo.setPrecip("50%");
itemPageTwo.setDew("40°f");
itemPageTwo.setCloud("80%");
itemPageTwo.setFog("75%");
CardItem itemPageThree = new CardItem();
itemPageThree.setLocation("Milwaukee");
itemPageThree.setTemp("60°f");
itemPageThree.setWeatherDesc("Rainy");
itemPageThree.setWeatherIcon(R.drawable.rain);
itemPageThree.setHum("75%");
itemPageThree.setVis("10");
itemPageThree.setPrecip("50%");
itemPageThree.setDew("40°f");
itemPageThree.setCloud("80%");
itemPageThree.setFog("75%");
CardItems.add(itemPageOne);
CardItems.add(itemPageTwo);
CardItems.add(itemPageThree);
CardAdapter = new CardAdapter(CardItems);
}
}
I have narrowed it down to the line that doesn't work properly:
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
I have tested the exact same line as above, only using a textView from inside activity main, which works just fine. Any help is greatly appreciated.
Edit: The file actually does crash, I mistakenly said it didn't, and I added both .xml Files:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="#566D8F"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/topBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:paddingTop="15dp"
android:paddingBottom="15dp">
<ImageButton
android:id="#+id/settingsBar2"
android:layout_width="27sp"
android:layout_height="27sp"
android:layout_gravity="left"
android:layout_marginStart="20sp"
android:layout_marginEnd="70sp"
android:background="#color/background"
android:cropToPadding="true"
android:scaleType="fitCenter" />
<TextView
android:id="#+id/homeName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center_horizontal"
android:maxLines="1"
android:text="#string/app_name"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:typeface="normal" />
<ImageButton
android:id="#+id/settingsBar"
android:layout_width="27sp"
android:layout_height="27sp"
android:layout_gravity="right"
android:layout_marginStart="70sp"
android:layout_marginEnd="20sp"
android:background="#drawable/settings_handle"
android:cropToPadding="true"
android:scaleType="fitCenter" />
</LinearLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/cardViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toBottomOf="#+id/topBar" />
</androidx.constraintlayout.widget.ConstraintLayout>
item_container_card.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">
<androidx.cardview.widget.CardView
android:id="#+id/pagerCard"
android:layout_width="match_parent"
android:layout_height="440dp"
android:layout_margin="20dp"
app:cardBackgroundColor="#EAC0A0"
app:cardCornerRadius="30dp"
app:cardElevation="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/locationName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-medium"
android:gravity="center"
android:textColor="#color/white"
android:textSize="18sp" />
<TextView
android:id="#+id/coordinates"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center"
android:textColor="#color/white"
android:textSize="12sp" />
<TextView
android:id="#+id/temperature"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-black"
android:gravity="center"
android:textColor="#color/white"
android:textSize="50sp" />
<TextView
android:id="#+id/weatherDesc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:gravity="center"
android:textColor="#color/white"
android:textSize="12sp" />
<ImageView
android:id="#+id/imageOnboarding"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_margin="15dp"
android:adjustViewBounds="true"
android:contentDescription="#string/app_name" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingBottom="5sp"
android:text="Humidity"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/humVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/visibility"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingEnd="10sp"
android:paddingBottom="5sp"
android:text="Visibility"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/visVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingRight="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/precipitation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Precip. "
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/precipVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/dewPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Dew Point"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/dewVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingRight="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/cloud"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-light"
android:paddingLeft="30sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Cloud"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/cloudVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="15sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/fog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed-light"
android:paddingStart="15sp"
android:paddingTop="5sp"
android:paddingBottom="5sp"
android:text="Fog"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:id="#+id/fogVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:fontFamily="sans-serif-condensed-medium"
android:paddingStart="10sp"
android:paddingTop="5sp"
android:paddingEnd="30sp"
android:paddingBottom="5sp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</TableRow>
</TableLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Edit 2: CardAdapter.java and CardItem.java
CardAdapter.java:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.cardViewHolder>
{
private List<CardItem> CardItems;
public CardAdapter(List<CardItem> CardItems) {
this.CardItems = CardItems;
}
#NonNull
#Override
public cardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new cardViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_container_card, parent, false
)
);
}
#Override
public void onBindViewHolder(#NonNull cardViewHolder holder, int position) {
holder.setCardData(CardItems.get(position));
}
#Override
public int getItemCount() {
return CardItems.size();
}
class cardViewHolder extends RecyclerView.ViewHolder
{
private TextView locationText;
private TextView weatherDesc;
private ImageView weatherIcon;
private TextView tempVal;
private TextView humVal;
private TextView visVal;
private TextView precipVal;
private TextView dewVal;
private TextView cloudVal;
private TextView fogVal;
public cardViewHolder(#NonNull View itemView)
{
super(itemView);
locationText = itemView.findViewById(R.id.locationName);
weatherDesc = itemView.findViewById(R.id.weatherDesc);
weatherIcon = itemView.findViewById(R.id.imageOnboarding);
tempVal = itemView.findViewById(R.id.temperature);
humVal = itemView.findViewById(R.id.humVal);
visVal = itemView.findViewById(R.id.visVal);
precipVal = itemView.findViewById(R.id.precipVal);
dewVal = itemView.findViewById(R.id.dewVal);
cloudVal = itemView.findViewById(R.id.cloudVal);
fogVal = itemView.findViewById(R.id.fogVal);
}
void setCardData(CardItem CardItem)
{
locationText.setText(CardItem.getLocation());
weatherDesc.setText(CardItem.getWeatherDesc());
weatherIcon.setImageResource(CardItem.getWeatherIcon());
tempVal.setText(CardItem.getTemp());
humVal.setText(CardItem.getHum());
visVal.setText(CardItem.getVis());
precipVal.setText(CardItem.getPrecip());
dewVal.setText(CardItem.getDew());
cloudVal.setText(CardItem.getCloud());
fogVal.setText(CardItem.getFog());
}
}
}
CardItem.java:
package com.example.viewpagertest;
public class CardItem
{
private int weatherIcon;
private String location;
private String temp;
private String weatherDesc;
private String hum;
private String vis;
private String precip;
private String dew;
private String cloud;
private String fog;
//weather icon
public int getWeatherIcon() {
return weatherIcon;
}
public void setWeatherIcon(int weatherIcon) {
this.weatherIcon = weatherIcon;
}
//location title
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
//temperature value
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
//weather description
public String getWeatherDesc() {
return weatherDesc;
}
public void setWeatherDesc(String weatherDesc) {
this.weatherDesc = weatherDesc;
}
//humidity value
public String getHum() {
return hum;
}
public void setHum(String hum) {
this.hum = hum;
}
//visibility value
public String getVis() {
return vis;
}
public void setVis(String vis) {
this.vis = vis;
}
//precipitation value
public String getPrecip() {
return precip;
}
public void setPrecip(String precip) {
this.precip = precip;
}
//dew point value
public String getDew() {
return dew;
}
public void setDew(String dew) {
this.dew = dew;
}
//cloud value
public String getCloud() {
return cloud;
}
public void setCloud(String cloud) {
this.cloud = cloud;
}
//fog value
public String getFog() {
return fog;
}
public void setFog(String fog) {
this.fog = fog;
}
}
Here's the Console when running a debugger with the breakpoint at
coordinates.setText(location.getLatitude()+", "+location.getLongitude());
The whole console breaks the character limit so here's a document with the console text.
Console Text
if (location != null)
{
// coordinates.setText(location.getLatitude()+", "+location.getLongitude());
cardAdapter.setCoordinates(0 /*the cardItem number you want to update*/, location.getLatitude()+", "+location.getLongitude());
}
Since the coordinates TextView is in your item xml, you will not be able to address it from the root of your MainActivity, but from your item.
Update
Thanks for adding the Adapter code:
Easiest would be to create a method in your adapter like the following:
setCoordinates(int position, String coords) {
holders.get(position).itemView.findViewById(R.id.coordinates).setText(coords);
}
To be able to access the holders on runtime, add the following:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.cardViewHolder>
{
private List<CardItem> cardItems;
private List<CardViewHolder> holders;
....
#Override
public cardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
CardViewHolder holder = new cardViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_container_card, parent, false
)
);
holders.add(holder);
return holder;
}
Another option would be to add the field coordinates to your CardItem and write the setCoordinates method like so:
setCoordinates(int position, String coords) {
cardItems.get(position).setCoordinates(coords);
notifyDataSetChanged(); // to reload the holders, only notifying the specific position will be faster to reload only the changed holder
}
You need to update the adapter items by creating a method in CardAdapter and calling it from main activity as below -
Create this method in your adapter class
public void updateAdapter(List<CardItem> CardItems) {
this.CardItems = CardItems;
notifyDataSetChanged();
}
Replace below line
CardAdapter = new CardAdapter(CardItems);
With this one
CardAdapter.updateAdapter(CardItems);
I tried to retrive images from firebase with correct url link. The RecyclerView keep shown "first" info of Food which is cookie-milk-cup:
This is my firebase data structure:
all_uploaded_image //directory
|-cookie milk cup
|-description: "yes!" //shown successful
|-image_uri: "content://com.android.providers.media.documents..." //no necessary in this case
|-name: "cookie milk cup" //shown successful
|-price: "1.20" //not shown
|-uploader_uid: "GSsY4tEo5ZZpS8kkJEpWGLCbFmC3" //no necessary in this case
fish n chips //recursive only on cookie milk cup, so nothing appear in here
|-description: "delicious fc"
|-image_uri: "content://com.android.providers.media.documents..."
|-name: "fish n chips"
|-price: "1.20"
|-uploader_uid: "GSsY4tEo5ZZpS8kkJEpWGLCbFmC3"
I am using android with java, want to get the info from firebase using fragment.
This is the AllFOodFragment.java
public class AllFoodFragment extends Fragment {
private View contactsView;
private ArrayList<Food> entries;
private DatabaseReference ref;
private FirebaseDatabase dbr;
private FoodAdapter adapter;
private RecyclerView recycler_view;
public AllFoodFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contactsView = inflater.inflate(R.layout.home_main, container, false); //v
recycler_view = (RecyclerView) contactsView.findViewById(R.id.recycler_view);
recycler_view.setHasFixedSize(true);
recycler_view.setItemAnimator(new DefaultItemAnimator());
final FragmentActivity ga = getActivity(); //2a
LinearLayoutManager lm = new LinearLayoutManager(ga); //2
recycler_view.setLayoutManager(lm);
entries = new ArrayList<Food>();
ref = FirebaseDatabase.getInstance().getReference().child("all_uploaded_image");
ref.addChildEventListener(new ChildEventListener(){
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot ds: dataSnapshot.getChildren()) {
//Log.e("Count " ,"" + dataSnapshot.getChildrenCount());
Food data = dataSnapshot.getValue(Food.class);
//data.setPrice(dataSnapshot.child("price").getValue().toString());
//data.setImageUrl(dataSnapshot.child("image_uri").getValue().toString());
entries.add(data);
//Log.e("Get All Description", data.get_price());
}
adapter = new FoodAdapter(getActivity(), entries);
adapter.notifyDataSetChanged();
adapter.setListFood(entries);
//3; No adapter attached in here, but program runs
recycler_view.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return contactsView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onViewCreated(View view, #Nullable Bundle savedUbstabceState){
super.onViewCreated(view, savedUbstabceState);
this.contactsView = view;
}
}
And, this is FoodAdapter.java
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {
private Context m_context;
private ArrayList<Food> m_listFood = new ArrayList<Food>();
public FoodAdapter(Context context, ArrayList<Food> food_list) {//m_context, food_list
this.m_context = context;
this.m_listFood = food_list;
}
#NonNull
#Override
public FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fragment_all_food, parent, false);
return new FoodViewHolder(v);
}
public class FoodViewHolder extends RecyclerView.ViewHolder{
public ImageView FoodIcon;
public TextView FoodName;
public TextView FoodDescription;
public TextView FoodPrice;
public Button Fooddetail;
public FoodViewHolder (View itemView){
super(itemView);
FoodIcon = (ImageView)itemView.findViewById(R.id.thumbnail); //icon
FoodName = itemView.findViewById(R.id.foodname);
FoodDescription = itemView.findViewById(R.id.fooddescription);
FoodPrice = itemView.findViewById(R.id.foodprice);
Fooddetail = itemView.findViewById(R.id.fooddetail);
}
public void onClick(View view) {
}
}
#Override
public void onBindViewHolder(#NonNull FoodViewHolder holder, int position) {
Food f = m_listFood.get(position);
holder.FoodName.setText(f.get_name());
holder.FoodDescription.setText(f.get_description());
holder.FoodPrice.setText(f.get_price());
holder.FoodPrice.setText(f.get_url());
//Picasso.get().load(m_listFood.get(position).get_url()).fit().into(holder.FoodIcon);
Glide.with(m_context).load(f.get_url()).into(holder.FoodIcon); //getListFood().get(position).get_icon()
}
#Override
public int getItemCount() {
return m_listFood.size();
}
public Context get_context() {
return m_context;
}
public void setListFood(ArrayList<Food> m_listFood){
this.m_listFood = m_listFood;
}
}
this is item_fragment_all_food.xml
<?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:layout_width="match_parent" android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView //icon not shown, white
android:id="#+id/thumbnail"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/star_big_on" />
<TextView
android:id="#+id/foodname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="191dp"
android:layout_marginTop="16dp"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/fooddescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/foodname"
android:layout_marginEnd="86dp"
android:layout_marginBottom="-91dp"
android:text="Description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/foodname" />
<TextView
android:id="#+id/foodprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="85dp"
android:layout_marginEnd="95dp"
android:text="Price"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.487"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/fooddescription"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/fooddetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginEnd="79dp"
android:layout_marginBottom="16dp"
android:background="#color/colorPrimary"
android:text="Detail"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/foodprice"
app:layout_constraintVertical_bias="0.0" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And, this is 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.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:autofillHints="email"
android:layout_margin="15dp"
android:inputType="textEmailAddress"
android:hint="Enter Email"
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_margin="15dp"
android:inputType="textPassword"
android:hint="Enter Password"
android:id="#+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_margin="15dp"
android:hint="Register"
android:id="#+id/btn_register"
android:layout_width="match_parent"
android:onClick="click_to_register_new_user"
android:layout_height="wrap_content" />
<Button
android:layout_margin="15dp"
android:hint="Login"
android:id="#+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="137dp"
android:text="#string/reset_string" />
</RelativeLayout>
Lastly, my Food Model
public class Food {
public String name;
public String description;
public String price;
public String img_url;
public String icon;
public Food() {
//empty
}
public Food(String name, String description, String price, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
this.name = name;
this.description = description;
this.price = price;
this.img_url = imageUrl;
}
public String get_name() {
return name;
}
public String get_description() {
return description;
}
public String get_price() {
return price;
}
public String get_icon() {
return icon;
}
public String get_url() {
return img_url;
}
public void setPrice(String price) {
this.price = price;
}
public void setImageUrl(String imageUrl) {
img_url = imageUrl;
}
public void set_icon(String icon) {
this.icon = icon;
}
}
The error I get is E/RecyclerView: No adapter attached; skipping layout
and No setter/field for image_uri found on class com.example.hungrystomach.Model.Food [but really I do not want image_uri shown in my recyclerview so I skip the TextView]
The recyclerView does not have any Image shown even I've FoodIcon with thumbnail in FOodAdaper.java. I've tried for three weeks already still no hope. I suppose to get all the info I need. I know it is little bit long but any suggestion and answer would appreciate.
It is allowing me to login through Gmail and its showing display picture, my name etc. but its not working with other random people's id.
I've added more owners on developer.google.com and its also allowing them but not me.
public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener{
private LinearLayout Prof_Section;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Pic;
private GoogleApiClient googleApiClient;
private static final int REQ_CODE=9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Prof_Section = (LinearLayout)findViewById(R.id.Prof_Section);
SignOut = (Button)findViewById(R.id.bn_logout);
SignIn = (SignInButton)findViewById(R.id.bn_login);
Name=(TextView)findViewById(R.id.name);
Email=(TextView)findViewById(R.id.email);
Prof_Pic=(ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,signInOptions).build();
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.bn_login:
signIn();
break;
case R.id.bn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn()
{
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent,REQ_CODE);
}
private void signOut()
{
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void handleResult(GoogleSignInResult result)
{if(result.isSuccess())
{
GoogleSignInAccount account = result.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
// Glide.with(this).load(img_url).into(Prof_Pic);
// Glide.with(this)
// .load(img_url)
// // .override(300, 200)
// .into(Prof_Pic);
// Glide.with(this).load(img_url).into(Prof_pic);
updateUI(true);
}
else
{updateUI(false);}
}
private void updateUI(boolean isLogin){
if(isLogin){
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility((View.GONE));
}
else
{
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==REQ_CODE)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
}
}
<?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="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/Prof_Section"
android:layout_width="match_parent"
android:layout_height="176dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="113dp"
android:layout_height="match_parent"
android:src="#drawable/myalpha"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="37dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Name display here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Email display here"
android:textSize="12dp"
android:textStyle="bold" />
<Button
android:id="#+id/bn_logout"
android:layout_width="match_parent"
android:layout_height="61dp"
android:text="Logout Google Account" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:id="#+id/bn_login"
>
</com.google.android.gms.common.SignInButton>
</LinearLayout>
Its logging me and showing me my details but not others people details.
I want that if they try to login, they also get there details
SignInButton Signin = findViewById(R.id.);
findViewById(R.id.bn_login).setOnClickListener(this);
findViewById(R.id.bn_login).setVisibility(View.GONE);