i'm from indonesia, i want to refresh a fragment after i insert a data to it.. i have try many times to refresh a fragment. but it can't work.
please help me..
here's my code..
class MainActivity
public class MainActivity extends FragmentActivity {
public MainActivity() {
}
DatabaseReference dataBaseref;
StorageReference strRef;
TextView logout;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBaseref = FirebaseDatabase.getInstance().getReference();
strRef = FirebaseStorage.getInstance().getReference();
tabLayout = findViewById(R.id.tab_layout_isi_menu);
viewPager = findViewById(R.id.view_pager_isi_menu);
logout = findViewById(R.id.text_logout);
viewAdapter = new ViewPagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewAdapter.addFragment(new isi_list_beli(), "Beli");
viewAdapter.addFragment(new isi_list_cek(), "Cek Data");
viewPager.setAdapter(viewAdapter);
tabLayout.setupWithViewPager(viewPager);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logOut();
}
});
}
private void logOut() {
AuthUI.getInstance()
.signOut(MainActivity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
}
public void onBackPressed() {
super.finish();
}
}
class isi_list_cek
public class isi_list_cek extends Fragment {
private ListView listView;
public AdapterListCek adapterListCek = null;
private ArrayList<Cek> cekArrayList;
Cursor cursor;
View view;
FloatingActionButton fab;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
adapterListCek.notifyDataSetChanged();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #NonNull Bundle savedInstanceState) {
view = inflater.inflate(R.layout.list_barang, container, false);
listView = view.findViewById(R.id.list_item_barang);
fab = view.findViewById(R.id.tambah_barang);
cekArrayList = new ArrayList<>();
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
listView.setAdapter(adapterListCek);
cursor = fragment_input_data.sqlHelper.getData("SELECT * FROM CEK");
if(cursor.moveToFirst()){
cekArrayList.clear();
do{
int id = cursor.getInt(0);
String kode = cursor.getString(1);
String nama = cursor.getString(2);
String jumlah = cursor.getString(3);
String harga = cursor.getString(4);
byte[] gambar = cursor.getBlob(5);
cekArrayList.add(new Cek(id, kode, nama, harga, jumlah, gambar));
}while (cursor.moveToNext());
fragment_input_data.sqlHelper.close();
}
adapterListCek.notifyDataSetChanged();
listView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
return false;
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), fragment_input_data.class));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
class ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private Context mContext;
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentListTitle = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm, Context mContext) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentListTitle.size();
//return 2;
}
#NonNull
#Override
public CharSequence getPageTitle(int position) {
return fragmentListTitle.get(position);
}
public void addFragment (Fragment fragment, String string){
fragmentList.add(fragment);
fragmentListTitle.add(string);
}
}
i expect when i insert some data, fragment will automatically update it's view.
call a function as: just send the new instance of present fragment that you want to recreate
replaceFragment(new YourPresentFragment());
the function can be as below:
private void replaceFragment(Fragment fragment) {
String fragmentTag = fragment.getClass().getName();
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.fragments, fragment, fragmentTag);
ft.addToBackStack("fragments");
ft.commit();
}
this should do the job
Related
I create an application and use a BottomNavigationView in it and one of the fragments calls the other fragment through the adapter. I am trying to make the BottomNavigationView disappear when this fragment is called, for this I use setVisibility (). But the problem is that it doesn’t disappear, maybe someone can tell me what I’m doing wrong
BottomNavigationView:
public class ProfileFragment extends Fragment {
private ImageView avatar;
private TextView nickname, bio, website;
private FirebaseMethods mFirebaseMethods;
private Context mContext;
private AppBarLayout mAppBarLayout;
private Menu mMenu;
private RecyclerView mRecyclerView;
private FirebaseUser mCurrentUser;
private TextView followers, followings;
private BottomNavigationView mBottomNavigationView;
private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
private ActivityResultContracts.RequestMultiplePermissions mRequestMultiplePermissions= new ActivityResultContracts.RequestMultiplePermissions();
private DatabaseReference mDatabaseReference;
private DatabaseReference followingRef;
private DatabaseReference followersRef;
private ReadWritePermissions mReadWritePermissions;
private IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
private String mParam1;
private String mParam2;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile2, container, false);
mContext = container.getContext();
mFirebaseMethods = new FirebaseMethods(mContext);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mBottomNavigationView = getActivity().findViewById(R.id.bottomNavigation);
followingRef = FirebaseDatabase.getInstance().getReference("Following");
followersRef = FirebaseDatabase.getInstance().getReference("Followers");
Toolbar toolbar = view.findViewById(R.id.toolbar);
mAppBarLayout = view.findViewById(R.id.app_bar);
mRecyclerView = view.findViewById(R.id.posts_recycler);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
loadPosts();
avatar = view.findViewById(R.id.profile_avatar);
nickname = view.findViewById(R.id.profile_nickname);
bio = view.findViewById(R.id.profile_bio);
website = view.findViewById(R.id.profile_website);
followers = view.findViewById(R.id.followers_count);
followings = view.findViewById(R.id.following_count);
setFollowingFollowers();
followers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FollowersFollowingsFragment fragment = new FollowersFollowingsFragment();
Bundle args = new Bundle();
args.putString("uid", mCurrentUser.getUid());
args.putString("followingsOrFollowers", "followers");
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
followings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FollowersFollowingsFragment fragment = new FollowersFollowingsFragment();
Bundle args = new Bundle();
args.putString("uid", mCurrentUser.getUid());
args.putString("followingsOrFollowers", "followers");
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
avatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mFirebaseMethods.getUserDataProfile(avatar, nickname, bio);
return view;
}
private void loadPosts()
{
mReadWritePermissions = new ReadWritePermissions(getActivity().getLifecycle(), getActivity().getActivityResultRegistry());
getLifecycle().addObserver(mReadWritePermissions);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseRecyclerOptions<Posts> options
= new FirebaseRecyclerOptions.Builder<Posts>()
.setQuery(mDatabaseReference.orderByChild("uid").equalTo(mCurrentUser.getUid()), Posts.class)
.build();
mReadWritePermissions = new ReadWritePermissions(getActivity().getLifecycle(), getActivity().getActivityResultRegistry());
getLifecycle().addObserver(mReadWritePermissions);
PostAdapter adapter = new PostAdapter(options, mContext, mReadWritePermissions);
mRecyclerView.setAdapter(adapter);
adapter.startListening();
}
private void setFollowingFollowers()
{
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
followersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followers.setText(Integer.toString((int)snapshot.child(mCurrentUser.getUid()).getChildrenCount()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
followingRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followings.setText(Integer.toString((int)snapshot.child(mCurrentUser.getUid()).getChildrenCount()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
Use setVisibility(View.GONE) instead.
I had the same problem, for some reason it doesn't work, but in the docs they also use View.GONE.
EDIT: Use the method shown in the docs to hide/show BottomNavigationView depending on the Fragment.
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller,
#NonNull NavDestination destination, #Nullable Bundle arguments) {
if(destination.getId() == R.id.full_screen_destination) {
toolbar.setVisibility(View.GONE);
bottomNavigationView.setVisibility(View.GONE);
} else {
toolbar.setVisibility(View.VISIBLE);
bottomNavigationView.setVisibility(View.VISIBLE);
}
}
});
Use Navigation component like in this example.
I fixed this by using DataBinding and ObservableField for the visibility, I don't why it didn't work through the normal onDestinationChangedListener on the NavController, it just bluntly ignored that command, everything else in that block worked fine but not the visibility.
So an ObservableField in the databinding did the trick
android:visibility="#{hideBottomNav ? View.GONE : View.VISIBLE}"
And set the value to the observable field in the onDestinationChangedListener to your desired outcome
if(destination.id == R.id.navigation_your_notes){
hideBottomNav.set(true)
} else hideBottomNav.set(false)
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();
}
When I run the activity it shows me items that I want plus a null card view(when i delete tostring() from holder.setTitle("product name:"+model.getName().toString()); I'm trying so hard to solve this problem but I didn't find a solution.
this is my class Client_order:
public class Client_order extends AppCompatActivity {
FragmentManager fragmentManager;
Fragment Settingsfrag,Orderfrag,panierfrag;
TextView delorder;
Order model2;
Button submit;
DatabaseReference ref,ref1,ref2;
private Toolbar hometoolbar;
private ImageView settingsbtn, orderIV, imageView7,imageView10;
private RecyclerView orderrv;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private DatabaseReference mDatabase;
private String user_id;
Spinner spinnerorder;
private String name;
private String email;
private String phone;
TextView tvName;
Orderviewholder holder1;
private FirebaseRecyclerAdapter<Order, Orderviewholder> orderAdapter;
DatabaseReference dborder,dbpanier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_order);
tvName = findViewById(R.id.tvName);
hometoolbar = findViewById(R.id.hometoolbarorder);
hometoolbar.setTitle("ordre");
hometoolbar.setTitleTextColor(Color.WHITE);
settingsbtn = findViewById(R.id.settingsbtn);
orderIV = findViewById(R.id.orderIV);
imageView7 = findViewById(R.id.imageView7);
fragmentManager=getSupportFragmentManager();
Orderfrag=fragmentManager.findFragmentById(R.id.orderfrag);
Settingsfrag=fragmentManager.findFragmentById(R.id.settingsfrag);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
if (currentUser == null) {
Intent intent=new Intent(Client_order.this,Login.class);
startActivity(intent);
} else {
if (!mAuth.getCurrentUser().isEmailVerified()) {
Toast.makeText(getApplicationContext(), "Please verify your email address", Toast.LENGTH_LONG).show();
Intent startActivity = new Intent(this, Login.class);
startActivity(startActivity);
finish();
} else {
user_id = currentUser.getUid();
}
}
Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_LONG).show();
panierfrag=fragmentManager.findFragmentById(R.id.panierfrag);
submit=findViewById(R.id.submit);
submit.setVisibility(View.VISIBLE);
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
imageView7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Client_order.this,Client_panier.class);
startActivity(intent);
}
});
settingsbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.hide(Orderfrag)
.show(Settingsfrag)
.commit();
}
});
orderIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
}
});
dborder = FirebaseDatabase.getInstance().getReference().child("order");
dborder.keepSynced(true);
orderrv = (RecyclerView) findViewById(R.id.orderrv);
DatabaseReference personsRef = FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
Query personsQuery = personsRef.orderByKey();
orderrv.hasFixedSize();
orderrv.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions personsOptions = new FirebaseRecyclerOptions.Builder<Order>().setQuery(personsQuery, Order.class).build();
orderAdapter=new FirebaseRecyclerAdapter<Order, Orderviewholder>(personsOptions) {
#Override
protected void onBindViewHolder(#NotNull Orderviewholder holder, int position, #NotNull Order model) {
holder.setTitle("product name:"+model.getName().toString());
holder1=holder;
imageView10=holder.mView.findViewById(R.id.imageVieworder);
Picasso.get().load(model.getImage()).into(imageView10, new Callback() {
#Override
public void onSuccess() {
ProgressBar progressbar3;
progressbar3=holder1.mView.findViewById(R.id.progressBar4);
progressbar3.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
}
});
holder.setdesc(model.getDesc().toString());
holder.setprice(model.getPrice());
holder.setquantity(model.getQuantity());
TextView status;
status=holder.mView.findViewById(R.id.statusorder);
status.setText(model.getStatus());
status.setVisibility(View.VISIBLE);
delorder=holder.mView.findViewById(R.id.orderDelbtn);
delorder.setText("done");
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delorder.setVisibility(View.VISIBLE);
}
});
model2=model;
delorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dborder.child(currentUser.getUid()).child(model2.getId()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NotNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Client_order.this, "order deleted successfully", Toast.LENGTH_LONG).show();
}
}
});
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ref=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
ref2=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString()).child("submitted");
ref1=FirebaseDatabase.getInstance().getReference().child("order").child("admin");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
for (DataSnapshot orderSnapshot: dataSnapshot.getChildren()) {
Order category = orderSnapshot.getValue(Order.class);
//if (category!=null){
ref1.child(category.getId()).setValue(category);
Toast.makeText(Client_order.this,"product successfully submitted", Toast.LENGTH_LONG).show();
ref2.child(category.getId()).setValue(category);
ref.child(category.getId()).removeValue();
// }
}
}
#Override
public void onCancelled(#NotNull DatabaseError databaseError) {
}
});
}
});
}
#NotNull
#Override
public Orderviewholder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_list_itemorder, parent, false);
return new Orderviewholder(view);
}
};
orderrv.setAdapter(orderAdapter);
}
#Override
protected void onStart() {
super.onStart();
orderAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
orderAdapter.stopListening();
}
public static class Orderviewholder extends RecyclerView.ViewHolder{
View mView;
public Orderviewholder(View itemView){
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView)mView.findViewById(R.id.order_name);
post_title.setText(title);
}
public void setdesc(String desc) {
TextView post_title = (TextView) mView.findViewById(R.id.order_description);
post_title.setText(desc);
}
public void setprice(int price) {
TextView post_title = (TextView) mView.findViewById(R.id.order_price);
post_title.setText(Integer.toString(price)+" dhs");
}
public void setquantity(int quantity) {
TextView post_title = (TextView) mView.findViewById(R.id.order_quantity);
post_title.setText(Integer.toString(quantity));
}
}
}
it shows me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:207)
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:204)
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 need help with a class trying to figure out how to create a first and last button in a fragment that will jump to the first item in a ViewPager and the last item in a ViewPager I'm a bit lost with how to implement. Here is the fragment.
public class CrimeFragment extends Fragment {
private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
private static final int REQUEST_DATE = 0;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
private Spinner mSpinner;
private Button mFirstButton;
private Button mLastButton;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date =
(Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(
CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(
CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mSpinner = (Spinner) v.findViewById(R.id.crime_severity);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.severity_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
mCrime.setSeverity((String) mSpinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return v;
}
}
Here is the Activity with the ViewPager.
public class CrimePagerActivity extends FragmentActivity{
private static final String EXTRA_CRIME_ID = "com.martin.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.activity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
For the First button Im pretty sure I just need to set item to 0? For last button I need to set item to size - 1 just not sure how to do that.
In your CrimePagerActivity, write two method's to jump to the ViewPager first page and last page.
CrimePagerActivity.java:
public void jumpToFirstPage() {
mViewPager.setCurrentItem(0);
}
public void jumpToLastPage() {
mViewPager.setCurrentItem(mCrimes.size() - 1);
}
Call those method's from mFirstButton and mLastButton click listener method:
CrimeFragment.java:
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToFirstPage();
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToLastPage();
}
});
Hope this will work perfectly.
Ok this was a answer that I was given by the teacher incase anyone is interested.
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(0);
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(CrimeLab.get(getActivity()).getCrimes().size()-1);
}
});
Create two button and on click set
viewPager.setCurrentItem(0); // for top
and
viewPager.setCurrentItem(mCrimes.size()); // for last