I've two values in my document which will help me to set progress bar in the app.
for ex joined and slots. both are numbers.
and below i am fetching the values and setting the progressbar value using the slots and joined number which i fetched from the firestore :
public class Home extends AppCompatActivity {
private FirebaseFirestore mDatabase;
private FirestoreRecyclerAdapter adapter;
RecyclerView recyclerView;
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
mDatabase = FirebaseFirestore.getInstance();
recyclerView = findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
if (mUser != null) {
fetch();
} else {
Intent intent = new Intent(Home.this, Login.class);
startActivity(intent);
finish();
}
}
private void fetch() {
Query query = mDatabase.collection("batches");
FirestoreRecyclerOptions<batches> options = new FirestoreRecyclerOptions.Builder<batches>()
.setQuery(query, new SnapshotParser<batches>() {
#NonNull
#Override
public matches parseSnapshot(#NonNull DocumentSnapshot snapshot) {
return new matches(
snapshot.getLong("slots"),
snapshot.getLong("joined")
);
}
}).build();
adapter = new FirestoreRecyclerAdapter<batches,BatchHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull BatchHolder holder, int position, #NonNull batches model) {
holder.progressBar.setProgress(model.getJoined().intValue()/model.getSlots().intValue()*100);
}
#NonNull
#Override
public BatchHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_items,viewGroup,false);
return new BatchHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
public class BatchHolder extends RecyclerView.ViewHolder {
ProgressBar progressBar;
public BatchHolder(#NonNull View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progressBar);
}
}
and in batches.class :
public class batches {
private Long slots, joined;
public matches(Long slots, Long joined) {
this.slots = slots;
this.joined = joined;
}
public Long getSlots() {
return slots;
}
public void setSlots(Long slots) {
this.slots = slots;
}
public Long getJoined() {
return joined;
}
public void setJoined(Long joined) {
this.joined = joined;
}
but when i run the app it says the following error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setProgress(int)' on a null object reference
at app.Home$2.onBindViewHolder(Home.java:109)
at app.Home$2.onBindViewHolder(Home.java:100)
at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:125)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752).... so on
Related
I have been trying to implement search using firestoreUI but when i run my code the logcat says that:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.firebase.ui.firestore.FirestoreRecyclerAdapter.startListening()' on a null object reference
at com.example.homebarberv1.Search.onStart(Search.java:93)
below is my code:
public class Search extends AppCompatActivity implements FirebaseAuth.AuthStateListener{
private EditText searchField;
private Button searchButton;
private RecyclerView searchRecyclerview;
private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
private FirestoreRecyclerAdapter<User, UsersViewHolder> adapter;
private String searchText;
static {
FirebaseFirestore.setLoggingEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_search);
searchField = findViewById(R.id.SearchField);
searchButton = findViewById(R.id.SearchButton);
searchRecyclerview = findViewById(R.id.SearchContainer);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setReverseLayout(true);
manager.setStackFromEnd(true);
searchRecyclerview .setHasFixedSize(true);
searchRecyclerview .setLayoutManager(manager);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setSelectedItemId(R.id.search);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
return true;
case R.id.appointment:
startActivity(new Intent(getApplicationContext(),HomePage.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext(),Profile.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = searchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
#Override
public void onStart() {
super.onStart();
if (isSignedIn()) {
adapter.startListening();
}
firebaseAuth.addAuthStateListener(this);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
FirebaseAuth.getInstance().removeAuthStateListener(this);
}
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth auth) {
if (isSignedIn()) {
adapter.startListening();
} else {
Toast.makeText(Search.this,"user are not signed in",Toast.LENGTH_LONG);
}
}
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
#NonNull
private void firebaseUserSearch(String searchText){
CollectionReference sCollection =
FirebaseFirestore.getInstance().collection("Barbers");
Query sQuery = sCollection.startAt(searchText).endAt(searchText + "\uf8ff");
FirestoreRecyclerOptions<User> options =
new FirestoreRecyclerOptions.Builder<User>()
.setQuery(sQuery, User.class)
.setLifecycleOwner(this)
.build();
adapter = new FirestoreRecyclerAdapter<User, UsersViewHolder>(options) {
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.searchlist, parent, false);
return new UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull User model) {
holder.setName(model.getShopname());
holder.setPic(model.getPiclink());
holder.setAddress(model.getAddress() + ", " + model.getPostcode().toString() + ", " + model.getCity());
}
};
searchRecyclerview.setAdapter(adapter);
}
public class UsersViewHolder extends RecyclerView.ViewHolder {
private View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.shopNameS);
userNameView.setText(name);
}
public void setPic(String link){
ImageView imageView = (ImageView)mView.findViewById(R.id.imageS);
Picasso.get().load(link).into(imageView);
}
public void setAddress(String address){
TextView addressView = (TextView) mView.findViewById(R.id.shopAddressS);
addressView.setText(address);
}
}
}
the error refers to this line:
adapter.startListening();
I'm still new to Android, so I do not really understand what I'm doing wrong here, help is really appreciated
You need to ensure that adapter has been given a value, before you call adapter.startListening on it.
That means that in onStart you need to ensure the adapter exists:
#Override
public void onStart() {
super.onStart();
if (isSignedIn() && adapter != null) {
adapter.startListening();
}
firebaseAuth.addAuthStateListener(this);
}
And then also start listening on the adapter when you create it and the user is signed in. So:
adapter = new FirestoreRecyclerAdapter<User, UsersViewHolder>(options) {
...
});
if (isSignedIn()) {
adapter.startListening();
}
I've created a listView, and since i'm opening one of the item, the application need to fetch all image of the application, but it's doesn't work, i can't figure it out why that's showing me this error.
Thank you for helping !
That's my model on Firebase :
imageSection.java
package com.flashpub.flash;
import java.util.List;
public class imageSection {
String imageUrl;
public imageSection(){
}
public imageSection(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getImageUrl() {
return imageUrl;
}
}
chooseSection.java
package com.flashpub.flash;
import java.util.List;
public class chooseSection {
String sectionn;
public chooseSection() {
}
public chooseSection(String sectionn) {
this.sectionn = sectionn;
}
public String getSectionn() {
return sectionn;
}
}
chooseSectionActivity.java
public class ChooseSectionActivity extends AppCompatActivity {
ListView listView;
FirebaseListAdapter<chooseSection> adapter;
chooseSection sectionChosse;
//private HashMap<Integer, String> allItemsList = new HashMap<Integer, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_section);
listView = findViewById(R.id.listView);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
myRef.keepSynced(true);
Query query = FirebaseDatabase.getInstance().getReference().child("Sections");
Log.i("salut", query.toString());
FirebaseListOptions<chooseSection> options = new FirebaseListOptions.Builder<chooseSection>()
.setLayout(R.layout.section_list)
.setQuery(query,chooseSection.class)
.build();
adapter = new FirebaseListAdapter<chooseSection>(options) {
#Override
protected void populateView(#NonNull View view, #NonNull chooseSection model, int position) {
TextView sectionView = (TextView) view.findViewById(R.id.sectionView);
sectionView.setText(model.getSectionn());
chooseSection lu = sectionChosse;
//String LatLng = lu.getLocationUserLatitude() + "," + lu.getLocationUserLongitude();
//allItemsList.put(position, model.getSectionn());
}
};
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//String item = allItemsList.get(position);
Intent intent = new Intent(ChooseSectionActivity.this, PubsSectionActivity.class);
//intent.putExtra("key", item);
startActivity(intent);
}
});
listView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
PubsSectionActivity.java
public class PubsSectionActivity extends AppCompatActivity {
ViewFlipper viewFlipp;
private DatabaseReference databaseReference;
private List<imageSection> slideLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pubs_section);
viewFlipp = findViewById(R.id.viewFlipper);
databaseReference = FirebaseDatabase.getInstance().getReference();
slideLists = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
usingFirebaseDatabase();
}
private void usingFirebaseDatabase() {
String lolipop = "Coiffeur";
databaseReference.child("Sections/Restaurant")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
slideLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
imageSection model = snapshot.getValue(imageSection.class);
slideLists.add(model);
}
Toast.makeText(PubsSectionActivity.this, "All data fetched", Toast.LENGTH_SHORT).show();
usingFirebaseImages(slideLists);
} else {
Toast.makeText(PubsSectionActivity.this, "No images in firebase", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(PubsSectionActivity.this, "NO images found \n" + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void usingFirebaseImages(List<imageSection> slideLists) {
for (int i = 0; i < slideLists.size(); i++) {
String downloadImageUrl = slideLists.get(i).getImageUrl();
Toast.makeText(this, downloadImageUrl, Toast.LENGTH_LONG).show();
ImageView imageView = new ImageView(this);
Picasso.get().load(downloadImageUrl).fit().centerCrop().into(imageView);
viewFlipp.addView(imageView);
viewFlipp.setInAnimation(this, android.R.anim.slide_in_left);
viewFlipp.setOutAnimation(this, android.R.anim.slide_out_right);
}
}
}
Help me please, i'm stuck !!
i don't know why there is this error...
You're attaching a listener to Sections/Restaurant. Since that is one specific restaurant, you don't need to loop over the children in onDataChange.
So:
databaseReference.child("Sections/Restaurant")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
slideLists.clear();
imageSection model = snapshot.getValue(imageSection.class);
slideLists.add(model);
Toast.makeText(PubsSectionActivity.this, "All data fetched", Toast.LENGTH_SHORT).show();
usingFirebaseImages(slideLists);
} else {
Toast.makeText(PubsSectionActivity.this, "No images in firebase", Toast.LENGTH_SHORT).show();
}
}
I got two RecyclerView on the same page at this moments which are Breakfast and Lunch RecyclerView but I am facing the following error Can't convert object of type java.lang.String to type com.example
It highlights this line
userRecordslist.add(ds.getValue(UserRecordsModel.class));
I have tried several ways.
but when I used this code , the data from different record was displayed in the Breakfast RecyclerView
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record);
these are the screenshots of my Firebase and my App. You can see both data from different record is displayed on the same RecyclerView.
and later I tried to use this "new" code for database reference, the data that was supposedly retrieved from Firebase was NOT be displayed on the Breakfast Recycler View and I got the Can't convert object of type java.lang.String to type error
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("BreakfastRecord");
I want to fetch the data and display it in the "suppose" RecyclerView. Please help out.
This code for my PlanMeal activity:
//BUTTON
Button backBtn;
Button addMealBreakBtn;
Button addMealLunchBtn;
Button addMealDinnerBtn;
//DATABASE
FirebaseAuth mAuth;
FirebaseUser currentUser;
DatabaseReference userRecordRef, myRef,requiredCalorieRef, mylunchRef;
//TEXT VIEW
TextView userRequiredCalorie;
ArrayList<UserRecordsModel> userRecordslist;
RecyclerView recyclerView, recyclerViewlunch;
private RecyclerView.Adapter userRecordHolder;
//DATE
String date_record ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plan_meal_user);
date_record = new SimpleDateFormat("yyMMdd", Locale.getDefault()).format(new Date());
//create a date string.
String date_n = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()).format(new Date());
//get hold of textview.
TextView date = (TextView) findViewById(R.id.datePlanMeal);
//set it as current date.
date.setText(date_n);
//INI VIEWS
userRequiredCalorie= (TextView) findViewById(R.id.outputPlanMealCalorie);
//FIREBASE AUTH
mAuth = FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
//DATABASE REFERENCE
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record);
/*mylunchRef=FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("LunchRecord");*/
//myRef = FirebaseDatabase.getInstance().getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//mylunchRef = FirebaseDatabase.getInstance().getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//RECYCLER VIEW
//*********BREAKFAST******************************************//
recyclerView = findViewById(R.id.userRecordRecylerView);
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
//ADAPTER
userRecordslist = new ArrayList<>();
userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerView.setAdapter(userRecordHolder);
//*********LUNCH******************************************//
recyclerViewlunch = findViewById(R.id.userRecordRecylerViewLunch);
LinearLayoutManager manager1 = new LinearLayoutManager(this);
recyclerViewlunch.setLayoutManager(manager1);
recyclerViewlunch.setHasFixedSize(true);
//ADAPTER
userRecordslist = new ArrayList<>();
userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerViewlunch.setAdapter(userRecordHolder);
//BUTTON
addMealBreakBtn = (Button) findViewById(R.id.addMealBreakBtn);
backBtn = (Button)findViewById(R.id.backBtnPlan) ;
//**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
userRequiredCalorie.setText((userCalorieSuggestion +"kcal"));
/*String userCalorieSuggestion = Double.toString((Double) dataSnapshot.child("daily calorie").getValue());
showDailyCalorie.setText(("Daily Calorie Suggestion: " + userCalorieSuggestion +"kcal"));*/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//BACK BUTTON*************************************************
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,HomepageUser.class);
startActivity(signIn);
}
});
//ADD MEAL BUTTONS**********************************************
addMealBreakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent breakfast = new Intent(PlanMealUser.this,ViewProduct.class);
startActivity(breakfast);
}
});
addMealLunchBtn = (Button) findViewById(R.id.addMealLunchBtn);
addMealLunchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,ViewProduct_Lunch.class);
startActivity(signIn);
}
});
addMealDinnerBtn = (Button) findViewById(R.id.addMealDinnerBtn);
addMealDinnerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,ViewProduct.class);
startActivity(signIn);
}
});
}
#Override
protected void onStart() {
super.onStart();
if (myRef != null) {
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userRecordslist = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userRecordslist.add(ds.getValue(UserRecordsModel.class));
}
UserRecordsHolder userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerView.setAdapter(userRecordHolder);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(PlanMealUser.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
This is my Model :
package com.example.buddymealplanneruser.Child.UserRecords;
public class UserRecordsModel {
private String foodName;
private String foodCalorie;
//constructor
public UserRecordsModel (String foodName,
String foodCalorie
)
{
this.foodName = foodName;
this.foodCalorie = foodCalorie;
}
public UserRecordsModel(){
}
//Getter and Setter
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getFoodCalorie() {
return foodCalorie;
}
public void setFoodCalorie(String foodCalorie) {
this.foodCalorie = foodCalorie;
}
}
This is my Adapter
public class UserRecordsHolder extends RecyclerView.Adapter<UserRecordsHolder.MyURHolder> {
Context context;
ArrayList<UserRecordsModel> userRecordslist;
public UserRecordsHolder (ArrayList<UserRecordsModel> userRecordslist)
{
this.userRecordslist=userRecordslist;
}
#NonNull
#Override
public MyURHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_user_records, viewGroup,false);
return new MyURHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyURHolder myURHolder, int i) {
myURHolder.foodName.setText(userRecordslist.get(i).getFoodName());
myURHolder.foodCalorie.setText(userRecordslist.get(i).getFoodCalorie());
}
#Override
public int getItemCount()
{
return userRecordslist.size();
}
class MyURHolder extends RecyclerView.ViewHolder
{
TextView foodName, foodCalorie;
public MyURHolder (#NonNull View itemView){
super(itemView);
foodName = itemView.findViewById(R.id.userRecordsFName);
foodCalorie = itemView.findViewById(R.id.userRecordsKcal);
}
}
}
Hope someone can help.
You'll need one more level beneath BreakfastRecord or LunchRecord:
UserRecords
UID
Date
BreakfastRecord
1
foodCalorie
foodName
2
foodCalorie
foodName
3
foodCalorie
foodName
I am trying to pass a value from my activity to my fragment but I keep getting this error "attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference". I am not sure why, some help would be greatly appreciated.
Fragment class
public class MessageFragment extends Fragment {
private RecyclerView displayMessagesRecycleView;
private View displayChatListView;
private RecyclerView.LayoutManager layoutManager;
private ChatListAdapter chatListAdapter;
private ArrayList<String> messageList;
private Message message;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
displayChatListView = inflater.inflate(R.layout.display_messages_layout, container, false);
createObjects();
initRecycleView();
populateRecycleView();
return displayChatListView;
}
//set up RecycleVIew/listener to detect taps
public void initRecycleView() {
displayMessagesRecycleView = displayChatListView.findViewById(R.id.chatListRecycleView);
layoutManager = new LinearLayoutManager(getContext());
((LinearLayoutManager) layoutManager).setStackFromEnd(true);
((LinearLayoutManager) layoutManager).setReverseLayout(true);
displayMessagesRecycleView.setLayoutManager(layoutManager);
chatListAdapter = new ChatListAdapter(getActivity(), messageList);
displayMessagesRecycleView.setAdapter(chatListAdapter);
displayMessagesRecycleView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, final int position) {
TextView textView = view.findViewById(R.id.textViewOptions);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("position", "item clicked");
}
});
}
})
);
}
#Override
public void onStart() {
super.onStart();
retreiveBundle();
}
//Instantiate objects
public void createObjects() {
messageList = new ArrayList<>();
}
public void populateRecycleView() {
messageList.add("HEy");
chatListAdapter.notifyDataSetChanged();
}
//retrieves selected user's name and profile pic from message activity and updates profile image and name
public void retreiveBundle() {
String data = getArguments().getString("data");// data whi
}
}
Message Activity
public class MessageActivity extends AppCompatActivity {
private RecyclerView messagesRecycleView;
private String userProfileName;
private String userProfilePic;
private String timeStamp;
private String messageTimeStamp;
private HashMap<String, Object> messageDictionary;
private FirebaseUser currentFirebaseUser;
private TextView userNameTextView;
private CircleImageView userProfilePicture;
private EditText messageInputEditText;
private DatabaseReference firebaseDatabase;
private DatabaseReference messesagesRef;
private DatabaseReference RootRef;
private String id;
private String messageSender, messageReceiver;
private Message messages;
private ArrayList<Message> messageList;
private MessageAdapter messageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
messageList = new ArrayList<>();
initRecycleView();
linkUpViews();
createObjects();
setUpFirebase();
retreiveBundle();
messageSender = currentFirebaseUser.getUid();
messageReceiver = id;
}
#Override
protected void onStart() {
super.onStart();
messageList.clear();
RootRef.child("Messages").child(messageSender).child(messageReceiver).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Message messages = dataSnapshot.getValue(Message.class);
messageList.add(messages);
messageAdapter.notifyDataSetChanged();
}
#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) {
}
});
}
//find views by id
public void linkUpViews() {
userNameTextView = findViewById(R.id.userNameTv);
userProfilePicture = findViewById(R.id.chatProfilePic);
messageInputEditText = findViewById(R.id.chatboxEditText);
}
//set up RecycleView
public void initRecycleView() {
messagesRecycleView = findViewById(R.id.messagesRecycleView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
messagesRecycleView.setLayoutManager(linearLayoutManager);
messageAdapter = new MessageAdapter(MessageActivity.this, messageList);
messagesRecycleView.setAdapter(messageAdapter);
}
//create objects
public void createObjects() {
messageDictionary = new HashMap<>();
//messageList = new ArrayList<>();
}
public void sendMessageButton(View view) {
sendMessages();
//saveMessages();
}
//retrieves selected user's name and profile pic from NewsFeedFragment and updates profile image and name
public void retreiveBundle() {
Bundle bundle = getIntent().getExtras();
userProfileName = bundle.getString("profileName");
userProfilePic = bundle.getString("profilePic");
timeStamp = bundle.getString("timestamp");
id = bundle.getString("id");
Log.i("timestamp", timeStamp);
userNameTextView.setText(userProfileName);
Picasso.get().load(userProfilePic).into(userProfilePicture);
}
//goes back to previous activity
public void backToShop(View view) {
Intent intent = new Intent(MessageActivity.this, MainActivity.class);
startActivity(intent);
}
//Set up Firebase connection
public void setUpFirebase() {
messesagesRef = FirebaseDatabase.getInstance().getReference();
RootRef = FirebaseDatabase.getInstance().getReference();
firebaseDatabase = FirebaseDatabase.getInstance().getReference();
currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
}
//Store messages to Firebase
public void sendMessages() {
if (TextUtils.isEmpty(messageInputEditText.getText().toString())) {
Toast.makeText(this, "Please enter a message", Toast.LENGTH_SHORT).show();
} else {
String messageSenderRef = "Messages/" + messageSender + "/" + messageReceiver;
String messageReceiverRef = "Messages/" + messageReceiver + "/" + messageSender;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSender).child(messageReceiver).push();
String messagePushKey = userMessageKeyRef.getKey();
messageDictionary.put("message", messageInputEditText.getText().toString());
messageDictionary.put("sender", messageSender);
messageDictionary.put("receiver", messageReceiver);
HashMap<String, Object> messageBodyDetails = new HashMap<>();
messageBodyDetails.put(messageSenderRef + "/" + messagePushKey, messageDictionary);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushKey, messageDictionary);
RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
messageInputEditText.setText("");
Toast.makeText(MessageActivity.this, "Sent message...", Toast.LENGTH_SHORT).show();
sendDataToFrag();
} else {
Log.e("Error", task.getException().getMessage().toString());
}
}
});
}
}
//sends data to message fragment...
public void sendDataToFrag(){
Bundle bundle = new Bundle();
bundle.putString("data", "From Activity");
// set Fragmentclass Arguments
MessageFragment fragobj = new MessageFragment();
fragobj.setArguments(bundle);
}
}
This code will work
public class MyFragment extends Fragment {
public static MyFragment newInstance(String data) {
Bundle args = new Bundle();
args.putString("data", data);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
public String getData() {
return getArguments().getString("data");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String data = getData();
return inflater.inflate(R.layout.test, container, false);
}
}
And you Activity must be like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uiView = findViewById(R.id.ui);
uiView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(new Runnable() {
#Override
public void run() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.fragment, MyFragment.newInstance("My Test"));
transaction.commit();
}
}).start();
}
});
}
}
Hello guys iam trying to get Data to putExtra => Intent from an Adapter to another Activity but every time i try to get data from the Adapter to the Activity it Gives me this Exception that
java.lang.String android.content.Context.getPackageName()'
so i tried to Enter the Context class i found it too many Errors cant fix that till now
what makes me really Believe that the problem with the Context is that when i Tried to use TinyDB
it need to define the Object inside the Adapter
tinyDB = new TinyDB(mContext);
the program Crashed and Gives Me this Exception
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
W/System.err: at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4910)
at com.team.plustegara.Views.Models.Adapters.EventsAdapter$1.onClick(EventsAdapter.java:83)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22465)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
i tried to Fix that but still cant handle the Context problem
Here is my Adapter
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsHolder> {
public EventsAdapter(List<EventsModel> list, Context mContext) {
this.list = list;
this.mContext = mContext;
}
private List<EventsModel> list;
private Context mContext;
FirebaseAuth mAuth;
DatabaseReference dbRef;
#NonNull
#Override
public EventsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.events_row_item, parent, false);
EventsHolder holder = new EventsHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final EventsHolder holder, int position) {
final EventsModel listy = list.get(position);
holder.eventTitle.setText(listy.getTitle());
holder.eventDate.setText(listy.getEventDate());
holder.eventCosts.setText("Event Costs " + listy.getCosts());
Picasso.get()
.load(listy.getEventImage())
.fit()
.centerCrop()
.placeholder(R.drawable.gradients_card)
.into(holder.eventImage);
holder.cardViewEvents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(mContext, ShowActivityEvents.class);
intent.putExtra("EventImage", listy.getEventImage());
intent.putExtra("EventTitle", listy.getTitle());
intent.putExtra("EventDate", listy.getEventDate());
intent.putExtra("EventCosts", listy.getCosts());
intent.putExtra("EventDescription", listy.getDescription());
intent.putExtra("eventID", listy.getPostID());
mContext.startActivity(intent);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
String userName = mAuth.getCurrentUser().getDisplayName();
String postID = listy.getPostID();
dbRef.child("Events").child(postID).child("Views").push().setValue(userName);
} catch (Exception e) {
e.printStackTrace();
}
}
});
String postID = listy.getPostID();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("PlusTeam");
databaseReference.child("Events").child(postID).child("Views").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long ViewsCount = dataSnapshot.getChildrenCount();
holder.txtViews.setText(String.valueOf(ViewsCount));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(mContext, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class EventsHolder extends RecyclerView.ViewHolder {
#BindView(R.id.EventImageCard)
ImageView eventImage;
#BindView(R.id.txtEventTitle)
TextView eventTitle;
#BindView(R.id.txtEventDate)
TextView eventDate;
#BindView(R.id.txtEventCosts)
TextView eventCosts;
#BindView(R.id.cardView_EventsCard)
CardView cardViewEvents;
#BindView(R.id.txtEventsViews) TextView txtViews;
public EventsHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
here is my Activity which receive the Extras from the Adapter
public class ShowActivityEvents extends AppCompatActivity {
DatabaseReference dbRef;
FirebaseAuth mAuth;
#Override
protected void onStart() {
super.onStart();
checkIfUserAlreadyAccepttheEvent();
}
private void checkIfUserAlreadyAccepttheEvent() {
final String postID = getIntent().getExtras().getString("eventID");
final String UserID = mAuth.getCurrentUser().getUid();
dbRef.child(postID).child("PeopleComing")
.addListenerForSingleValueEvent(new ValueEventListener() {
public static final String TAG = "ShowEvents";
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildAdded: " + dataSnapshot);
String peopleCount = String.valueOf(dataSnapshot.getChildrenCount());
txtPeopleComing.setText( peopleCount + " People Comming");
if (dataSnapshot.child(UserID).exists()) {
btnIamIn.setEnabled(false);
} else {
btnIamIn.setEnabled(true);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(ShowActivityEvents.this, "Error code : " + 1, Toast.LENGTH_LONG).show();
}
});
}
#BindView(R.id.btnIamIn)
Button btnIamIn;
#BindView(R.id.txtPeopleComingCount)
TextView txtPeopleComing;
#BindView(R.id.imgEventPost)
ImageView imgEvent;
#BindView(R.id.txtEventTitle) TextView txtEventTitle;
#BindView(R.id.txtEventDescription) TextView txtEventDescription;
#BindView(R.id.txtEventCost) TextView txtEventCost;
#BindView(R.id.txtEventDate) TextView txtEventDate;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_events2);
ButterKnife.bind(this);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
try {
loadDataFromAdapter();
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadDataFromAdapter() {
String Image = getIntent().getExtras().getString("EventImage");
String Title = getIntent().getExtras().getString("EventTitle");
String Date = getIntent().getExtras().getString("EventDate");
String Costs = getIntent().getExtras().getString("EventCosts");
String Description = getIntent().getExtras().getString("EventDescription");
GlideApp.with(this)
.load(Image)
.fitCenter()
.into(imgEvent);
txtEventTitle.setText(Title);
txtEventDescription.setText(Description);
txtEventDate.setText(Date);
txtEventCost.setText(Costs);
}
#OnClick(R.id.btnIamIn) public void addPersonToEvent(){
String UserName = mAuth.getCurrentUser().getDisplayName();
String userID = mAuth.getCurrentUser().getUid();
String postID = getIntent().getExtras().getString("eventID");
dbRef.child(postID)
.child("PeopleComing").setValue(UserName);
btnIamIn.setEnabled(false);
}
}
Finally just wanted to say i searched for this kind of Problem in Google and inside questions in Stack but didn't worked
so any Suggestions
You should pass your context in adapter like in the example below
Activity
adapter = new EventsAdapter(myList,MainActivity.this);
Fragment
adapter = new EventsAdapter(myList,getActivity());
Or another way
#Override
public void onClick(View v) {
v.getContext().startActivity(v.getContext(), ShowActivityEvents.class);
}