name is null - Custom ArrayAdapter - android

I have a custom ArrayAdapter that is supposed to display a users' profile image and username.
I've been following this tutorial:
Custom Android Layouts with Your Own ArrayAdapter
Yet, when I open my activity, the app crashes and says:
java.lang.NullPointerException: name is null
Which is true, since I have yet to build a feature for users to add one. Instead it should be displaying a placeholder image.(Picasso)
Here is my CustomAdapter:
public class ContactsAdapter extends ArrayAdapter<CustomContact>{
private Context context;
private List<CustomContact> contactList;
//constructor, call on creation
public ContactsAdapter(Context context, int resource, ArrayList<CustomContact> objects) {
super(context, resource, objects);
this.context = context;
this.contactList = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
//get the user we are displaying
CustomContact customcontact = contactList.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.mylist, null);
ImageView image = (ImageView) view.findViewById(R.id.friend_icon2);
TextView friend_name = (TextView) view.findViewById(R.id.Itemname);
//get & set username
String completeUsername = customcontact.getUsername();
friend_name.setText(completeUsername);
//get the image associated with this user
int imageID = context.getResources().getIdentifier(customcontact.getImageURL(), "string", context.getPackageName());
//set image
Picasso.get().load(imageID).placeholder(R.drawable.placeholder_image).resize(96, 96)
.centerCrop().into(image);
return view;
}
}
The line in question returning null is this one defining ImageID:
//get the image associated with this user
int imageID = context.getResources().getIdentifier(customcontact.getImageURL(), "string", context.getPackageName());
Here is my ContactsActivity.java
public class ContactsActivity extends ListActivity {
private DatabaseReference mFriendDatabase;
private DatabaseReference mRootRef;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
private RecyclerView mFriendsList;
private ListView contacts_list, lstView;
private ArrayAdapter dataAdapter;
private RelativeLayout individual_contact;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
ArrayList<CustomContact> contactList = new ArrayList<>();
ArrayAdapter<CustomContact> adapter = new ContactsAdapter(ContactsActivity.this, 0, contactList);
mAuth = FirebaseAuth.getInstance();
mRootRef = FirebaseDatabase.getInstance().getReference();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("friends").child(mCurrent_user_id);
mFriendDatabase.keepSynced(true);
contacts_list = (ListView) findViewById(android.R.id.list);
contacts_list.setAdapter(adapter);
individual_contact = (RelativeLayout) findViewById(R.id.mylist);
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users");
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot friendKeySnapshot: dataSnapshot.getChildren()) {
String friendKey = friendKeySnapshot.getKey();
usersRef.child(friendKey).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot friendSnapshot) {
String friendName = friendSnapshot.child("username").getValue(String.class);
String friendPicture = friendSnapshot.child("image_url").getValue(String.class);
contactList.add(
new CustomContact(friendName, friendPicture)
);
contacts_list.setAdapter(adapter);
//add event listener so we can handle clicks
AdapterView.OnItemClickListener adapterViewListener = new AdapterView.OnItemClickListener() {
//on click
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomContact customContact = contactList.get(position);
Intent intent = new Intent(ContactsActivity.this, MessageActivity.class);
intent.putExtra("username", customContact.getUsername());
intent.putExtra("ImageURL", customContact.getImageURL());
startActivity(intent);
}
};
//set the listener to the list view
contacts_list.setOnItemClickListener(adapterViewListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}

To set image with Picasso you need to put an image url as parameter in the load() method but you are putting an integer id. You may try this
Picasso.get().load(customcontact.getImageURL()).placeholder(R.drawable.placeholder_image).resize(96, 96)
.centerCrop().into(image);
Please provide your ContactsActivity.java codes for further clarification.

Related

FirebaseRecyclerAdapter model returning null values

I'm trying to make a comment system for posts on my social media app. In my database each post has a section inside of "comments" table, like so:
"hypno--######" is the title of the social media post. It Contains the comment, user id of the user who posted the comment, and a unixtimestamp when the comment was posted. Each comment is titled after the time it was posted.
This is the Comment class
public class comment {
public String uID;
public String comment_t;
public long unixTimestamp;
public comment() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public comment(String uID, String comment_t, long unixTimestamp) {
this.uID = uID;
this.comment_t = comment_t;
this.unixTimestamp = unixTimestamp;
}
public String getuID() {
return uID;
}
public void setuID(String uID) {
this.uID = uID;
}
public String getComment() {return comment_t;}
public void setComment() {this.comment_t = comment_t; }
public long getUnixTimestamp() {
return unixTimestamp;
}
}
This is the Comment Adapter:
Public class Adapter_Comment extends FirebaseRecyclerAdapter<comment, Adapter_Comment.ViewHolder_com> {
private DatabaseReference mDatabase;
private static final String TAG = "RecyclerViewAdapter";
private Context mContext;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private static AppCompatActivity unwrap(Context context) {
while (!(context instanceof Activity) && context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
}
return (AppCompatActivity) context;
}
public Adapter_Comment(#NonNull FirebaseRecyclerOptions<comment> options) {
super(options);
//this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder_com onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_comment, parent, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
return new ViewHolder_com(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder_com holder, int position, #NonNull comment model) {
mDatabase = FirebaseDatabase.getInstance().getReference();
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
holder.postPfp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//AppCompatActivity activity = (AppCompatActivity) v.getContext();
AppCompatActivity activity = unwrap(v.getContext());
Fragment OtherProfileFragment = new OtherProfileFragment();
Bundle bundle = new Bundle();
bundle.putString("key", model.getuID());
OtherProfileFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, OtherProfileFragment).addToBackStack(null).commit();
}
});
}
public class ViewHolder_com extends RecyclerView.ViewHolder {
TextView comment_text;
CircleImageView postPfp;
TextView time;
RelativeLayout comment_layout;
public ViewHolder_com(#NonNull View itemView) {
super(itemView);
postPfp = itemView.findViewById(R.id.iv_comment_icon);
comment_text = itemView.findViewById(R.id.tv_comment_text);
time = itemView.findViewById(R.id.tv_comment_time);
comment_layout = itemView.findViewById(R.id.comment_layout);
}
}
}
This is Comment Fragment:
public class CommentFragment extends Fragment {
private DatabaseReference mDatabase;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
View view;
String value;
RecyclerView recyclerView;
Query query;
TextView comment_text;
long unixTime = System.currentTimeMillis() / 1000L;
public long globalUnix;
Button comment_post;
String comment_string;
Adapter_Comment adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_comment, container, false);
value = getArguments().getString("key");
mDatabase = FirebaseDatabase.getInstance().getReference();
recyclerView = view.findViewById(R.id.recyclerv_comment);
comment_text = view.findViewById(R.id.tv_comment_type);
comment_post = view.findViewById(R.id.btn_comment_post);
globalUnix = (unixTime * -1);
comment_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(comment_text.getText().toString() == NULL){
Toast.makeText(getActivity(), "No Comment Typed", Toast.LENGTH_LONG).show();
}
else{
comment com = new comment();
com.uID = user.getUid();
com.comment_t = comment_text.getText().toString();
com.unixTimestamp = globalUnix;
mDatabase.child("comments").child(value).child(globalUnix + "").setValue(com);
}
}
});
initRecyclerView();
return view;
}
private void initRecyclerView(){
//Log.d(TAG, "initRecyclerView: init recyclerView");
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
query = FirebaseDatabase.getInstance().getReference().child("comments").orderByValue();
FirebaseRecyclerOptions<comment> options = new FirebaseRecyclerOptions.Builder<comment>().setQuery(query, comment.class).build();
adapter = new Adapter_Comment(options);
recyclerView.setAdapter(adapter);
adapter.startListening();
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Inside of the adapter I'm using the comment model, to get the uID, comment and timestamp to fill the holder, however when i set these values im getting null values. Is there something im missing when trying to connect the adapter/firebase and model/holder?
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
There's really too much going on in here, but...
As far as I can see you're creating a FirebaseUI adapter on FirebaseDatabase.getInstance().getReference().child("comments"). FirebaseUI adapters show the direct child nodes of the node you pass in, so in your case it'll create one view for the hypno---...196 node. You're trying to read a Comment object from there, but don't exist until one level lower in your JSON.
So you can:
Either show the comments for one post, by basing the adapter off of that. So: FirebaseDatabase.getInstance().getReference().child("comments").child("hypno---...196") (which the real key in there).
Or you can show one piece of information about each post, for example its key.
If you want to show a flat list of comments for all posts through the FirebaseUI adapter, you'll have to store a flat list of comments across all posts in your database too.

Firebase ListView is not updating in real time

When I make changes to the data which is displayed using ListView and DataSnapshot the data is not refreshed in real time until I restart the Activity. The ListView loads and displays all the data without any problem. Why is this happening and how to solve this ?
MainMenuRequest.java
public class MainMenuRequest extends AppCompatActivity {
String UserNameString;
DatabaseReference db;
ListView lv;
ArrayList<RequestItem> list = new ArrayList<>();
RequestItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_request);
makeItem();
}
public void makeItem ()
{
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReferenceFromUrl("https://vsem-inventory.firebaseio.com/ItemRequest");
ValueEventListener valueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<RequestItem>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
RequestItem Ri = ds.getValue(RequestItem.class);
Ri.setRefID(ds.getKey());
Log.d("myTag",ds.getKey());
list.add(Ri);
}
}
lv = findViewById(R.id.listViewRequest);
adapter = new RequestItemAdapter(MainMenuRequest.this,list);
lv.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("DatabaseError", databaseError.getMessage()); //Don't ignore errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
}
}
RequestItemAdapter.java
public class RequestItemAdapter extends ArrayAdapter<RequestItem> {
private Context ctx;
private ArrayList<RequestItem> list;
ImageView statusimg;
Drawable lateIcon;
Drawable paidIcon;
public RequestItemAdapter(Context context, ArrayList<RequestItem> list)
{
super(context,0,list);
this.ctx = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(ctx).inflate(R.layout.content_main_menu_request_list,parent,false);
final RequestItem rq = list.get(position);
final TextView tvAmount = listItem.findViewById(R.id.amountReq);
final TextView tvName = listItem.findViewById(R.id.nameReq);
final TextView tvSerial = listItem.findViewById(R.id.serialNoReq);
final TextView tvSupplier = listItem.findViewById(R.id.supplierNameReq);
final ImageView more = listItem.findViewById(R.id.moreReq);
statusimg = listItem.findViewById(R.id.statusReq);
lateIcon = listItem.getResources().getDrawable(R.drawable.late);
Drawable pendingIcon = listItem.getResources().getDrawable(R.drawable.pending);
String userName = rq.getRequestBy();
userName = userName.replace("#vsemtech.com","");
tvAmount.setText(userName);
tvName.setText(rq.getProductName());
tvSerial.setText(rq.getSerialNo());
tvSupplier.setText(rq.getCategory());
String status = rq.getStatus();
if(status.equals("REJECT"))
statusimg.setImageDrawable(lateIcon);
else if (status.equals("APPROVED"))
statusimg.setImageDrawable(paidIcon);
else if (status.equals("PENDING"))
statusimg.setImageDrawable(pendingIcon);
more.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String RequestBy = rq.getRequestBy();
String Status = rq.getStatus();
String ProductName = rq.getProductName();
String SerialNo = rq.getSerialNo();
String Model = rq.getModel();
String Category = rq.getCategory();
String Quantity = rq.getQuantity();
String Remarks = rq.getRemarks();
showMenu(rq,more);
}
});
return listItem;
}
public void showMenu (RequestItem reqItem,ImageView More)
{
final RequestItem finalItem = reqItem;
final ImageView more = More;
final String shortRequestby = reqItem.getRequestBy().replace("#vsemtech.com","");
final DatabaseReference DeleteRef = FirebaseDatabase.getInstance().getReference().child("ItemRequest").child(shortRequestby);
final DatabaseReference DbRef = FirebaseDatabase.getInstance().getReference().child("ItemRequest").child(shortRequestby).child(finalItem.getRefID());
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ctx, more);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.menu_options_req, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.item_approve)
{
DeleteRef.child(finalItem.getRefID()).removeValue();
writeNewPost(new RequestItem(finalItem,"APPROVED"));
Toast.makeText(ctx,"Successfully approved request made by " + shortRequestby ,Toast.LENGTH_SHORT).show();
}
else if (itemId == R.id.item_reject)
{
DeleteRef.child(finalItem.getRefID()).removeValue();
writeNewPost(new RequestItem(finalItem,"REJECTED"));
Toast.makeText(ctx,"Successfully rejected request made by " + shortRequestby ,Toast.LENGTH_SHORT).show();
}
return true;
}
});
popup.show();//showing popup menu
}
public void writeNewPost(RequestItem item)
{
DatabaseReference dbReq = FirebaseDatabase.getInstance().getReference().child("ItemHistory").child(item.getRequestBy().replace("#vsemtech.com",""));
String key = dbReq.push().getKey();
Map<String, Object> postValues = toMap(item);
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(key, postValues);
dbReq.updateChildren(childUpdates);
}
public Map<String, Object> toMap(RequestItem item)
{
HashMap<String, Object> result = new HashMap<>();
result.put("ProductName", item.getProductName());
result.put("SerialNo", item.getSerialNo());
result.put("Quantity", item.getQuantity());
result.put("Category",item.getCategory());
result.put("Model", item.getModel());
result.put("RequestBy", item.getRequestBy());
result.put("Status",item.getStatus());
result.put("Remarks",item.getRemarks());
return result;
}
}
You are using addListenerForSingleValueEvent() which will only listen for single value and then stop. You need to use addValueEventListener().
one way of doing this is you need to add elements in this ArrayList<RequestItem> list by making this as static in adapter class instead of the list in activity which you are passing to the adapter then you notifyDataSetChanged() function will work if you want to show changes in the list in real time
I suggest you to use the already built in library to make the list automatically updated when new data is pushed in firebase: check out this
If you want to stick with a custom implementation, define the adapter first in OnCreate callback and call adapter.notifyDataSetChanged() every time you updated your data.
If you want to insert/update/delete only one item inside your list call adapter.notifyItemChanged(position) from your adapter.
I strongly suggest you to switch to RecyclerView instead of ListView in Android (interesting comparison between them)

Null pointer exception on null object reference

I keep getting a null pointer exception error at the DessertAdapter class starting at the line holder.mName.setText(dessert.getName());
I've tried all methods I know and I'm still getting the same error.
Here is the Adapter class
public class DessertAdapter extends RecyclerView.Adapter<DessertAdapter.DessertVh> {
private List<Dessert> desserts = new ArrayList<>();
private static final int VIEW_TYPE_EMPTY_LIST_PLACEHOLDER = 0;
private static final int VIEW_TYPE_OBJECT_VIEW = 1;
private Context context;
#Override
public int getItemViewType(int position) {
if (desserts.isEmpty()) {
return VIEW_TYPE_EMPTY_LIST_PLACEHOLDER;
} else {
return VIEW_TYPE_OBJECT_VIEW;
}
}
public DessertAdapter(Context context,List<Dessert> desserts) {
this.context = context;
this.desserts = desserts;
}
// TODO: another placeholder stuff here
#Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_dessert, parent, false);
return new DessertAdapter.DessertVh(view);
}
#Override
public void onBindViewHolder(DessertVh holder, int position) {
Dessert dessert = desserts.get(position);
System.out.println(position);
holder.mName.setText(dessert.getName());
holder.mDescription.setText(dessert.getDescription());
holder.mFirstLetter.setText(String.valueOf(dessert.getFirstLetter()));
holder.mPrice.setText(String.valueOf(dessert.getAmount()));
}
#Override
public int getItemCount() {
return desserts == null ? 0 : desserts.size();
}
public static class DessertVh extends RecyclerView.ViewHolder {
private TextView mName;
private TextView mPrice;
private TextView mDescription;
private TextView mFirstLetter;
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mPrice = (TextView) itemView.findViewById(R.id.txt_price);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
}
Here is the class to save the data to the Dessert object
public class AddGigActivity extends AppCompatActivity {
private static String TAG = "AddGigActivity";
private ImageButton saveBtn;
private EditText gigName, gigDescrip, gigAmount;
private String userID;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_gig);
gigName = (EditText)findViewById(R.id.gig_name);
gigDescrip = (EditText)findViewById(R.id.gig_description);
gigAmount = (EditText) findViewById(R.id.gig_amnt);
saveBtn = (ImageButton) findViewById(R.id.mybtn_add);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = FirebaseDatabase.getInstance().getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddGig();
}
});
}
// real-time adding to the firebase database
private void AddGig(){
String name = gigName.getText().toString();
String descrip = gigDescrip.getText().toString();
String amount = gigAmount.getText().toString();
if((!TextUtils.isEmpty(name))&&(!TextUtils.isEmpty(descrip) && (!TextUtils.isEmpty(amount))) ){
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
String id = myRef.push().getKey();
Dessert dessert = new Dessert( name, descrip, amount);
// myRef.child(id).setValue(dessert);
myRef.child("users").child(userID).child("Gig posts").child(id).setValue(dessert);
Toast.makeText(this, "Posted! ",Toast.LENGTH_LONG).show();
finish();
// you can still sprlit these to check for each text field
}else{
Toast.makeText(this, "One or more field(s) missing!",Toast.LENGTH_LONG).show();
}
}
And here is the main activity code snippet that displays the data from firebase on the recycler view:
public static class FeedsFragment extends Fragment {
int color;
public FeedsFragment() {
}
#SuppressLint("ValidFragment")
public FeedsFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
final List<Dessert> dessertList;
dessertList = new ArrayList<>();
//dessertList = new Dessert(context,"");
final String curtUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
// DatabaseReference mDatabaseGig = rootRef.child("users").child(curtUserId).child("Gig posts");
final String id = rootRef.push().getKey();
final DessertAdapter adapter = new DessertAdapter(getContext(), dessertList);
recyclerView.setAdapter(adapter);
rootRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dessertList.clear();
for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
Dessert dessert = gigSnapshot
.child("users")
.child(curtUserId)
.child("Gig posts")
.child(id).getValue(Dessert.class);
dessertList.add(dessert);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// possible to put progress dialogue
return view;
}
}
please would you mind taking a look at the code and help me straighten it out? Thank you.
try below Adapter class
public class DessertAdapter extends RecyclerView.Adapter<DessertAdapter.DessertVh> {
private List<Dessert> desserts;
private static final int VIEW_TYPE_EMPTY_LIST_PLACEHOLDER = 0;
private static final int VIEW_TYPE_OBJECT_VIEW = 1;
private Context context;
// TODO: placeholder stuff here
#Override
public int getItemViewType(int position) {
if (desserts.isEmpty()) {
return VIEW_TYPE_EMPTY_LIST_PLACEHOLDER;
} else {
return VIEW_TYPE_OBJECT_VIEW;
}
}
public DessertAdapter(Context context,List<Dessert> desserts) {
this.context = context;
this.desserts = desserts;
// desserts = Dessert.prepareDesserts(
// context.getResources().getStringArray(R.array.dessert_names),
// context.getResources().getStringArray(R.array.dessert_descriptions),
// context.getResources().getStringArray(R.array.dessert_amounts));
}
// TODO: another placeholder stuff here
#Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_dessert, parent, false);
return new DessertAdapter.DessertVh(view);
}
#Override
public void onBindViewHolder(DessertVh holder, int position) {
holder.mName.setText(desserts.get(position).getName());
holder.mDescription.setText(desserts.get(position).getDescription());
holder.mFirstLetter.setText(String.valueOf(desserts.get(position).getFirstLetter()));
holder.mPrice.setText(String.valueOf(desserts.get(position).getAmount()));
}
#Override
public int getItemCount() {
// if nothing, return null,
// else return the number of items in the list
return desserts == null ? 0 : desserts.size();
}
public static class DessertVh extends RecyclerView.ViewHolder {
private TextView mName;
private TextView mPrice;
private TextView mDescription;
private TextView mFirstLetter;
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mPrice = (TextView) itemView.findViewById(R.id.txt_price);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
}
Ok, so I fixed it!
here's the code
public static class UserFeedFragment extends Fragment {
int color;
public UserFeedFragment() {
}
#SuppressLint("ValidFragment")
public UserFeedFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
String curtUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference()
.child("users")
.child(curtUserId)
.child("Gig posts");
final List<Dessert> dessertList = new ArrayList<Dessert>();
final DessertAdapter adapter = new DessertAdapter(getContext(), dessertList);
recyclerView.setAdapter(adapter);
rootRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dessertList.clear();
for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
Dessert dessert = gigSnapshot
.getValue(Dessert.class);
dessertList.add(dessert);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// possible to put progress dialogue
return view;
}
}
All I had to change was here
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference()
.child("users")
.child(curtUserId)
.child("Gig posts");
then add an event listener here
rootRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
and it worked!
I do have a minor problem though. I have two feeds fragment: UserFeed and FeedsFragments. The Userfeed gets the feeds that the current user has posted while the FeedsFragment is meant to get feeds posted by all users. I tried doing this
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference()
.child("users")
// .child(curtUserId) I commented out the id of the user but nothing happened
.child("Gig posts");
My question is : is there a way I can "direct" the reference to retrieve posts by all users?
Once again, thanks so much in advance for your help!

How can i read data of outh user in firebase database?

I am building an android app in which when the user create its account as a technician his name id display in a listview in which other users which don't have firebase outh.the problem is that I am unable to show data of technicians in the listview.
This is my firebase database
This is my code that return 0 items or blank listview. I tried several things, but unable to display the information of technicians. Anyone please help me with this I am new in firebase.
public class Technician extends Activity {
ListView listView;
ArrayList<String> tecnames = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_technician);
ImageButton Back_Btn = (ImageButton) findViewById(R.id.back);
Back_Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Technician.this, Technician_main.class);
startActivity(i);
finish();
}
});
listView = (ListView) findViewById(R.id.list_item);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(Technician.this, Book_Now.class);
startActivity(intent);
finish();
}
});
Technician.CostumAdapter costumAdapter = new Technician.CostumAdapter();
listView.setAdapter(costumAdapter);
GetItems();
}
private class CostumAdapter extends BaseAdapter {
#Override
public int getCount() {
return tecnames.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.cuctom_listview, null);
TextView txt_one = (TextView) view.findViewById(R.id.skill_txt);
txt_one.setText(tecnames.get(i));
return view;
}
}
private void GetItems() {
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("user");
final Query itemsQuery = ref.orderByChild("name");
itemsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
Pojo item = singleSnapshot.getValue(Pojo.class);
tecnames.add(String.valueOf(item));
Log.e(TAG,"value of name"+itemsQuery);
}
}else {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e(TAG, "Returning " + tecnames.size() + " items");
}
}
instead of this:
Technician.CostumAdapter costumAdapter = new Technician.CostumAdapter();
Write this:
Technician.CostumAdapter costumAdapter = new Technician.CostumAdapter(getApplicationContext(),tecnames);
Then add this constructor inside of the class:
private ArrayList<String> datas;
Context mContext;
public CustomAdapter(Context context, ArrayList<String> datas) {
super(context, R.layout.row_item, datas);
this.mContext=context;
this.datas = datas;
}
change addListenerforSingleValueEvent to addValueEventListener
Ok, there are few things that you need to fix:
1.Your array list tecnames should be of your POJO class
ArrayList<POJO> tecnames = new ArrayList<>();
Now change tecnames.add(String.valueOf(item)); to tecnames.add(item);
2.As #Peter Haddad suggested, you need to give this list to your adapter as a dataset.
3.Firebase DB listeners are asynchronous so you need to notify your adapter after you get data in your dataset(list). Add the following code inside onDataChange after your foreach loop:
costumAdapter.notifyDataSetChanged();
You can refer to this link for the 3rd point.

How can I retrieve all nodes data from Firebase to listview in Android?

I've followed below tutorial and it works, but it can only retrieve one spacial node data, how can I retrieve all nodes data? Below photo is my database.
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("my url");
final FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(this, String.class, android.R.layout.simple_list_item_1, databaseReference) {
#Override
protected void populateView(View v, String model, int position) {
TextView textView= (TextView) v.findViewById(android.R.id.text1);
textView.setText(model);
}
};
listView.setAdapter(firebaseListAdapter);
A FirebaseListAdapter can show a list of items. Your data model is not a list, but a tree. So it cannot be shown with a single FirebaseListAdapter.
I have create Adapter class for binding ListView and row_item.xml for display list of items in ListView.
FireListAdapter.java
public class FireListAdapter extends BaseAdapter {
private List<User> modelList = new ArrayList<User>();
private Context context;
LayoutInflater inflater;
public FireListAdapter(Context context, List<User> modelList) {
this.context = context;
this.modelList = modelList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return modelList.size();
}
#Override
public Object getItem(int position) {
return modelList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
view = inflater.inflate(R.layout.row_item, null);
TextView textName = (TextView) view.findViewById(R.id.textName);
TextView textEmail = (TextView) view.findViewById(R.id.textEmail);
textName.setText(modelList.get(position).getName());
textEmail.setText(modelList.get(position).getEmail());
return view;
}
}
And create Welcome.java for display data from FirebaseDatabase in ListView.
public class Welcome extends AppCompatActivity implements View.OnClickListener {
private ListView listView;
private List<User> myModelList = new ArrayList<User>();
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private String TAG = Welcome.class.getSimpleName();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
setUI();
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'signUp' node Here signUp is table in FirebaseDatabase
mFirebaseDatabase = mFirebaseInstance.getReference("signUp");
getData();
}
public void setUI() {
textProfile = (TextView) findViewById(R.id.textWelcome);
listView = (ListView) findViewById(R.id.listItem);
}
//This method is getting data from FirebaseDatabase
public void getData() {
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
Iterator<DataSnapshot> iterator = snapshotIterable.iterator();
while (iterator.hasNext()) {
DataSnapshot dataSnapshot1 = iterator.next();
User user = dataSnapshot1.getValue(User.class);
user.setName(user.getName());
user.setEmail(user.getEmail());
myModelList.add(user);
FireListAdapter fireListAdapter = new FireListAdapter(Welcome.this, myModelList);
fireListAdapter.notifyDataSetChanged();
listView.setAdapter(fireListAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Hope this will help You :)

Categories

Resources