Update a RecyclerView from another class - android

I will try to be brief:
I have three classes that have to interact in this:
The server, which receives the message (in a thread).
The contact, which stores messages in its class (in each object).
The chat activity belonging to each user, which has to show the
messages of the corresponding object, the idea is that it is a RecyclerView.(an activity)
The server receives a message, this message would be added to the chat of the specific contact and then the RecyclerView must be updated.
This is the basic Contact class code:
public class Contact implements Serializable {
private String name;
private String ip;
//Here would be a variable that contains the chat strings
public Contact (String name, String ip){
this.name = name;
this.ip = ip;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
And then there is the activity of the chat that is launched when selecting a specific user and it contains a RecyclerView where I want the messages to be.
My problem is that, how to make the messages that are stored in the
variable of a specific object appear in the list.
From already thank you very much.

you can use data class instead of serialization
public class Data {
private String text;
private String uid;
private String tnviews;
private String numberlikes;
public Data(String text,String tnviews,String numberlikes,String uid) {
this.text = text;
this.tnviews = tnviews;
this.numberlikes = numberlikes;
this.uid = uid;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
/////////// VIEWS
public String getViews() {
return tnviews;
}
public void setViews(String tnviews) {
this.tnviews = tnviews;
}
//////// likes
public String getLikes() {
return numberlikes;
}
public void setLikes(String numberlikes) {
this.numberlikes = numberlikes;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}

you can Update RecyclerView Adapter Data
mAdapter.notifyDataSetChanged();
Reference link

Related

unable to retrieve data from one app to another app from firebase single Database

I have 2 applications(different package names) which use one Firebase database. One app has to write access to the database and another have read access to the database.in my second application, i use recyclerview to retrieve data which is stored by 1st App.
for this I use below code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:567....259c8f58311") // Required for Analytics.
.setApiKey("AIzaSyA9BRxl......hE03y5qD-c") // Required for Auth.
.setDatabaseUrl("https://mycity-3a561.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
DatabaseReference data = secondaryDatabase.getInstance().getReference();
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
WaterClass waterClass = dSnapshot.getValue(WaterClass.class);
Log.d("Show", waterClass.getName() == null ? "" : waterClass.getName());
list.add(waterClass);
}
adapter = new WaterAdapter(ShowWaterDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
Adapter class
private class WaterAdapter extends RecyclerView.Adapter<WaterAdapter.ViewHolder> {
ShowWaterDetails showDetail;
List<WaterClass> listData;
public WaterAdapter(ShowWaterDetails showWaterDetails, List<WaterClass> list) {
this.showDetail = showWaterDetails;
this.listData = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
WaterAdapter.ViewHolder viewHolder = new WaterAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(WaterAdapter.ViewHolder holder, int position) {
WaterClass AllDetails = listData.get(position);
holder.NameTextView.setText(AllDetails.getName());
holder.DetailTextView.setText(AllDetails.getDetail());
holder.DateTextView.setText(AllDetails.getDate());
holder.LocationTextView.setText(AllDetails.getLocation());
holder.TypeTextView.setText(AllDetails.getType());
Picasso.with(showDetail).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
}
#Override
public int getItemCount() {
return listData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
}
POJO Class
class WaterClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public WaterClass(){
}
public WaterClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString) {
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
:
there is no error but my recycler not showing anything
go to onStart() and start listening
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
and in your onStop
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
The FirebaseRecyclerAdapter uses a snapshot listener to monitor changes to the Firestore query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
Be sure that the names of constant in the POJO match exatly the names
of your database structure in your firebase console !!
ps: do not post your api-keys or app-ids in your questions, keep them secret, and consider using firebaserecycleradapter if you are using firebase-database , it will be more easy to setup and to show values.
Your POJO is ok !
Found Solution!!
just change this part of a code
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
TO
FirebaseApp.initializeApp(this);
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");

Android Studio displaying FirebaseListAdapter change codes

i have a FirebaseListAdapter which retrieves all the uid from the user but i want it to retrieve the names instead.
i have two child. one is to store all the uid of the connected users for a chat, and the other contains their information such as names. how do i convert the retrieved values (uid) into names and display it as shown below.
i have attached a snippet of how my app looks like currently and i want it to show names instead of uid.
FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(getActivity(), String.class, R.layout.fragment_chatfprow, mDatabase) {
#Override
protected void populateView(View v, String model, int position) {
TextView text = v.findViewById(R.id.text1);
text.setText(model);
}
};
i think there is something to do with these lines of code but i cant figure out how.
This is how my Firebase ListView looks like
You need a model class for Firebase UI Database with an empty constructor for example:
public class Users {
private String mName;
private String mMessage;
public Users() {} // Required for Firebase
public Users(String name, String message) {
mName = name;
mMessage = message;
}
public String getName() { return mName; }
public void setName(String name) { mName = name; }
public String getMessage() { return mMessage; }
public void setMessage(String message) { mMessage = message; }
}
Then in Adapter creation you can do like this:
FirebaseListAdapter<Users> firebaseListAdapter = new FirebaseListAdapter<Users>(getActivity(), Users.class, R.layout.fragment_chatfprow, mDatabase) {
#Override
protected void populateView(View v, String model, int position) {
TextView text = v.findViewById(R.id.text1);
text.setText(model.getName());
}
};
You can take a look here from more informations: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md

Access string from another class

I have different packages in my app like this.
CansTypeObject class looks like this
public class CansTypeObject {
String productId;
String productName;
String productPrice;
String productReturnPrice;
String productImage;
}
Now, I want to access these strings from MainActivity
CansTypeObject object = new CansTypeObject();
But I cant. If I move the CansTypeObject class to the same package as that of MainActivity, I can access them. What is the solution for this?
The default scope is package-private. Use the public modifier on the String declaration
public String productId;
The only reason of this behavior is that you declared yours class Strings as package-protected strings. In Java this means, that this fields will be accessible only for classes in the same package.
There are several solutions for your problem.
The first (and the worst) - declare your fields as public strings, like this:
public String myField;
The second - create getters for your fields and declare your strings as private fields, like this:
private String myField;
public String getMyField() {
return myField;
}
Then, use this getters on your class object.
Hope, it helps.
You can define getter-setter method for the CansTypeObject class as follows for accessing them easily:
public class CansTypeObject {
String productId;
String productName;
String productPrice;
String productReturnPrice;
String productImage;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getProductReturnPrice() {
return productReturnPrice;
}
public void setProductReturnPrice(String productReturnPrice) {
this.productReturnPrice = productReturnPrice;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
}
for creating getter-setter method you can use shortcut key for
MAC - command + N
Windows - Alt + Insert
Another way is to open the class for which you have to make getter setter and then right click and from the context menu select Generate option

Realm: How to query with many to many field

I recently heard about Realm for android (also available for iOS) in this talk by Joaquim Verques . Very interesting and very powerful tool for persistent data.
I decided to give it a try after the video, researching and reading the documentation.
I found it very easy to use and set up but i end up stuck in the middle of my project because i couldn't manage to successfully make a query with many to many relationships.
I have created a small example for this topic.
My models:
public class Feed extends RealmObject {
#PrimaryKey
private int id;
private String title;
private String description;
private String link;
private Terms terms;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Terms getTerms() {
return terms;
}
public void setTerms(Terms terms) {
this.terms = terms;
}
}
public class Terms extends RealmObject {
private String tag;
private RealmList<Category> categories;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public RealmList<Category> getCategories() {
return categories;
}
public void setCategories(RealmList<Category> categories) {
this.categories = categories;
}
}
public class Category extends RealmObject {
#PrimaryKey
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So far so good, now im going to save a list of feeds to realm (make it persistent) and then try to make some query.
public static void test(final Context context,final List<Feed> feedList) {
Realm realm = null;
try {
realm = Realm.getInstance(context);
realm.beginTransaction();
realm.copyToRealmOrUpdate(feedList);
realm.commitTransaction();
RealmResults<Feed> realmResults = realm.where(Feed.class).findAll();// return me all feeds
RealmResults<Feed> realmResults1 = realm.where(Feed.class).equalTo("id", 1).findAll(); // return feed with id 1
RealmResults<Feed> realmResults2 = realm.where(Feed.class).equalTo("terms.tag", "tech").findAll(); // return feeds //with tag = "tech"
RealmResults<Feed> realmResults3 = realm.where(Feed.class).equalTo("terms.category.name", "test").findAll(); //exception here
}
} catch (Exception e) {
//Empty
Log.d("Test","",e);
} finally {
if (realm != null)
realm.close();
}
}
}
Everything run well untill the last query and i get this exception:"java.lang.IllegalArgumentException: Invalid query: category does not refer to a class."
So my question is How do i do that kind of query successfully, as i will like realm to return me every feed with terms which has at least 1 category with name = "test"
Thank you very much
Your field is called "categories" and not "category". The third query should be:
RealmResults<Feed> realmResults3 = realm.where(Feed.class).equalTo("terms.categories.name", "test").findAll();

how to get object's attributes

How can I get an object's attributes?
I created an object that has two fields, first one called Title containing the string value "title1" and second one called Description containing the string value "description1". I would like to get the strings inside.
The method item.toString() gets me the two strings one after the other. Is there a way to get the strings separatively?
Just create accessor methods for each field.
Assuming you have declared your fields like this:
private String title;
private String desciption;
create the accessor methods in your class definition like this:
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
then you just call these methods to get the appropriate value.
Class Declaration
public class Class_Name {
private String Category;
private String Category_Type;
public Class_Name () {
super();
}
public Class_Name(String Category, String Category_Type) {
super();
this.Category = Category;
this.Category_Type = Category_Type;
}
/*public Class_Name (String Category_Type) {
this.Category_Type = Category_Type;
}*/
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public String getCategory_Type() {
return Category_Type;
}
public void setCategory_Type(String Category_Type) {
this.Category_Type = Category_Type;
}
}
In the class where you should use this Object to store and retrieve values.
//Create an object for this class
private Class_Name data;
// To save values
data.setCategory(sCategory);
data.setCategory_Type(sType);
// To retrieve values
String sCategory = data.getCategory();
String sType = data.getCategory_Type();

Categories

Resources