I am unable to have my Firebase data show up in my RecyclerView. I am able to add data from my other activities to my Firebase Database, I am just having problems seeing the data in my RecyclerView.
I have created a FriebaseRecyclerAdapter that takes Recipe.class and my RecipeViewHolder. My ViewHolder takes three parts if my class (name, rating, and description). I am not receiving any helpful errors in Logcat.
RecipeList.class
public class RecipeList extends AppCompatActivity {
private RecyclerView recipes;
private FloatingActionButton newRecipeBtn;
private DatabaseReference mRecipeDatabase;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_list);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mRecipeDatabase = FirebaseDatabase.getInstance().getReference("Recipes");
newRecipeBtn = findViewById(R.id.fab);
recipes = findViewById(R.id.recyclerView);
recipes.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
recipes.setLayoutManager(mLayoutManager);
recipes.setItemAnimator(new DefaultItemAnimator());
recipes.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
FirebaseRecyclerAdapter<Recipe, RecipeViewHolder> adapter = new FirebaseRecyclerAdapter<Recipe, RecipeViewHolder>(
Recipe.class,
R.layout.recycler_list_item,
RecipeViewHolder.class,
mRecipeDatabase
) {
#Override
protected void populateViewHolder(RecipeViewHolder viewHolder, Recipe model, int position) {
viewHolder.setName(model.getName());
viewHolder.setRating(model.getRating());
viewHolder.setDescription(model.getDescription());
}
};
recipes.setAdapter(adapter);
}
public void toRecipeAdd(View view){
Intent intent = new Intent(RecipeList.this, RecipeAdd.class);
startActivity(intent);
}
public static class RecipeViewHolder extends RecyclerView.ViewHolder{
TextView text_name, text_rating, text_description;
public RecipeViewHolder(View itemView){
super(itemView);
text_name = itemView.findViewById(R.id.recipeNameTextView);
text_rating = itemView.findViewById(R.id.recipeRatingTextView);
text_description = itemView.findViewById(R.id.recipeDescriptionTextView);
}
public void setName(String name){
text_name.setText(name);
}
public void setRating(String rating){
text_rating.setText(rating);
}
public void setDescription(String description){
text_description.setText(description);
}
}
}
Recipe.Class
public class Recipe {
public String name;
public String url;
public String rating;
public String description;
public String id;
public String ingredients, instruction;
public Recipe(){}
public Recipe(String id, String name, String url, String rating, String description,
String ingredients, String instruction) {
this.id = id;
this.name = name;
this.url = url;
this.rating = rating;
this.description = description;
this.ingredients = ingredients;
this.instruction = instruction;
}
public Recipe(String name, String rating, String description){
this.name = name;
this.rating = rating;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public String getInstruction() {
return instruction;
}
public void setInstruction(String instruction) {
this.instruction = instruction;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Remove the following for the data to appear:
recipes.setHasFixedSize(true);
Refer to this:
https://github.com/firebase/FirebaseUI-Android/issues/204
Related
I've been trying to show my array of foods on a textview from my Firestore Database. I have been able to view the array on the textview but it is not readable by lame readers, they show in the array braces and the curly brackets. I want to extract the values like produName, Quantity, etc independently
Below is my Model class and Activity class.
public class Request {
private String phone;
private String name;
private String address;
private String total;
private String status;
private List<HashMap<String, String>> foods; //list of food orders
private #ServerTimestamp Date timestamp;
public Request() {
}
public Request(String phone, String name, String address, String total, List<HashMap<String, String>> foods) {
this.phone = phone;
this.name = name;
this.address = address;
this.total = total;
this.foods = foods;
this.status = "0"; //Default is 0, 0: Place, 1: Shipping, 2: Shipped
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public List<HashMap<String, String>> getFoods() {
return foods;
}
public void setFoods(List<HashMap<String, String>> foods) {
this.foods = foods;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
MY ACTIVITY CLASS, I implemented call to firestore at onStart()
#Override
protected void onStart() {
super.onStart();
FirestoreRecyclerOptions<Request> options = new FirestoreRecyclerOptions.Builder<Request>()
.setQuery(query, Request.class)
.build();
adapter = new FirestoreRecyclerAdapter<Request, MainActivity.DataViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MainActivity.DataViewHolder dataViewHolder, int i, #NonNull final Request mainMenuItem) {
dataViewHolder.setData(mainMenuItem.getTotal(), mainMenuItem.getName(), mainMenuItem.getStatus(), mainMenuItem.getPhone(),
mainMenuItem.getAddress(), mainMenuItem.getTimestamp(), mainMenuItem.getFoods());}
#NonNull
#Override
public MainActivity.DataViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_layout, parent, false);
return new MainActivity.DataViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private View view;
DataViewHolder(View itemView) {
super(itemView);
view = itemView;
}
void setData(String orderTotalValue, String nameOfPerson, String dataOrderStatus, String dataOrderPhone, String dataOrderAddress,
Date dataDateAndTime, final List<HashMap<String,String>>foodsOrdered) {
TextView orderTotal = view.findViewById(R.id.order_total);
TextView orderStatus = view.findViewById(R.id.order_status);
TextView orderPhone = view.findViewById(R.id.order_phone);
TextView orderAddress = view.findViewById(R.id.order_address);
TextView orderName = view.findViewById(R.id.order_name);
TextView orderDateAndTime = view.findViewById(R.id.order_dateTime);
TextView orderFoods = view.findViewById(R.id.order_foods);
orderTotal.setText(orderTotalValue);
orderStatus.setText(convertCodeToStatus(dataOrderStatus));
orderPhone.setText(dataOrderPhone);
orderAddress.setText(dataOrderAddress);
orderName.setText(nameOfPerson);
orderDateAndTime.setText(dataDateAndTime.toString());
//what i must do to foods array when it comes and then finally is attached to the textview!
orderFoods.setText(foodsOrdered.toString());
}
}
You can create a model class (OrderData) with this parameters discount, price, productId, productName, quantity and replace in ActualFoodRequest class
private List<String> foods; //list of food orders
with this
private List<OrderData> foods;
I put in intent my object with following code (while putting list does exists, I checked in debugger)
Intent intent = new Intent(getApplicationContext(), ProductActivity.class);
intent.putExtra("product", CategoryActivity.this.list.get(position));
startActivity(intent);
And then retrive
Intent intent = getIntent();
product = (Product) intent.getSerializableExtra("product");
But it is null
Model class is following
public class Product implements Serializable {
Integer pk;
String name;
String description;
Integer price;
String image_url;
List<Option> options;
public Product(Integer pk, String name, String description, Integer price, String image_url, List<Option> options) {
this.pk = pk;
this.name = name;
this.description = description;
this.price = price;
this.image_url = image_url;
this.options = options;
}
public Integer getPk() {
return pk;
}
public void setPk(Integer pk) {
this.pk = pk;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
}
What am I doing wrong ?
You have to add more code to use your class inside intent data.
import android.os.Parcel;
import android.os.Parcelable;
public class Yourclass implements Parcelable {
//your code
#Override
public void writeToParcel(Parcel out, int flags) {
//e.g.
out.writeInt(this.getWhat());
//similar code
}
#Override
public int describeContents() {
return 0;
}
private YourClass(Parcel in) {
//e.g.
this.setWhat(in.readInt());
}
public static final Parcelable.Creator<YourClass> CREATOR
= new Parcelable.Creator<YourClass>() {
public YourClass createFromParcel(Parcel in) {
return new YourClass(in);
}
public YourClass[] newArray(int size) {
return new YourClass[size];
}
};
}
to store use intent.putExtra(EXTRANAME, obj); to retrieve use YourClass myObj = (YourClass) getIntent().getParcelableExtra(EXTRANAME);
I am trying to download data from the url ( JSON ) =
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json
for the networking i have used retrofit, and these are my classes, whenever i try to access the nested classes or lists, it throws a fatal error.
MainActivity
public class MainActivity extends AppCompatActivity {
ArrayList<Recipe> mRecipies = new ArrayList<>();
public TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.text);
IRecipe iRecipe = RetrofitBuilder.Retrieve();
Call<ArrayList<Recipe>> recipe = iRecipe.getRecipe();
recipe.enqueue(new Callback<ArrayList<Recipe>>() {
#Override
public void onResponse(Call<ArrayList<Recipe>> call, Response<ArrayList<Recipe>> response) {
mRecipies = response.body();
text.setText(mRecipies.get(3).getIngredients().size());
}
#Override
public void onFailure(Call<ArrayList<Recipe>> call, Throwable t) {
}
});
MyRecipe class
public class Recipe {
private String id;
private String name;
private List<Ingredients> ingredients = new ArrayList<>();
private List<Steps> steps = new ArrayList<>();
private String servings;
public Recipe(String id, String name, String servings, List<Ingredients> ingredients, List<Steps> steps) {
this.id = id;
this.name = name;
this.ingredients = ingredients;
this.steps = steps;
this.servings = servings;
}
public Recipe(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Ingredients> getIngredients() {
return ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
this.ingredients = ingredients;
}
public List<Steps> getSteps() {
return steps;
}
public void setSteps(List<Steps> steps) {
this.steps = steps;
}
public String getServings() {
return servings;
}
public void setServings(String servings) {
this.servings = servings;
}
}
My ingredients class
public class Ingredients {
private String quantity;
private String measure;
private String ingredient;
public Ingredients(String quantity, String measure, String ingredient) {
this.quantity = quantity;
this.measure = measure;
this.ingredient = ingredient;
}
public Ingredients(){
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getMeasure() {
return measure;
}
public void setMeasure(String measure) {
this.measure = measure;
}
public String getIngredient() {
return ingredient;
}
public void setIngredient(String ingredient) {
this.ingredient = ingredient;
}
}
Retrofit classes
Builder
public final class RetrofitBuilder {
static IRecipe iRecipe;
public static IRecipe Retrieve() {
Gson gson = new GsonBuilder().create();
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
iRecipe = new Retrofit.Builder()
.baseUrl("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/")
.addConverterFactory(GsonConverterFactory.create(gson))
.callFactory(httpClientBuilder.build())
.build().create(IRecipe.class);
return iRecipe;
}
}
Interface
public interface IRecipe {
#GET("baking.json")
Call<ArrayList<Recipe>> getRecipe();
}
Stack Trace
FATAL EXCEPTION: main
Process: com.example.vamshi.retrofittrial, PID: 20350
android.content.res.Resources$NotFoundException: String resource ID #0x9
at android.content.res.Resources.getText(Resources.java:328)
at android.content.res.MiuiResources.getText(MiuiResources.java:123)
at android.widget.TextView.setText(TextView.java:4432)
at com.example.vamshi.retrofittrial.MainActivity$1.onResponse(MainActivity.java:34)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5527)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-08 19:07:00.145 20350-20350/com.example.vamshi.retrofittrial E/MQSEventManagerDelegate: failed to get MQSService.
Well, setText doesnt allow integers.
So instead of
text.setText(mRecipies.get(3).getIngredients().size());
use
text.setText(String.valueof(mRecipies.get(3).getIngredients().size()));
I have a model class "JobPostBean" which I'm initiating in another model class and adding data using the second model class. I would like to clear any data which gets saved in the "JobPostBean" class. Is there any way to clear it either in "JobPostBean" class or in the second model class where its initialised? I would prefer to clear it using a single method rather than setting every item in the "JobPostBean" class to null.
public class BidNextJobDataModel {
private static BidNextJobDataModel ourInstance = new BidNextJobDataModel();
public static BidNextJobDataModel getInstance() {
return ourInstance;
}
private BidNextJobDataModel() {
}
public UserBean userBean;
// Here I initialised the class
public JobPostBean jobPostBean = new JobPostBean();
public ArrayList<FilterModel> filterModelArrayList = new ArrayList<FilterModel>();
public ArrayList<FilterModel> notificationModelArrayList = new ArrayList<FilterModel>();
public ArrayList<FilterModel> chooseCategoryArrayList = new ArrayList<FilterModel>();
public ArrayList<JobsBean> jobsBeanArrayList = new ArrayList<JobsBean>();
}
public class JobPostBean {
private String jobtype="";
private String days="";
private String hour="";
private String title="";
private String category="";
private String categorytxt="";
private String description="";
private String price="";
private String duration="";
private String is_certified="";
private String is_insure="";
private String is_experience="";
private String address="";
private String name="";
private String image="";
private String date="";
private String pricetype="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getJobtype() {
return jobtype;
}
public void setJobtype(String jobtype) {
this.jobtype = jobtype;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public String getHour() {
return hour;
}
public void setHour(String hour) {
this.hour = hour;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategorytxt() {
return categorytxt;
}
public void setCategorytxt(String categorytxt) {
this.categorytxt = categorytxt;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getIs_certified() {
return is_certified;
}
public void setIs_certified(String is_certified) {
this.is_certified = is_certified;
}
public String getIs_insure() {
return is_insure;
}
public void setIs_insure(String is_insure) {
this.is_insure = is_insure;
}
public String getIs_experience() {
return is_experience;
}
public void setIs_experience(String is_experience) {
this.is_experience = is_experience;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPricetype() {
return pricetype;
}
public void setPricetype(String pricetype) {
this.pricetype = pricetype;
}
}
public ArrayList<JobPostBean > al_JobPostBean = new ArrayList<JobPostBean >(); // Declare as global
At first Hold Data in ArrayList .If you want delete all data then You can Clear ArrayList
al_JobPostBean.clear();
The clear() method removes all the elements of ArrayList .
I am using Sugar ORM 1.3.1 and i am trying to save the following objects
public class Article extends SugarRecord<Article> implements Serializable {
#JsonProperty("Categories")
private List<Category> categories = new ArrayList<Category>();
#JsonProperty("Contents")
private List<Content> contents = new ArrayList<Content>();
#JsonProperty("Country")
private CountryRelated country;
#JsonProperty("Description")
private String description;
#JsonProperty("ExpiryDate")
private String expiryDate;
#JsonProperty("ExtraFields")
private List<ExtraField> extraFields = new ArrayList<ExtraField>();
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("ImageURL")
private String imageURL;
#JsonProperty("Name")
private String name;
#JsonProperty("PortalID")
private int portalID;
#JsonProperty("PublishDate")
private String publishDate;
#JsonProperty("Region")
private Region region;
#JsonProperty("Related")
private List<Related> related = new ArrayList<Related>();
#JsonProperty("Newsbite")
private boolean newsbite;
#JsonProperty("ShareURL")
private String shareURL;
#JsonProperty("Tags")
private List<Tag> tags = new ArrayList<Tag>();
#JsonProperty("Type")
private int type;
public Article() {
}
public Article(List<Category> categories, List<Content> contents, List<ExtraField> extraFields, CountryRelated country, String description, String expiryDate, int identifier, String imageURL, String name, boolean newsbite, int portalID, String publishDate, Region region, List<Related> related, String shareURL, List<Tag> tags, int type) {
this.categories = categories;
this.contents = contents;
this.extraFields = extraFields;
this.country = country;
this.description = description;
this.expiryDate = expiryDate;
this.identifier = identifier;
this.imageURL = imageURL;
this.name = name;
this.newsbite = newsbite;
this.portalID = portalID;
this.publishDate = publishDate;
this.region = region;
this.related = related;
this.shareURL = shareURL;
this.tags = tags;
this.type = type;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Content> getContents() {
return contents;
}
public void setContents(List<Content> contents) {
this.contents = contents;
}
public List<ExtraField> getExtraFields() {
return extraFields;
}
public void setExtraFields(List<ExtraField> extraFields) {
this.extraFields = extraFields;
}
public CountryRelated getCountry() {
return country;
}
public void setCountry(CountryRelated country) {
this.country = country;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNewsbite() {
return newsbite;
}
public void setNewsbite(boolean newsbite) {
this.newsbite = newsbite;
}
public int getPortalID() {
return portalID;
}
public void setPortalID(int portalID) {
this.portalID = portalID;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Related> getRelated() {
return related;
}
public void setRelated(List<Related> related) {
this.related = related;
}
public String getShareURL() {
return shareURL;
}
public void setShareURL(String shareURL) {
this.shareURL = shareURL;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
Category.class
public class Category extends SugarRecord<Category> implements Serializable {
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("Name")
private String name;
public constructor + getters and setters }
Content.class and CountryRelated.class have same structure
after i do article.save() my lists doesnt save . Am i doing something wrong or it doesnt save lists at all ???
I few things to look at.
First. I do not believe that the database will handle a column with the type of List or a type of other Object. When I tried running your code, I received:
Class cannot be read from Sqlite3 database. Please check the type of field categories(java.util.List)
These should be types the database can store. Try serializing your List(s) to Strings to insert them in the db. You can try doing this in your getter and setter. The setter takes the list of objects and converts it to a serialized String, the getter takes the serialized String and converts it back to a list of objects.
In the instance of SugarOrm, you can reference another table and it will create a relationship outlined here:
http://satyan.github.io/sugar/creation.html#why
Notice the "Author" type is just referencing a record from another table in the database.
Second I usually try and set my default values inside my default constructor. so something like:
... property declarations...
public Article() {
this.name = "Default Value";
}
Hope this helps you finish troublshooting!